@rig-c/play 1.26.0 → 1.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1482 @@
1
+ # @rig-c/play reference
2
+
3
+ The sections below were the README's *Status* and the reference under its
4
+ *Install* (#182), moved here unchanged. A link into the old README lands at the
5
+ same heading in the file this table names:
6
+
7
+ | Old README anchor | Now |
8
+ | --- | --- |
9
+ | `#status` | [Status](#status), below |
10
+ | `#wind-gravity-and-dragging-the-rig` | [Wind, gravity and dragging the rig](#wind-gravity-and-dragging-the-rig), below |
11
+ | `#drawing-your-own-frames` | [Drawing your own frames](#drawing-your-own-frames), below |
12
+ | `#reading-the-pose` | [Reading the pose](#reading-the-pose), below |
13
+ | `#drawing-some-slots-only` | [Drawing some slots only](#drawing-some-slots-only), below |
14
+ | `#attachment-sets-setsjson` | [Attachment sets (`sets.json`)](#attachment-sets-setsjson), below |
15
+ | `#slot-identity-snapshot-slotidentity` | [Slot identity snapshot (`slotIdentity()`)](#slot-identity-snapshot-slotidentity), below |
16
+ | `#several-tracks` | [Several tracks](#several-tracks), below |
17
+ | `#adjusting-bones` | [Adjusting bones](#adjusting-bones), below |
18
+ | `#live-physics-parameters` | [Live physics parameters](#live-physics-parameters), below |
19
+ | `#one-load-several-players` | [One load, several players](#one-load-several-players), below |
20
+ | `#loading-it-yourself` | [Loading it yourself](#loading-it-yourself), below |
21
+ | `#loading-for-the-canvas-mode-only-and-data-regions` | [Loading for the canvas mode only, and `data:` regions](#loading-for-the-canvas-mode-only-and-data-regions), below |
22
+ | `#pages-that-ship-at-another-resolution` | [Pages that ship at another resolution](#pages-that-ship-at-another-resolution), below |
23
+ | `#premultiplied-pages-pma` | [Premultiplied pages (`pma`)](#premultiplied-pages-pma), below |
24
+ | `#what-unloading-frees` | [What unloading frees](#what-unloading-frees), below |
25
+ | `#one-part-per-page` | [One part per page](#one-part-per-page), below |
26
+ | `#runtime-knobs-and-what-they-cost` | [Runtime knobs and what they cost](#runtime-knobs-and-what-they-cost), below |
27
+ | `#coming-from-18-meshes-draw-through-webgl-by-default` | [MIGRATION.md](MIGRATION.md#coming-from-18-meshes-draw-through-webgl-by-default) |
28
+ | `#coming-from-spine-html-08`, `#08--10`, `#no-counterpart-in-100`, `#before-and-after` | [MIGRATION.md](MIGRATION.md#coming-from-spine-html-08) |
29
+ | `#tests`, `#independent-official-raster-oracle` | [TESTING.md](https://github.com/rig-c/play/blob/main/docs/TESTING.md) |
30
+ | `#benchmark-dom-canvas-and-official-webgl` | [BENCHMARK.md](https://github.com/rig-c/play/blob/main/docs/BENCHMARK.md#benchmark-dom-canvas-and-official-webgl) |
31
+
32
+ *Measured*, *Install*, *A minimal page*, *Demo (this repository)*, *How it
33
+ works* and *License* stay in the [README](../README.md).
34
+
35
+ ## Status
36
+
37
+ **Production.** The questions this started as a PoC to answer — how far does the
38
+ DOM actually go, and how cheap is it — are answered with on-device numbers: the
39
+ practical scenario (a character or two, mostly holding pose, a few parts
40
+ deforming) holds **60 fps on every engine measured**, and the 10-skeleton
41
+ stress scene holds 45 fps on the weakest one (Safari, webgl backend). Ships
42
+ with a self-contained test suite (backend visual parity + invariants) and CI.
43
+
44
+ **Two render modes.** `mode: 'dom'` (the default, everything below) draws a rig
45
+ as elements. `mode: 'canvas'` draws the whole frame into **one `<canvas>`** per
46
+ player: every slot as textured triangles from its atlas page through the same
47
+ shared WebGL context the mesh tier's `webgl` backend uses, into one rect, then
48
+ one `drawImage` onto the player's canvas. Tint and dark (two-colour) tint are
49
+ vertex colours, blend modes are batch state, clips are cut on the CPU by
50
+ `@rig-c/core/core`'s clipper — no `clip-path`, no SVG filter, no per-slot element.
51
+ `RigPlayer` swaps between the two in place (`player.mode = 'canvas'`). The
52
+ canvas mode is held against the DOM tier pixel for pixel on the parity suite's
53
+ frozen poses (bad pixels ≤ 1.6% of drawn content, measured, macOS Chromium and
54
+ WebKit); which mode is faster where is **not measured on a device yet**, so the
55
+ default stays `dom`.
56
+
57
+ - ✅ Region attachments (rigid parts): exact affine mapping, draw-order via `z-index`,
58
+ attachment swaps, alpha
59
+ - ✅ Atlas unpacking at load time (90°-packed regions restored to the orientation
60
+ the region's UVs name, held against hand-written UVs on a rigc build whose region
61
+ is packed turned),
62
+ so the rigid per-frame path never touches a canvas — a region that covers its whole
63
+ page is passed through uncut, and `revokeRegions()` frees the rest when a skeleton
64
+ is unloaded
65
+ - ✅ Mesh attachments (deform tier): small per-part canvases sized to the mesh's world
66
+ bounds, interleaved with the rigid `<img>` slots in one stacking context — the DOM
67
+ handles the bones, a rasterizer handles the warps
68
+ - ✅ Blend modes via `mix-blend-mode` (additive = `plus-lighter`)
69
+ - ✅ Crack-free mesh seams on the canvas2d backend: canvas2d antialiases each
70
+ triangle's clip edge, so two triangles sharing an edge each leave it partly
71
+ transparent and the background shows through as a hairline — plainest over a
72
+ light background behind light art (#104). Each edge of a triangle's clip
73
+ polygon is moved 0.5px outward along its own normal so neighbours overlap —
74
+ the texture is continuous across shared edges, so the overlap is invisible
75
+ (`?expand=0` shows the cracks for comparison)
76
+ - ✅ RGB tinting (skeleton × slot × attachment color) via an SVG `feColorMatrix`
77
+ reference filter per element — an exact channel multiply that works identically on
78
+ `<img>` and `<canvas>` without touching the raster (needs reference-filter support,
79
+ Safari 15+; verified pixel-level on Chromium and WebKit). Dark/two-color tint is
80
+ not expressible this way and stays out of scope
81
+ - ✅ DPR-aware mesh canvas backing store: `renderer.pixelRatio` (defaults to
82
+ `devicePixelRatio`; if you scale the root element, fold that scale in)
83
+ - ✅ Dirty-skip: a mesh whose canvas-space vertices match the last raster reuses it;
84
+ whole-pixel translations allow at most half a Float32 ULP at the current world
85
+ coordinate, strictly less than half a pixel. CSS still tracks the translation, while
86
+ stationary axes stay exact and the comparison anchor changes only on a redraw.
87
+ 10 frozen spineboys: WebKit ~141 → ~0.5 ms/frame
88
+ - ✅ Clipping attachments as element-level CSS `clip-path`: spine-core's semantics
89
+ (one active clip at a time, applied from the clip's slot through its end slot
90
+ inclusive), with the polygon expressed in each element's own local frame — the
91
+ inverse of the `<img>` matrix for rigid slots, the canvas translate for mesh
92
+ slots. Covers **part masks** (a clip with a real end slot, like the figure test
93
+ rig's `mask` animation) and **whole-skeleton clips** (an end slot that never
94
+ arrives, which takes a fast path: one `clip-path` on the root instead of one per
95
+ element). **Inverse clips** are supported too: the region they keep has a hole
96
+ in it, so it needs two rings, and `polygon()` carries only one — a box and a
97
+ polygon listed inside one `polygon()` become a single self-intersecting ring
98
+ whose even-odd fill leaves a wedge along the seam between them (measured, on a
99
+ corner of spineboy's boot). So an inverse clip is written as a two-subpath
100
+ `path(evenodd, …)` whose outer ring is the element's own box. The whole feature
101
+ is element-level, so both mesh backends see the same thing and neither raster
102
+ path knows clipping exists; `renderer.clipping = false`
103
+ restores the old counted-and-skipped behaviour. Concave polygons go to CSS as
104
+ authored — the convex decomposition spine's CPU clipper performs exists to feed a
105
+ triangle rasterizer and has no job here. Two things this does not do: Spine's
106
+ clipper convexifies an *inverse* polygon (convex hull) where CSS clips it as
107
+ authored, so the two agree exactly when that polygon is convex — which is the
108
+ shape `inverse` is meant for; and the cost of many simultaneous `clip-path`s on
109
+ real-device Safari is **not measured** (the headless numbers that exist are not
110
+ Safari evidence — see Measured above)
111
+ - ✅ Safari mesh cost root-caused by on-device triangulation (two corrections deep):
112
+ the early "~15× slower per-triangle path" was a **headless-WebKit artifact**
113
+ (software rasterization), and the follow-up "on par with Chromium" held only for
114
+ in-callback JS time. Real-Safari rAF rates — rigid ×10 = 60 fps, meshed ×1 =
115
+ 37 fps, meshed ×10 = 3–4 fps with JS flat at ~4–5 ms — put the real cost in the
116
+ GPU process: Safari antialiases canvas2d **clip paths**, so the per-triangle clip
117
+ mapping pays a per-triangle AA-mask tax (the same AA that caused the seam cracks)
118
+ - ✅ WebGL blit backend for the mesh tier, the default since 1.9 (#109;
119
+ `renderer.meshBackend = 'canvas2d'` keeps the 2d raster). All dirty meshes are shelf-packed into
120
+ **one shared offscreen WebGL context** (module-level — browsers cap contexts at
121
+ ~16), drawn as textured triangles with premultiplied alpha, then rect-blitted
122
+ onto the same per-part canvases with an unclipped `drawImage` — cheap on Safari.
123
+ Everything element-level is unchanged: z-index interleave, tint filter,
124
+ `mix-blend-mode`, dirty-skip, grow-only backing. GL rasterizes shared triangle
125
+ edges seamlessly, so this path needs no crack overdraw. Falls back to canvas2d
126
+ only when WebGL is unavailable or the context is lost. A batch larger than the
127
+ buffer the browser grants — a zoomed-in stage can ask for one, and Chromium
128
+ caps the area (rig-c/review#332) — is drawn in passes through the granted
129
+ buffer, and a part larger than it in tiles, each rastered in its own part's
130
+ rect (#245). Every such frame stays on WebGL on every engine tested. On
131
+ Chromium the pixels are the single-pass draw's, held at 0 in both modes; WebKit
132
+ rasterizes a job differently at different buffer positions, so there passes
133
+ and tiles can differ from one pass (measured 0–6,130 px a frame across macOS
134
+ and Linux, up to 51 levels on macOS where the level was read), and that is
135
+ reported rather than held. Backend parity verified by
136
+ headless Chromium+WebKit screenshot diffs (glow / clipping / tint scenes;
137
+ sub-pixel edge differences only). On-device Safari, meshed ×10 with every mesh
138
+ redrawn per frame: **3–4 fps (canvas2d) → 45 fps (webgl)**
139
+
140
+ ### Wind, gravity and dragging the rig
141
+
142
+ A rig's physics links answer the world the page sets (#121). `environment()`
143
+ gives them spine-core's skeleton-level wind and gravity — x right, **y down**,
144
+ the runtime's axes; each constraint's authored `wind` / `gravity` is its
145
+ response, so a link stating `wind: 0` feels none — and `moved()` tells them the
146
+ page moved or turned the rig, in the skeleton's world (y up), so a dragged rig
147
+ trails its cloth. Both apply from the next step, at any time. Added to the
148
+ minimal page above:
149
+
150
+ ```ts
151
+ // A wind slider, -1 (left) to 1 (right). The runtime starts at wind [1, 0], so set calm first.
152
+ const wind = stage.appendChild(Object.assign(document.createElement('input'),
153
+ { type: 'range', min: '-1', max: '1', step: '0.01', value: '0' }));
154
+ player.environment({ wind: [0, 0] });
155
+ wind.addEventListener('input', () => player.environment({ wind: [Number(wind.value), 0] }));
156
+
157
+ // Drag the rig: move the root, and tell the physics how far, in world units with y up.
158
+ let held = null; // the pointer's position while a drag is held
159
+ stage.addEventListener('pointerdown', (e) => { if (e.target !== wind) held = { x: e.clientX, y: e.clientY }; });
160
+ addEventListener('pointerup', () => { held = null; });
161
+ stage.addEventListener('pointermove', (e) => {
162
+ if (!held) return;
163
+ const dx = e.clientX - held.x, dy = e.clientY - held.y;
164
+ held = { x: e.clientX, y: e.clientY };
165
+ root.style.left = `${parseFloat(root.style.left) + dx}px`;
166
+ root.style.top = `${parseFloat(root.style.top) + dy}px`;
167
+ player.moved({ x: dx / scale, y: -dy / scale });
168
+ });
169
+ ```
170
+
171
+ The block is plain JavaScript, so it runs inside the page as written.
172
+ `environment(null)` returns to the runtime's start values, and `environment()`
173
+ reads the standing environment, which every track and layer shares. The player
174
+ keeps only its current environment. A plain `seek(time)` replays under those
175
+ values, and `seek(time, environmentAt)` can supply wind and gravity for that
176
+ replay. A rig with no physics shows no effect from wind, gravity or `moved()`.
177
+ `tests/readme-page.spec.ts` runs this block in the minimal page.
178
+
179
+ **Moving only some physics (`physicsMoved`)**. When an external/deform-only
180
+ head turn moves the artwork without moving its hair-root bones, provide the
181
+ additional apparent world displacement only to the intended physics:
182
+
183
+ ```ts
184
+ player.physicsMoved({ subtree: 'head' }, { translation: { x: dx, y: dy } });
185
+ player.physicsMoved({ bone: 'hair_root' }, { rotation: { degrees: rollDelta, pivot: [px, py] } });
186
+ player.physicsMoved({ constraints: ['hair_left', 'hair_right'] }, { translation: { x: dx, y: 0 } });
187
+ ```
188
+
189
+ `bone` selects constraints whose owner is exactly that bone; `subtree` includes
190
+ that bone and all descendants; `constraints` selects exact physics constraint
191
+ names (repeats apply once). Rotation always names its world pivot. Distances
192
+ are skeleton world units, x right/y up; rotation is degrees CCW in the XY plane.
193
+ Yaw/pitch are not roll: derive projected displacement from the producer's actual
194
+ geometry/depth and supply its change since the preceding sample. No automatic
195
+ gain, force conversion or dt multiplier is applied. If the bones already make
196
+ that displacement, do not send it again. Use `moved()` for movement of the whole
197
+ rig/display object, including its existing rotation about the skeleton origin.
198
+
199
+ The complete scope and motion are validated before any state changes. Unknown
200
+ bones (even before `play`), unknown/non-physics constraints, extra fields,
201
+ ambiguous variants and non-finite numbers refuse by name. Valid calls before
202
+ play have no state to move; an empty selection or valid zero motion is an exact
203
+ no-op. The call changes selected remembered origins synchronously, leaving the
204
+ held pose, generation and rendered picture alone until evaluation; it does not
205
+ rotate remembered tip direction or inject angular velocity. An origin exactly
206
+ at a rotation pivot has zero displacement.
207
+
208
+ Call immediately before `advance`/`frame`. Explicit `repose()`/`step(0)` may
209
+ consume input; reset/first activation may overwrite it. Pause/zero advance does
210
+ not evaluate; a held advance (`hold`) does. Seek, skin replay and promotion to composed tracks do not replay
211
+ external motion history; use `tracks: true` from the start when composing.
212
+ No unselected state is written by this input. Independent chains stay identical
213
+ to a matched no-input baseline after stepping; normal descendant/constraint
214
+ coupling still applies. Both renderer modes use the same posing path.
215
+
216
+ A head-local input agrees with native bone motion up to floating-point
217
+ reassociation, which the physics solver can amplify by stepping; it is not
218
+ bit-for-bit, and the acceptance cap in the test is empirical for its fixture,
219
+ not a bound on every rig. The fixture's peak cap is `F * ulp(nativePeak)`,
220
+ with the actual rotational integration count `F` taken up to the earliest peak
221
+ frame of a fresh native run. It is frozen before the scoped comparison. The
222
+ coordinatewise maximum difference is reported separately, without that gate.
223
+
224
+ The demo's `wind.html` is the same thing with controls: wind and gravity
225
+ sliders, a drag on the stage, and the rig named by `?model=` (the `cloth` test
226
+ rig by default; `bun run dev`, then `/wind.html?model=rigs/<name>/skeleton.model.json`).
227
+ `tests/wind-page.spec.ts` holds it.
228
+
229
+ The player owns one track: `play(name, { loop })` opens an animation at its first
230
+ pose, `frame(dt)` steps it (or `advance(dt)` then `draw()`, to time the two
231
+ apart), `pause()` / `resume()` hold and release it, `timeScale` scales every
232
+ step, and `seek(t)` moves it to a time. A seek is "reopen, then step to the
233
+ time" in `seekStep` increments (1/60 s by default) — never a jump, because a
234
+ physics rig has history and its pose at a time depends on the steps that
235
+ reached it. The physics integrates on rig-c's render clock (`physicsClockStep`:
236
+ each step and 2⁻³⁰ of it more), so stepping at a fixed rate — `frame(1/60)`, a
237
+ capture, a test — shows no single-frame spring jump where a frame ends on a
238
+ physics step; the animation, the events and `time` stay on the steps (#103). `on('event', …)` receives the event keys each step crosses, in the
239
+ runtime's order across a loop's wrap; `on('complete', …)` fires once a step
240
+ completes a cycle. `skin` (a constructor option) poses under a named skin;
241
+ without it the rig is posed the way a fresh Spine skeleton is, with no skin
242
+ set. `player.color` multiplies a whole-rig colour into every slot's tint.
243
+ `player.renderer` is the `DomRenderer` underneath, whose knobs and counters
244
+ are below.
245
+
246
+ **Seeking with changing wind and gravity** (#265). The optional second argument
247
+ to `seek(time, environmentAt)` is a `RigEnvironmentSchedule`, exported from
248
+ `@rig-c/play`.
249
+
250
+ ```ts
251
+ import type { RigEnvironmentSchedule } from '@rig-c/play';
252
+
253
+ const gust: RigEnvironmentSchedule = (replayTime) => ({
254
+ wind: replayTime < 0.5 ? [0, 0] : [1, 0],
255
+ gravity: [0, 1],
256
+ });
257
+ player.seek(1.25, gust);
258
+ ```
259
+
260
+ On the oracle poser, the player opens the animation at pose zero and calls the
261
+ schedule once before each positive replay step, including any shorter final
262
+ step. The callback receives the stepper's unwrapped track time in seconds,
263
+ independent of `timeScale`, animation wrapping and the physics clock. The first
264
+ step is sampled at `0`. Seeking to zero takes the initial pose with no callback.
265
+ Return both `wind` and `gravity` as finite `[x, y]` pairs with x right and y down.
266
+ Use the callback to supply values from replay time and keep player mutations
267
+ outside it.
268
+
269
+ Each scheduled seek rebuilds the physics from pose zero. Past movement calls
270
+ and held steps belong to the prior live run. Ordinary seek snapshots stay
271
+ available for later `seek(time)` calls. After a successful replay, the player
272
+ holds the resulting pose and integrated physics state. `environment()` still
273
+ reports the standing values, which the next live step uses. If the callback
274
+ throws or the core refuses the replay, the error propagates and the player keeps
275
+ its previous pose, time and environment. A successful seek lands a set ease in
276
+ flight, keeps pause or hold, and suppresses replay events and completions.
277
+
278
+ The schedule works on the oracle's single track and with `tracks: true` before
279
+ composition. The same composition restrictions apply as for plain seeks. The
280
+ runtime poser has no physics. It seeks as usual and skips the callback.
281
+
282
+ **Physics on a held frame (`hold`)**. `pause()` stops the physics with the
283
+ clip; `hold(true)` stops only the clip (#248). While held, `advance(dt)` and
284
+ `frame(dt)` move the physics clock by `dt × timeScale` and re-pose at the same
285
+ track time, so a paused or stopped rig settles and stays alive:
286
+
287
+ ```ts
288
+ pauseButton.onclick = () => player.hold(!player.held); // the frame loop keeps calling player.frame(dt)
289
+ ```
290
+
291
+ Every animation timeline reads what it read — bone keys, slot colour,
292
+ attachments, deform, draw order — and only what physics drives moves. `time`
293
+ stands, no event or complete fires, and an eased set switch holds where it is.
294
+ `hold(false)` resumes from the physics state the held steps left, with no reset.
295
+ A held step is the core's zero step on a clock that moves the held step, so it
296
+ equals an `@rig-c/core/core` track given those steps. A rig with no physics constraint
297
+ ignores held steps: nothing is re-posed and the generation stands. `pause()`
298
+ still stops everything, held or not. `play` releases the hold, as it releases a
299
+ pause; `seek` keeps it and replays as it always does. `moved()` and
300
+ `physicsMoved` given while held apply on the next held step. A mode rather than
301
+ an `advance` option, so the caller's frame loop stays one `frame(dt)` call. The
302
+ bars and their planted controls are in `tests/held-clock.spec.ts`, on the
303
+ `held` test rig.
304
+
305
+ **What it refuses, by name.** A Spine export (`.json`, `.skel`) is refused
306
+ before anything is fetched: this package reads compiled models and nothing
307
+ else. A document whose `spec` is not one `@rig-c/core/core` reads is refused with the
308
+ core's own sentence plus "build it with `rigc build`", and so is a
309
+ `rigc-compiled/1` document, which predates the `pages` section.
310
+
311
+ `@rig-c/play` is a third-party renderer and is not affiliated with or endorsed by
312
+ Esoteric Software.
313
+
314
+ ### Drawing your own frames
315
+
316
+ `RigPlayer` is the convenient path; the renderer underneath takes a plain
317
+ record, so anything that can produce one can draw through it:
318
+
319
+ ```ts
320
+ import { DomRenderer, type PosedFrame } from '@rig-c/play';
321
+
322
+ const renderer = new DomRenderer(rootElement, assets.regionImages, assets.pageImages);
323
+ renderer.render(frame); // frame: PosedFrame
324
+ ```
325
+
326
+ ```ts
327
+ PosedFrame { order: PosedSlot[] } // the slots that draw, in draw order
328
+ PosedSlot = { slot; z; blend: 'Normal'|'Additive'|'Multiply'|'Screen';
329
+ tint: [r, g, b, a]; dark?: [r, g, b];
330
+ clip?: { polygon: number[]; inverse: boolean; convex: boolean } } // world space, Y up
331
+ & ( { kind: 'region'; region: string; corners: number[] /* BL, UL, UR, BR */;
332
+ page: string; pma: boolean; uvs: number[] /* page UVs at the corners */ }
333
+ | { kind: 'mesh'; page: string; pma: boolean; vertices: number[];
334
+ uvs: number[]; triangles: number[]; sequence: number } )
335
+ ```
336
+
337
+ `player.posedFrame()` returns the record the player would draw. Two things the
338
+ renderer reads off it by identity rather than by value: every slot a clip
339
+ covers carries the **same** `clip` object (one that covers every slot of the
340
+ frame takes the one-`clip-path`-on-the-root path), and a mesh's `uvs` and
341
+ `triangles` are the same arrays from frame to frame for the same texture
342
+ mapping (a new array re-rasters the mesh).
343
+
344
+ ### Borrowing a live frame
345
+
346
+ `player.liveFrame()` borrows the current draw buffers until the next pose mutation
347
+ (`advance`, `play`, `seek`, `repose`, a set/skin/filter change, or disposal).
348
+ A colour refresh that overwrites borrowed tint data also invalidates checked leases.
349
+ `player.poser` reads `"runtime"` for a covered active animation, or
350
+ `"oracle: <reason>"` naming a missing model/animation feature or an operation
351
+ that needs the oracle. Covered event keys are delivered to the same listeners, in the same order and
352
+ with the same payload shape as the oracle. Re-entrant listeners keep the rest
353
+ of the current delivery batch. Event keys are not silently ignored. A mixed track,
354
+ local adjustment or attachment-set operation continues on the oracle when the
355
+ runtime cannot execute it. `new RigPlayer(root, assets, { poser: 'oracle' })`
356
+ selects that reference path explicitly.
357
+
358
+ The bundled runtime reads animated dark colour, draw order (including each
359
+ slot's full-order `z`) and clipping polygons from the core's live buffers.
360
+ Covered slots share one borrowed clip object; detached snapshots copy its
361
+ polygon while preserving that sharing within the snapshot. Filtering a clip's
362
+ own slot suppresses its effect, just as on the oracle path.
363
+
364
+ Models containing a physics constraint stay on the oracle with a named
365
+ `physics constraint "…" requires player clock, seek and movement integration`
366
+ reason. The player's nonloop clamp, seek replay and movement APIs continue to
367
+ use that existing path. Track composition, local adjustment, attachment sets,
368
+ set easing and environment configuration also retain their oracle policies.
369
+
370
+ ```ts
371
+ player.advance(dt);
372
+ const live = player.liveFrame();
373
+ renderer.render(live); // DomRenderer and CanvasRenderer accept both frame forms
374
+ for (let i = 0; i < live.count; i++) {
375
+ const attachment = live.attachments[live.drawOrder[i]];
376
+ // World x/y pairs: live.vertices[attachment.offset .. offset + count).
377
+ // Final RGBA: live.tint[attachment.slotIndex * 4 .. + 4).
378
+ // attachment.uvs, triangles, page, pma, blend, dark and clip describe the draw.
379
+ }
380
+ ```
381
+
382
+ `drawOrder[0..count)` contains attachment indices. The remaining buffer capacity
383
+ is not a draw list. `LiveNumbers` exposes read-only indexed values and length,
384
+ not writable backing storage. Runtime attachment metadata includes the exact
385
+ `skin` and `placeholder` table identity; `attachment` is the display name and
386
+ need not be unique. On the oracle fallback `placeholder` is explicitly `null`,
387
+ because its snapshot does not expose that table key. `slotIndex` always means
388
+ the setup slot index, not the index among visible draws.
389
+
390
+ The runtime preallocates its production buffers and render view. Development
391
+ builds add generation-capturing leases: reading a held frame **or a retained
392
+ nested buffer** after mutation throws `LIVE_FRAME_STALE`; drawing a stale lease
393
+ also refuses before touching the renderer. Writes and backing-storage escape
394
+ routes refuse as `LIVE_FRAME_READONLY`. `liveFrameChecks` can explicitly select
395
+ this diagnostic behavior. Those leases allocate; they are reported separately
396
+ from the production allocation measurement. Listener delivery creates the same
397
+ detached callback payloads as the oracle and is measured separately; the
398
+ no-listener advance/liveFrame path reuses event records and frame buffers. The oracle fallback packs a borrowed
399
+ view from its snapshot and also carries no zero-allocation promise.
400
+
401
+ Supported skin changes rebuild the view and preserve accumulated track time
402
+ and its wrapped animation time. A held checked live view becomes stale; retained
403
+ snapshots keep their old values. Unsupported views still name the oracle fallback.
404
+
405
+ A production borrowed view is reused and overwritten: keeping its object does
406
+ not keep its values or its old generation. Use `player.posedFrame()` for a
407
+ detached snapshot that survives later steps, including when the runtime is
408
+ selected. Existing `posedFrame(slots)` filtering and `slotIdentity()` generation
409
+ coherence remain available. Bone/identity readback can perform an on-demand
410
+ oracle read; it is not part of the runtime advance/live-frame allocation path.
411
+ The core runtime entry is experimental and the bundled core version is pinned
412
+ exactly; consumers of this package need no separate core installation.
413
+
414
+ ### Reading the pose
415
+
416
+ Two reads off the pose the player holds — the last `frame`/`advance`/`seek`,
417
+ or the setup pose before `play` — for framing a stage around a rig:
418
+
419
+ ```ts
420
+ const head = player.bone('head'); // { x, y, a, b, c, d, rotationX, rotationY, scaleX, scaleY, active }
421
+ const box = player.bounds(); // { x, y, width, height } | null — world units, Y up
422
+ ```
423
+
424
+ `bone` is the core's world transform for that bone (`@rig-c/core/core`'s `RawBone`,
425
+ unchanged), and an unknown name is refused by name. `bounds` is the box of
426
+ every region's four corners and every mesh's vertices in the frame record the
427
+ renderer takes; a slot under a clip counts only inside the clip polygon's own
428
+ box, an inverse clip removes nothing, and bounding boxes, paths and points do
429
+ not draw and do not count. Both cost nothing until called and read the same
430
+ numbers in `dom` and `canvas` mode.
431
+
432
+ `readSetupMesh` reads a named mesh from loaded assets before or during playback,
433
+ including an attachment the setup pose does not select:
434
+
435
+ ```ts
436
+ import { readSetupMesh } from '@rig-c/play';
437
+
438
+ const mesh = readSetupMesh(assets, { slot: 'flag', attachment: 'alternate' });
439
+ // mesh: { slot, attachment, skin, vertices, triangles, hull }
440
+ // vertices: flat world x,y pairs, Y up; hull counts vertices, or is null.
441
+ ```
442
+
443
+ Names are exact slot names and attachment table keys, not display names or atlas
444
+ regions. Omitted or `null` skin means no skin set, as for a fresh player. A named
445
+ `skin` uses that skin's activation lists with default-table fallback; the returned
446
+ `skin` names the supplying table. `skin: 'all'` uses all activation lists and
447
+ refuses differing definitions rather than guessing a merge order. Linked meshes
448
+ retain the requested identity and borrow source topology/bindings; unweighted
449
+ vertices use the queried slot's bone. Inactive bones retain core's zero matrix.
450
+ The result and its arrays are detached and mutable. Missing slot/attachment/skin,
451
+ non-mesh and ambiguous targets throw core's named `CoreInputError` messages;
452
+ setup/non-finite refusals propagate unchanged. The read creates no player and
453
+ changes no document, existing player, time, generation or rendered frame.
454
+
455
+ **Setup-slider boundary (core 2.66.0):** selected meshes include setup-slider
456
+ deform, exactly as core's setup pose does. Unselected meshes use stored geometry
457
+ through the same setup constraint/reset-physics matrices, without switching the
458
+ attachment or borrowing another selection's deform. Core measured **four of six
459
+ nonselected official-runtime comparisons differing by up to
460
+ `2.9999999999999982` world units (about 3.0)**: spine-core 4.3.13's
461
+ `computeWorldVertices` borrows the selected slot's deform, including for a linked
462
+ mesh with `timelines: false`. The other two nonselected calls and all three
463
+ selected reads agree exactly. This wrapper passes core's output through; it does
464
+ not correct or round it. Stored-only formula comparisons therefore have a
465
+ different domain from selected geometry with setup deform. See
466
+ [core AUTHORING §14, including S1538_09](https://github.com/rig-c/core/blob/v2.66.0/docs/AUTHORING.md#14-read-a-named-mesh-at-setup).
467
+
468
+ ### Pointer camera for a composed take
469
+
470
+ Open `composed-parallax.html` in the demo to inspect the public Create rehearsal.
471
+ The page starts in Fixed. Use `?camera=parallax` or `?camera=pan` to opt in, and
472
+ `?fixture=original|overscan|clip` to choose the source variant. The default is
473
+ `overscan`. Use `?time=2` to hold the pose at two seconds while keeping the camera
474
+ interactive. The readouts separate camera excursion from each plane's shift
475
+ and show the requested maximum even when a mode is refused.
476
+
477
+ Select **Automatic and pointer** (or add `?motion=handoff&camera=parallax`)
478
+ to try the handoff on the same public fixtures. Move into the stage to acquire
479
+ pointer control, then leave to return to the automatic motion. The demo uses a
480
+ 120 ms handoff in each direction and a 12-second horizontal sine sweep with a
481
+ 24 CSS px camera excursion before plane gains. The pose-hold control also holds
482
+ the sweep's phase. The original plate has zero overscan, so use the overscan
483
+ fixture for the moving camera.
484
+
485
+ #### Mounting a composed take
486
+
487
+ Import `mountComposedTake` from `@rig-c/play/composed-take`. Serve the take's
488
+ `skeleton.model.json` and its named page images. The compiled model needs a
489
+ positive stage and a named animation with a positive duration. Give the browser
490
+ root a CSS width and height for the stage. Cross-origin page images must allow
491
+ anonymous CORS so the renderer can read back canvas pixels.
492
+
493
+ ```ts
494
+ import { mountComposedTake } from '@rig-c/play/composed-take';
495
+
496
+ const take = await mountComposedTake(viewport, {
497
+ modelUrl: '/take/skeleton.model.json',
498
+ animation: 'idle',
499
+ loop: true,
500
+ planes: {
501
+ backdrop: { slots: ['backdrop'], role: 'backdrop' },
502
+ figure: { slots: ['actor:body'], role: 'figure' },
503
+ overlay: { slots: ['overlay'], role: 'overlay', gain: 0.55 },
504
+ },
505
+ });
506
+
507
+ // On unmount, call take.dispose().
508
+ ```
509
+
510
+ Name the planes in `planes` and assign each drawable slot once by its exact
511
+ compiled name. Give the take one `backdrop`, one `figure` and any number of
512
+ `overlay` planes. Each plate binds one rigid region slot. The figure binds
513
+ its drawable slots. The mount preserves the player's draw order, moves geometry
514
+ and clips with their plane, and crops at the model's fixed stage.
515
+
516
+ The returned `MountedTake` owns the mounted canvas, player, loaded assets,
517
+ coverage renderer, pointer listeners and resize observer. Use `take.canvas`
518
+ for accessibility attributes and `take.player` for pose inspection and
519
+ playback controls such as `seek()` and `pause()`. Let the take control drawing
520
+ and its dial adjustment hook. Call `take.dispose()` to cancel its frame clock,
521
+ remove the mounted surface and release its resources. The caller owns the root.
522
+
523
+ #### Authored scene camera
524
+
525
+ Set `sceneReportUrl` to the Parts `scene.json` and `modelUrl` to the exact
526
+ packed `check/build/skeleton.model.json` named by that report. Play checks
527
+ the SHA-256 of the fetched model bytes for `spine-parts-scene-report/2`.
528
+ Serve a keyed mount from a secure context, such as HTTPS or localhost, so the
529
+ browser can use Web Crypto to verify those bytes.
530
+ A keyed take uses the report's loop flag, which must agree with the mount's
531
+ `loop` option. The camera follows the pose through playback, pause, seek and
532
+ repeat, including curved and stepped keys between the report's coverage
533
+ samples. Play trusts Parts' coverage for the authored window. When a pointer
534
+ mode is selected, Play checks that the backdrop quad at every reported frame
535
+ can cover the window across the mode's maximum CSS displacement, including
536
+ any automatic sweep. Extra displacement must leave a guard of one backing
537
+ pixel on each axis, projected onto the backdrop edges using the actual
538
+ rounded backing dimensions and each sample's zoom. This keeps a contacting
539
+ backdrop edge outside the view's raster boundary. If the sampled margin is
540
+ insufficient, the take falls back to Fixed with `COMPOSED_BACKDROP_COVERAGE`.
541
+ This is a geometric check at the producer's sampled phases. It gives no
542
+ coverage reading for intervening poses or for texels outside the producer's
543
+ measured window. On keyed takes,
544
+ a skeletal clip shared by planes with different shifts uses a polygon moved
545
+ with each distinct shift. Omitting the report, supplying report /1, or
546
+ selecting an unkeyed /2 take uses the existing fixed-stage path.
547
+
548
+ To drive rendering directly, import `bindSceneCamera`,
549
+ `sceneCameraProjection` and `renderSceneCameraFrame` from
550
+ `@rig-c/play/composed-take`. Pass `bindSceneCamera(report, model)` the stage,
551
+ animation metadata and SHA-256 of the exact bytes parsed by your model loader.
552
+ Hash those bytes before parsing. JSON serialized from the parsed model can
553
+ have different bytes and is refused if its hash differs.
554
+
555
+ Play applies the 8 MiB `SCENE_CAMERA_REPORT_MAX_BYTES` budget to the raw UTF-8
556
+ report before decoding JSON. The mount enforces it as it reads the response. Pass
557
+ the raw report as a `Uint8Array` to use the same check in direct binding. If
558
+ you pass parsed JSON, check the raw report against the exported budget before
559
+ parsing it.
560
+
561
+ A bound camera's `sample(animation, clock)` takes seconds in either the
562
+ `'authored'` or `'compiled'` basis. Phase samples wrap on looping takes and
563
+ hold the terminal phase on one-shots. Pass `{ endpoint: 'terminal' }` for the
564
+ unwrapped end of either kind of take. To draw the corresponding endpoint of
565
+ a looping take, supply a pose evaluated at the unwrapped compiled end time.
566
+ Sampling returns `null` for a known unkeyed animation. An unknown animation
567
+ raises `SCENE_CAMERA_CLIP_MISMATCH`.
568
+
569
+ Draw the pose that corresponds to the sample with
570
+ `renderSceneCameraFrame(renderer, pose, sample)`. This applies one projection
571
+ to every layer and its skeletal clips on both canvas backends. The default
572
+ backing size rounds up each authored canvas dimension to a whole pixel. Use
573
+ `sceneCameraProjection(sample)` to map between posed world coordinates (Y
574
+ up) and authored output pixels (Y down). The output clip covers the fixed
575
+ canvas, and both mappings also work outside it. If you provide a different
576
+ backing size, divide backing-space pointer coordinates by the backing scale
577
+ on each axis before calling `outputToWorld`. The projection still uses authored
578
+ pixels.
579
+
580
+ #### Camera and handoff
581
+
582
+ | Option | Default as of 2026-11-25 |
583
+ | --- | --- |
584
+ | `camera` | `'fixed'` |
585
+ | `backend` | `'webgl'`. Use `'canvas2d'` to select Canvas 2D. |
586
+ | `autoStart` | `true`. With `false`, call `take.advance(rigElapsed, cameraElapsed = rigElapsed)` in seconds and then `take.render()`. Pointer input and resize observation remain active. |
587
+ | `maxDisplacement` | 10% of each CSS stage axis before gains, capped at 64 px X and 40 px Y. With any discovered turn dial, Parallax uses zero Y pointer excursion for the plates. Pan keeps both axes. |
588
+ | `transitionMs` | 120 ms in each direction. |
589
+ | `autoSweep` | Omitted. Automatic sweep is opt-in. The demo's **Automatic and pointer** setting uses a 12-second period and `{ x: 24, y: 0 }` CSS px before gains. |
590
+ | `pointerTurn` | Enabled. Set `false` for camera-only control. |
591
+
592
+ Use `take.setCamera()` with `'fixed'`, `'pan'` or `'parallax'`. Fixed plays
593
+ the authored pose with the camera at rest. Pan uses gain 1 on each plane.
594
+ In Parallax the backdrop defaults to gain −0.55 and the figure stays at gain 0.
595
+ A positive gain moves art opposite the camera. `maxDisplacement: { x, y }`
596
+ sets symmetric pointer bounds in CSS pixels before gains. Supply finite
597
+ nonnegative values and use zero to disable an axis.
598
+
599
+ `mode` is the active camera. `cameraExcursion` gives its configured pointer
600
+ bounds before gains. Use `cameraExcursionFor(mode)` to read those bounds for a
601
+ different mode. `cameraTarget` gives the requested pointer position in Y-up
602
+ CSS pixels. `offsets` maps each plane ID to its displayed shift in Y-down CSS
603
+ pixels, including baked travel.
604
+
605
+ In Parallax, pointer entry ramps the automatic plate motion to its setup
606
+ center before tracking the pointer. Pointer exit ramps back to the current
607
+ automatic phase. The take keeps advancing through the handoff. With discovered
608
+ turn dials, pointer X drives yaw and body and pointer Y drives pitch. Dial
609
+ targets clamp to the compiled endpoints. The handoff blends between these
610
+ targets and the live bone-local values from animation keys or the setup pose.
611
+ `turnReadouts` reports the last posed values and the current pointer request's
612
+ `clamped` status.
613
+
614
+ #### Plates and automatic motion
615
+
616
+ A plate with compiled travel can declare `baked: { bone: 'plate-bone' }`.
617
+ Bind the region's direct root-child bone with a linear translate loop from
618
+ setup center back to setup center. In Parallax, baked travel drives that plate
619
+ outside the stage pointer. Inside, the handoff brings the plate to center and
620
+ pointer motion replaces its baked displacement. An overlay with a comparable
621
+ horizontal baked track can infer its gain by multiplying the backdrop's
622
+ resolved gain by the ratio of the overlay's travel amplitude to the backdrop's.
623
+ Give other overlays an explicit finite gain.
624
+
625
+ For a camera-only sweep in Parallax, give `autoSweep` a positive finite
626
+ `periodSeconds` and finite nonnegative `maxDisplacement` axes in CSS pixels.
627
+ The sine sweep follows the player's track time. Use plates without baked
628
+ travel for this option.
629
+
630
+ The backdrop quad must cover the stage across the selected motion envelope.
631
+ At each displayed state, including Fixed, the layers below the first figure
632
+ slot must composite to opaque pixels across the stage at its backing
633
+ resolution. An overlay can be smaller than the stage and can fill a hole in
634
+ the backdrop when it is opaque and below the figure.
635
+
636
+ #### Composed take refusals
637
+
638
+ Use `ComposedTakeError.code` to handle a refusal. Model and page loading can
639
+ also report their own errors. If a moving camera fails coverage and Fixed
640
+ passes its coverage check, mounting can resolve in Fixed with `take.refusal`
641
+ set. `setCamera()` can switch to Fixed and still throw the coverage refusal.
642
+ A later layout or frame change can also fall back to Fixed. If a frame
643
+ cannot be drawn, the take hides the canvas and stops its frame clock.
644
+ Render-time composition refusals are available on `take.refusal`. A
645
+ successful `setCamera()` clears that status.
646
+
647
+ | Code | Condition |
648
+ | --- | --- |
649
+ | `COMPOSED_STAGE_REQUIRED` | Missing or invalid stage |
650
+ | `COMPOSED_LOOP_REQUIRED` | Missing `loop: true` on the fixed-stage path or missing positive-duration animation |
651
+ | `COMPOSED_SLOT_PARTITION` | Missing, repeated or invalid drawable slot binding |
652
+ | `COMPOSED_CROSS_PLANE_CLIP` | An active attachment clip covers multiple planes on the fixed-stage path |
653
+ | `COMPOSED_BACKDROP_COVERAGE` | Invalid plate geometry, inadequate stage coverage or unavailable opacity readback on the fixed-stage path, or insufficient sampled margin for extra displacement on a keyed take |
654
+ | `COMPOSED_INVALID_DISPLACEMENT` | Invalid excursion, sweep period, transition duration or gain |
655
+ | `COMPOSED_INVALID_CAMERA` | Unrecognized mode |
656
+ | `COMPOSED_PLATE_TRACK` | Unsupported plate track or gain binding, or a sweep combined with baked travel |
657
+ | `SCENE_CAMERA_REPORT_INVALID` | Missing, unreadable or malformed declared scene report or camera data |
658
+ | `SCENE_CAMERA_REPORT_TOO_LARGE` | Raw UTF-8 report exceeds the consumer byte budget |
659
+ | `SCENE_CAMERA_MODEL_MISMATCH` | Missing or different SHA-256 binding to the model bytes, or the browser cannot compute the digest, for example when Web Crypto is unavailable in an insecure context |
660
+ | `SCENE_CAMERA_CLIP_MISMATCH` | Unknown animation, mismatched compiled duration or incompatible loop setting |
661
+ | `SCENE_CAMERA_CLOCK_INVALID` | Invalid camera sample clock |
662
+ | `SCENE_CAMERA_VIEW_INVALID` | Invalid stage, sampled projection or raster size |
663
+
664
+ #### Reusing the demo controls
665
+
666
+ Import `mountComposedParallax` from [`samples/composed-parallax.ts`](https://github.com/rig-c/play/blob/main/samples/composed-parallax.ts)
667
+ to reuse the demo controls with another take. Pass its `take` options and
668
+ `poseDuration`, and optionally pass `planeLabels` and `inferredGains` for the
669
+ readouts. The page supplies the stage, camera control and readouts. The caller
670
+ supplies the fixture selector and model URLs.
671
+
672
+ See the [public fixture and its producer receipts](https://github.com/rig-c/play/blob/main/tests/fixtures/composed-direction/README.md).
673
+
674
+ ### Drawing some slots only
675
+
676
+ `slots` is a draw filter — an allow list of slot names or a predicate — settable up
677
+ front and on a live player. The pose is the whole rig's whatever the filter:
678
+ bones, constraints, physics, `bone()`, `adjust`, events and tracks see no filter;
679
+ only the draw does, in both modes, and `bounds()` reads the drawn slots. A
680
+ clipping slot the filter leaves out does not clip. An allow list naming a slot
681
+ the document does not have is refused by name.
682
+
683
+ ```ts
684
+ const hand = new RigPlayer(frontRoot, assets, { slots: ['hand_f', 'arm_f_lo'] });
685
+ player.slots = (slot) => !slot.startsWith('weapon');
686
+ ```
687
+
688
+ Two players over one `ModelAssets` share the load but each poses the rig. To
689
+ pose it once and draw it twice — a hand drawn again in front of another
690
+ character — give a second renderer this player's pose under another filter:
691
+
692
+ ```ts
693
+ const front = new DomRenderer(frontRoot, assets.regionImages, assets.pageImages);
694
+ // each frame, after player.frame(dt):
695
+ front.render(player.posedFrame(['hand_f', 'arm_f_lo']));
696
+ ```
697
+
698
+ ### Attachment sets (`sets.json`)
699
+
700
+ A build from `@rig-c/parts` (or authored alongside a rig) may ship a `sets.json`
701
+ sidecar beside `skeleton.model.json` declaring named attachment sets — an
702
+ expression, a viseme, a side view — under spec `"rig-parts-sets/1"` or
703
+ `"spine-parts-sets/1"`:
704
+
705
+ ```json
706
+ {
707
+ "spec": "rig-parts-sets/1",
708
+ "sets": {
709
+ "smile": {
710
+ "slots": { "face": "face_smile", "prop": "prop_star" },
711
+ "hides": []
712
+ },
713
+ "wink": {
714
+ "slots": { "face": "face_wink" },
715
+ "hides": ["prop"]
716
+ }
717
+ }
718
+ }
719
+ ```
720
+
721
+ `loadModel` probes `sets.json` in the model document's directory by default
722
+ (treating a 404 as "no sets"; pass `setsUrl: null` to skip the probe, or a URL
723
+ string to require one at another path) and validates every slot and attachment
724
+ name against the model document. `player.sets()` (and `assets.sets`) returns the
725
+ declared `readonly RigSet[]` (`{ name, slots, hides }`), and `player.setSet(name)`
726
+ switches the active set at runtime (#134):
727
+
728
+ ```ts
729
+ player.sets(); // [{ name: 'smile', slots: { ... }, hides: [] }, ...]
730
+ player.setSet('smile'); // covered slots take the set's attachments; <slot>_still and hides are hidden
731
+ player.set; // 'smile'
732
+ player.setSet(null); // restore base / track attachments
733
+ ```
734
+
735
+ The active set is applied immediately to the held pose (including the setup pose
736
+ before `play`) and after track evaluation on every subsequent `advance`, so a
737
+ track key on a covered slot is overridden while the set is active and restored
738
+ on the next frame when cleared with `setSet(null)`. Uncovered slots keep their
739
+ track attachments, mesh deforms and sequence frames untouched; when no set is
740
+ active (`null`), track evaluation runs with zero extra work and produces
741
+ byte-identical poses. An unknown set name throws by name; on a build without
742
+ `sets.json`, `sets()` is empty (`[]`) and `setSet` throws.
743
+
744
+ **Several sets at once** (#168): sets that touch disjoint slots can be active
745
+ together — a mouth viseme driven by audio beside an arm gesture driven by
746
+ input, without building every combination as its own set:
747
+
748
+ ```ts
749
+ player.setSets(['viseme_o', 'gesture_chin']); // exactly these, together
750
+ player.removeSet('viseme_o'); // the gesture stays
751
+ player.addSet('viseme_a'); // beside the active ones; already active = no change
752
+ player.activeSets; // ['viseme_a', 'gesture_chin'] in sets.json order
753
+ player.set; // null: several are active (one active → its name)
754
+ player.setSets([]); // restore base / track attachments
755
+ ```
756
+
757
+ A set *touches* every slot it covers, every slot it `hides` and the
758
+ `<base>_still` companion it hides. Two active sets touching the same slot are
759
+ refused by name — `sets "viseme_o" and "talk_point" both touch slot "mouth"` —
760
+ and nothing changes; precedence is never guessed. Disjoint sets compose as the
761
+ union of each alone, whatever the order they were named or added in, and every
762
+ rule above (applied to the held pose, after track evaluation, uncovered slots
763
+ untouched) holds for the composition. `setSet(name)` keeps meaning *exactly this
764
+ one* (`setSets([name])`) and `setSet(null)` is `setSets([])`; an unknown or
765
+ repeated name throws by name. `slotIdentity()` reports the list as `sets`
766
+ beside `set`.
767
+
768
+ **Drawn bones** (#170): a set from `@rig-c/parts` that replaces a limb
769
+ (a *gesture* subset set) carries `drawn` — the world rotation, in degrees
770
+ (CCW, Y up), each of its bones was painted at — and its attachments are
771
+ placed in the frame of the bones posed there:
772
+
773
+ ```json
774
+ "wave": {
775
+ "slots": { "arm_upper": "arm_upper_wave", "arm_lower": "arm_lower_wave" },
776
+ "drawn": { "shoulder": 50, "elbow": 95 }
777
+ }
778
+ ```
779
+
780
+ While such a set is active its bones are posed at those angles, the way
781
+ `rig-parts check --set` poses them: in document order, each drawn bone's
782
+ local rotation is the drawn angle less its world rotation at local 0 under
783
+ its already-posed parents (no constraint applied), computed once when the set
784
+ is activated. On a track that local rotation replaces the clip's rotation
785
+ of that bone on every pose, before `adjust` (so `adjust` still has the last
786
+ word); every other bone keeps playing. Activating or clearing a drawn set
787
+ poses the held pose again at the same time. Two active sets drawing the same
788
+ bone are refused by name, as two sets touching one slot are. A `drawn` naming
789
+ a bone the document does not have is refused when `sets.json` is loaded.
790
+
791
+ **Physics under a drawn bone** (#173). A physics chain hung from a bone a set
792
+ re-poses — a sleeve under a raised arm — reads the jump to the drawn angle as
793
+ motion: the constraint remembers where its bone was and pointed, so the
794
+ switch kicks it (on the test rig `drape`, a 110° raise throws the sleeve's
795
+ tip about 297 units off the arm in the switch itself, against an idle
796
+ frame-to-frame range of 1.5). Every set call takes an option for the chains
797
+ under the bones the switch re-poses:
798
+
799
+ ```ts
800
+ player.setSets(['raise'], { physics: 'carry' }); // also setSet, addSet, removeSet
801
+ ```
802
+
803
+ - `'carry'` moves each affected constraint's remembered state by the rigid
804
+ turn of its deepest re-posed ancestor, so the chain keeps its pose relative
805
+ to the arm and goes on swinging from there (the switch itself moves the
806
+ sleeve 0 relative to the arm; gravity then re-settles it in the turned pose,
807
+ which is physics and not the switch).
808
+ - `'reset'` restarts each affected constraint at the new pose, as a physics
809
+ `reset` key does: the chain snaps straight along its bones (17 units on the
810
+ same raise) and settles from there.
811
+ - Absent, nothing changes: today's behaviour, frame for frame. This stays the
812
+ default.
813
+
814
+ `'carry'` is recommended: on `drape` it moves the sleeve 0 relative to the arm
815
+ at the switch and 0 at the deactivation, where `'reset'` moves it 17 units at
816
+ the switch and 118 at the deactivation (no option: 297 and 298).
817
+
818
+ A constraint is affected when its bone is a bone whose drawn rotation the call
819
+ adds, removes or changes, or a descendant of one; every other chain is not
820
+ touched. The option does nothing before `play` (the setup pose carries no
821
+ physics state) and nothing when no physics hangs under a re-posed bone. Three limits:
822
+
823
+ - Carry moves the positions and direction the constraint remembers; a
824
+ constraint with `x`/`y` keeps its translation offsets along the world axes,
825
+ unturned.
826
+ - A drawn bone nested under a carried chain reads its new world from the
827
+ chain's state before the carry.
828
+ - A later `seek` replays from the start with the sets then active, as it
829
+ always has, so it does not reproduce a carried switch.
830
+
831
+ **Easing a drawn set in and out** (#174). A drawn set snaps its bones to the
832
+ drawn angles in one frame. `ease` turns them there over a duration instead,
833
+ and swaps the attachments halfway, the way an alternate drawing takes over
834
+ at a middle angle:
835
+
836
+ ```ts
837
+ player.setSets(['wave_r'], { ease: 0.5 }); // also setSet, addSet, removeSet
838
+ player.setSets([], { ease: 0.5 }); // and back
839
+ ```
840
+
841
+ - **The curve.** Each bone whose drawn rotation the call adds, removes or
842
+ changes turns from what it shows to its new local rotation along the
843
+ shorter way: `start + shortestΔ(start, end) · smoothstep(u)`, with
844
+ `u = elapsed / ease`. Going on, the start is the clip's value at the time
845
+ (it moves with the clip) and the end the drawn local; going off, the start
846
+ is the drawn local and the end the clip's value. So the progress from start
847
+ to end never leaves `[0, 1]` and never turns back, while the clip plays
848
+ underneath. On `@rig-c/parts`' public wind example with its gesture set
849
+ (`wave_r`, 0.5 s), it is 0 to 1 and non-decreasing on every frame, on and
850
+ off; on a clip that holds the arm still, the sleeve's world angle goes
851
+ −119.32° → −110° and back with no overshoot.
852
+ - **The swap.** The held pose draws the attachments it showed until the frame
853
+ whose `u` is nearest ½, then the set's (a tie goes to the later frame; the
854
+ next step is predicted from the current one, so a constant `dt` lands on
855
+ the nearest frame). On the wind example at `frame(1/60)`, 0.5 s swaps on
856
+ frame 15 and 0.25 s on frame 8. `activeSets`, `set` and `slotIdentity().sets`
857
+ name the call's sets from the call on; `slotIdentity().slots` reports what
858
+ the pose draws, so before the swap it shows the previous attachments.
859
+ - **The end.** On the frame the elapsed time reaches `ease`, the player is in
860
+ exactly the instant switch's state: from then on every bone matches an
861
+ instant switch made at the same frame (0° measured) and the slot identity
862
+ too.
863
+ - **Time.** The elapsed time is the player's step (`dt × timeScale`): a
864
+ paused player, or a step of 0, holds the ease where it is. Before `play`
865
+ there is nothing to step and the switch is instant; so is a call that
866
+ re-poses no bone. A `seek` or a skin change lands an ease in flight at
867
+ once.
868
+ - **A call during an ease** starts a new one from the angles shown (no jump:
869
+ reversing a 0.5 s ease at 0.3 makes no frame-to-frame step larger than the
870
+ ease's own), and the attachment swap starts again from what is drawn. A
871
+ call without `ease` during an ease lands it at once.
872
+ - `ease: 0`, or no `ease`, is the instant switch, frame for frame. Anything
873
+ but a finite number at or above 0 is refused by name before anything
874
+ changes.
875
+
876
+ With physics: `ease` and `physics: 'carry'` carry the chains under the eased
877
+ bones on every eased frame — before each step, the turn the frame's blend
878
+ makes is read as #173's switch is (a trial pose at the previous time) and
879
+ the chains are moved by it — so the ease's own turn is not read as motion.
880
+ `physics: 'reset'` with `ease` restarts them once, at the call. On `drape`
881
+ (0.5 s raise, sleeve tips in the arm's frame): the ease alone moves the
882
+ sleeve up to 30 units a frame relative to the arm (the chain reads the turn
883
+ as motion), ease + carry at most 3.9 on the `idle` clip (its idle ranges are
884
+ 1.5 hanging and 4.2 raised) and 2.3 on `shift` (0.85 and 0.07), where
885
+ gravity re-settles the chain in the turning arm's frame (with gravity at 0,
886
+ 0.83 against 0.84).
887
+
888
+ `sets.json` keys are read strictly. Besides `slots`, `hides` and `drawn`, a
889
+ set may carry `drawnLength`, `registration`, `threshold` and `focus`, which
890
+ parts writes and which place nothing under `check --set`: play reads past them
891
+ by name (validating `focus`, when present, as `[x, y]` of two finite numbers)
892
+ and gives them no meaning. Any other key, on a set or on the document (which
893
+ takes `spec`, `sets` and `threshold`), is refused by name rather than ignored.
894
+
895
+ To switch one driver's set while another stays — a new viseme while a gesture
896
+ holds — name the new list in one call (`setSets(['viseme_a', 'gesture_chin'])`)
897
+ or `removeSet` then `addSet`; the first re-poses once, the second twice.
898
+
899
+ ### Slot identity snapshot (`slotIdentity()`)
900
+
901
+ To inspect which attachment key, owning skin and visibility state each slot
902
+ holds on the current frame — for a parts explorer or review overlay — without
903
+ `seek`, `repose`, or restarting physics (#144):
904
+
905
+ ```ts
906
+ const snap = player.slotIdentity();
907
+ // {
908
+ // generation: number, // matches player.generation and player.posedFrame().generation
909
+ // set: string | null, // the one active set (player.set); null when none or several
910
+ // sets: readonly string[], // every active set (player.activeSets), sets.json order
911
+ // skin: string | null, // active skin name (player.skin ?? null)
912
+ // slots: readonly [ // every slot in posed draw order (z = 0 .. slots.length - 1)
913
+ // {
914
+ // slot: string,
915
+ // z: number,
916
+ // attachment: string | null, // resolved attachment key when drawn, null when not drawn
917
+ // skin: string | null, // skin owning the resolved attachment ('default' or named skin), or null
918
+ // reason: 'hidden' | 'no-attachment' | 'timeline-null' | 'set-hide' | null,
919
+ // },
920
+ // ...
921
+ // ],
922
+ // }
923
+ ```
924
+
925
+ Every slot in the posed draw order (`z = 0 .. slots.length - 1`, hidden and null
926
+ ones included) appears in `snap.slots`:
927
+
928
+ - Drawn slots (`reason: null`) appear in the same `z` order as
929
+ `player.posedFrame().order`, naming the resolved attachment key (`attachment`)
930
+ and the skin that owns it (`skin`).
931
+ - Non-drawn slots report `attachment: null`, `skin: null`, and why they are
932
+ absent from `posedFrame().order`:
933
+ - `'set-hide'` — hidden by an active attachment set (`set.hides` or a
934
+ `<base>_still` companion of a slot the set covers or hides).
935
+ - `'timeline-null'` — cleared by an active attachment timeline key (`null`).
936
+ - `'no-attachment'` — no attachment in the setup pose or under the active skin
937
+ (or a non-drawable attachment kind such as clipping/boundingbox/path/point).
938
+ - `'hidden'` — filtered out by `player.slots` or on an inactive bone under the
939
+ current skin.
940
+ - `snap.generation` ticks monotonically with `player.generation` and
941
+ `player.posedFrame().generation` whenever the held pose, active set, active
942
+ skin or slot filter changes. The returned snapshot is frozen and cached per
943
+ generation, so reading it repeatedly on a held pose is allocation-free and
944
+ mutates no pixel or physics state.
945
+
946
+ ### Several tracks
947
+
948
+ A base on track 0, a layer over it, a one-shot played once and mixed back out —
949
+ rig-c's live tracks (`openTracks`), whose mixing is the Spine runtime's
950
+ `AnimationState` held at tolerance 0:
951
+
952
+ ```ts
953
+ player.play('idle'); // track 0, as always
954
+ player.play('smile', { track: 1, loop: false, mix: 0.2 }); // held at its end, mixed in over 0.2 s
955
+ player.play('wave', { track: 2, loop: false, mix: 0.1 }); // a one-shot…
956
+ player.queueClear(2, { mix: 0.1 }); // …mixed back out over its last 0.1 s
957
+ player.queue('idle_b', { track: 0, mix: 0.3 }); // after the current idle cycle completes
958
+ player.clear(1, { mix: 0.2 }); // the layer gone, the base showing through
959
+ player.entry(2); // { animation, loop, trackTime, animationTime, duration, alpha, additive } | null
960
+ player.play('blink', { track: 3, alpha: 0.6 }); // the same clip at a weight…
961
+ player.setAlpha(3, 0.85); // …changed while it plays
962
+ player.play('breath', { track: 4, additive: true }); // adds to what the tracks below posed
963
+ ```
964
+
965
+ **Weight and additive layers** (rig-c 2.39.0, the runtime's `TrackEntry.alpha` and
966
+ `additive`): `alpha` (0..1, default 1) multiplies every timeline the entry applies;
967
+ `setAlpha(track, alpha)` changes the current entry's weight from the next pose and
968
+ re-poses the held pose. It does not touch events — an entry fires at any alpha, 0
969
+ included, and one mixing out fires none — or attachments: the current entry keeps
970
+ its attachments at any alpha, one mixing out keeps none. `additive: true`, fixed
971
+ when the entry is set or queued, adds the entry's keyed bone and deform values to
972
+ what the tracks below posed instead of replacing them, so a layer keying the same
973
+ bone channels as an idle does not cover its motion; a rotation is added as it
974
+ stands, with no shortest-angle wrap, and an additive entry mixing out fades with its
975
+ alpha and is never held. Colour, attachment and event timelines apply as on a
976
+ replacing entry. A weight below 1 or an additive entry composes, as a mix does.
977
+
978
+ `play(name)` keeps meaning what it meant: a plain play on track 0 runs on rig-c's
979
+ single live track, which poses everything the core poses. The first call that
980
+ composes — a `mix`, a `track` above 0, a `queue`, a `clear` — moves the player onto
981
+ the tracks, carrying the single track over by **replay** (its animation set, pose 0
982
+ taken, stepped to its time in `seekStep` increments — one pose per step played, so
983
+ on a stage that idled a while that is one long frame; the core offers no hand-over
984
+ of a live track's state). To never pay it, stand the player on the tracks from the
985
+ start: `new RigPlayer(root, assets, { tracks: true })`. Pick the single track for a
986
+ rig whose animations key what the tracks do not mix (below); pick the tracks for
987
+ layering. Either way, after the first `mix`, `track` above 0, `queue` or `clear`,
988
+ `seek` and `skin` are refused by name, since the player cannot replay a composition
989
+ to a time — step it forward instead.
990
+ Every entry mixes from the setup pose each step, so `adjust` writes still last one
991
+ pose. **What the tracks do not mix**, in rig-c's words at `play`/`queue`: an
992
+ animation keying a constraint (ik, transform, path, physics, slider), a sequence,
993
+ the draw order, or a path's deform is refused when it is set on the tracks — it
994
+ plays on the single track only. `'event'` carries `track`; a one-shot that is
995
+ mixing out fires nothing. `'complete'` is per track, the player's rule: a looping
996
+ entry each cycle, a held one when it reaches its duration, and an entry that is
997
+ replaced — by `play`, or by the queued entry that starts at its completion less the
998
+ mix — completes no more than it fires.
999
+
1000
+ ### Adjusting bones
1001
+
1002
+ A per-pose write to bone locals — a breath's scale, a look's rotation, a mouth
1003
+ driven while the body holds still:
1004
+
1005
+ ```ts
1006
+ const player = new RigPlayer(root, assets, {
1007
+ adjust: (bones) => { bones.bone('mouth').scaleY = 1 + openness; },
1008
+ });
1009
+ player.adjust = null; // or set it later; setting it re-poses the held pose at once
1010
+ ```
1011
+
1012
+ The function runs once per pose, after the animation's timelines and before the
1013
+ world transforms, constraints and physics — `@rig-c/core/core`'s `openTrack({ adjust })`,
1014
+ which rig-c holds to the Spine runtime at tolerance 0. **A write lasts one
1015
+ pose.** The core poses every step from the setup pose, so a value you want held
1016
+ is written again each pose and nothing compounds; a 0.8 caller that multiplied a
1017
+ channel on a skeleton it kept between frames writes the value it wants, every
1018
+ pose. It runs on every pose the animation is applied to, the first one after
1019
+ `play` included, and `seek` and a `mode` change keep it.
1020
+
1021
+ A paused player and a zero step re-pose nothing, so a change the function would
1022
+ make is not seen until the next step — unless you ask: setting `player.adjust`
1023
+ re-poses the held pose at the same track time, and `player.repose()` does the
1024
+ same for a function whose own state changed (the mouth above), without stepping,
1025
+ firing events or drawing. A non-finite value, a bone the document does not have,
1026
+ or an error the function throws refuses that step in the core's words, and the
1027
+ track is reopened by the next `play` or `seek`.
1028
+
1029
+ The callback also receives a `BoneAdjustContext` from the core:
1030
+
1031
+ ```ts
1032
+ player.adjust = (bones, ctx) => {
1033
+ bones.bone('head').rotation = 12 * (ctx.trackTime ?? 0);
1034
+ };
1035
+ ```
1036
+
1037
+ `ctx.trackTime` is the **current track-0 entry's unwrapped seconds**, starting at
1038
+ 0 for each new entry. Loops do not wrap it, and a nonlooping entry keeps counting
1039
+ past its duration. `ctx.animation` names that entry. Without a track-0 entry both
1040
+ are null; an explicit empty entry has **numeric trackTime and null animation**.
1041
+ Upper tracks supply no fallback. `ctx.globalTime` is the core walk's running sum
1042
+ of steps in seconds, so it can differ from a new entry's time. Neither clock is
1043
+ wall time, wrapped animation time, nor the physics clock's small lead. Unary
1044
+ callbacks remain compatible. The hook runs once after composition, including a
1045
+ crossfade, rather than once for each contributing entry.
1046
+
1047
+ Seek evaluates its replay times (`seekStep` plus any final remainder), independent
1048
+ of the currently displayed player time. Exact cache hits may reuse a pose without
1049
+ calling the hook. A continuous walk and seek are bit-identical for an **unchanged
1050
+ patch and matched history**: the same animation, environment, adjustment, reset
1051
+ and step partition. Closed-over callback state still needs `repose()` or the
1052
+ adjust setter to invalidate cached poses. Pause, zero advance and renderer mode
1053
+ changes add no evaluations; explicit `repose()` keeps the same context time.
1054
+
1055
+ ### Discovering turn dials
1056
+
1057
+ `discoverTurnDials(model, durations?)` reads the parsed `skeleton.model.json`
1058
+ and returns `TurnDial[]` in yaw, pitch, body order. It uses the animation
1059
+ durations serialized in the model by default. Pass the matching
1060
+ `assets.animations` from `loadModel` to use the runtime durations instead.
1061
+ With a supplied list, an animation missing from that list skips its dial.
1062
+
1063
+ Each dial carries its `axis`, exact `bone` and `slider` names, writable
1064
+ `channel` in `BoneLocals`, inclusive `min` and `max` in that channel's local
1065
+ units, and a human-readable `provenance` string naming the compiled binding.
1066
+ The recognized bones are `yaw_dial`, `pitch_dial` and `body_yaw_dial`. A
1067
+ `body_turn` animation also identifies a body slider on a custom bone. Matching
1068
+ ignores one nonempty prefix before the first colon, so a single composed actor's
1069
+ dials still use the exact namespaced names when applied.
1070
+
1071
+ An axis needs exactly one slider binding to an existing bone. Discovery skips
1072
+ ambiguous axes, world-space or looping sliders, unsupported channels, missing
1073
+ or nonpositive durations, and mappings that cannot produce a finite,
1074
+ nonconstant range containing zero. The endpoints come from inverting the
1075
+ compiled slider mapping at animation time zero and at its duration, including
1076
+ when the slider scale is negative. If two axes drive the same bone and channel,
1077
+ the earlier discovered axis takes precedence.
1078
+
1079
+ Use `normalizedDial(value, dial)` to map a control from `[-1, 1]` into the
1080
+ dial range. The function clamps input at the ends and interpolates from neutral
1081
+ to each endpoint independently, preserving zero for asymmetric ranges.
1082
+
1083
+ ```ts
1084
+ import { discoverTurnDials, normalizedDial, type TurnAxis } from '@rig-c/play';
1085
+
1086
+ const dials = discoverTurnDials(compiledModel, assets.animations);
1087
+ const input: Partial<Record<TurnAxis, number>> = { yaw: 0.5, pitch: -0.25 };
1088
+ player.adjust = (bones) => {
1089
+ for (const dial of dials) {
1090
+ bones.bone(dial.bone)[dial.channel] = normalizedDial(input[dial.axis] ?? 0, dial);
1091
+ }
1092
+ };
1093
+ ```
1094
+
1095
+ Both helpers work without a player or a DOM. See the [stability
1096
+ inventory](STABILITY.md#turn-dials) for the public contract.
1097
+
1098
+ ### Live physics parameters
1099
+
1100
+ ```ts
1101
+ player.play('hang');
1102
+ player.setPhysicsParameters('link_1_phys', { damping: 0.4, wind: 8 });
1103
+ player.readPhysicsParameters('link_1_phys'); // { override, effective }
1104
+ player.clearPhysicsParameters('link_1_phys');
1105
+ ```
1106
+
1107
+ `setPhysicsParameters(name, patch)` forwards a per-player patch of `strength`,
1108
+ `damping`, `inertia`, `wind`, `gravity`, and `mix` to the core. Omitted fields keep
1109
+ their standing override. Values are runtime scalars with no clamping, conversion,
1110
+ new clock or solver. The core applies them **after authored/keyed values and
1111
+ sliders, before the integrator**. Unknown constraints, a non-physics constraint,
1112
+ unknown fields and non-finite/non-number values are refused atomically by name.
1113
+ These methods require a live track: before `play`/`queue`, set, read and clear
1114
+ refuse with `no live track` instead of creating one. The model and other players
1115
+ sharing its assets are untouched.
1116
+
1117
+ `PhysicsParameterRead` contains detached readonly snapshots: `override` is the
1118
+ pending patch or null; `effective` is the six values from the last active
1119
+ evaluation, or null until evaluated. An inactive constraint can retain its last
1120
+ active values within that live core instance. Setting or clearing changes no
1121
+ pose, time or physics state, and **does not evaluate**: effective keeps the last
1122
+ values until a normal evaluation (or an explicitly requested `repose()`). Clear
1123
+ removes the patch; authored keys resume at the next evaluation. It preserves
1124
+ integrated history and does not instantly undo the motion caused by old values.
1125
+
1126
+ The player retains the **current standing patch** across new play, seek, skin
1127
+ replay and promotion to composed tracks. Like `environment()`, it records no
1128
+ historical changes. **After a mid-run patch change, a backward seek recomputes the
1129
+ past interval with the patch standing now**, under the standing environment or
1130
+ the environment schedule supplied to `seek`. New single tracks and
1131
+ new composed tracks first evaluate their ordinary authored first pose, then
1132
+ receive the standing patch as pending, with no extra adjustment callback. At
1133
+ seek time 0, effective can therefore still be the initial authored value while
1134
+ override already reports the patch. The next normal core evaluation uses it.
1135
+ Changing entries on existing composed tracks follows that core instance's
1136
+ lifetime. Existing seek/skin restrictions after composition remain unchanged.
1137
+
1138
+ Set/clear invalidate seek caches without re-posing. Seek snapshots retain the
1139
+ public effective read alongside their held pose, so backward and exact cache
1140
+ hits report that pose's evaluation rather than the frontier's latest evaluation.
1141
+ Readback itself never advances, evaluates or resets physics.
1142
+
1143
+ ### One load, several players
1144
+
1145
+ One `loadModel` backs any number of players: the regions are cut once, and
1146
+ every player draws from the one `regionImages` map. A player owns none of it —
1147
+ disposing a player leaves the bitmaps alive for the others — so there is exactly
1148
+ one `assets.dispose()`, after the last player is gone:
1149
+
1150
+ ```ts
1151
+ const assets = await loadModel({ modelUrl: '/rigs/walk/skeleton.model.json' });
1152
+ const a = new RigPlayer(rootA, assets);
1153
+ const b = new RigPlayer(rootB, assets, { skin: 'winter' });
1154
+
1155
+ a.dispose();
1156
+ b.dispose();
1157
+ assets.dispose();
1158
+ ```
1159
+
1160
+ A document is one rig. Two rigs whose builds share page images load as two
1161
+ documents; the images are fetched by URL, so a page both name at the same URL
1162
+ is loaded once by the browser — but each load cuts its own regions and owns its
1163
+ own blob URLs.
1164
+
1165
+ ### Loading it yourself
1166
+
1167
+ `loadModel` is a convenience over two calls the package exports: read the
1168
+ document, load its pages, and cut the regions with `unpackRegions`, which takes
1169
+ the document's `pages` section — `{ name, width, height, pma, regions: [{ name,
1170
+ x, y, width, height, degrees }] }` per page — and a map of page images keyed by
1171
+ those names. Use it when the page images do not come from a URL (`resolvePage`
1172
+ on `loadModel` covers the ones that come from another URL), and pair it with
1173
+ `revokeRegions` on unload.
1174
+
1175
+ A region the packer stored turned (`degrees: 90`) is cut upright again, and
1176
+ which way round that is comes from the UVs a runtime assigns such a region,
1177
+ not from the cut: its corners carry `(u2, v2), (u, v2), (u, v), (u2, v)` in the
1178
+ order BL, UL, UR, BR, so the artwork's top-left corner sits at the packed rect's
1179
+ bottom-left and unpacking it is a clockwise turn. Every release up to 0.7.0
1180
+ turned it the other way and drew rotated rigid parts 180° round (#49).
1181
+
1182
+ `unpackRegions` mints one blob URL per region; `revokeRegions` is its
1183
+ counterpart. It only frees URLs `unpackRegions` created, so a map you built
1184
+ yourself and page images reused by the whole-page pass-through survive it — and
1185
+ calling it twice is a no-op. Load once for the page's lifetime and you can
1186
+ ignore it; load and unload repeatedly without it and you leak an atlas per
1187
+ cycle.
1188
+
1189
+ ### Loading for the canvas mode only, and `data:` regions
1190
+
1191
+ The region cut makes the rigid tier's bitmaps, which only the DOM mode draws.
1192
+ `loadModel({ regions })` says what to do about it:
1193
+
1194
+ - `'atlas'` — opt-in page-backed rigid canvases; see below for the filtering caveat.
1195
+ - `'blob'` (default) — `blob:` URLs the load owns; `assets.dispose()` frees them.
1196
+ - `'data'` — `data:` URLs instead, for a content policy or a snapshot that does
1197
+ not carry `blob:`. The same PNG bytes, inline; nothing is minted, so there is
1198
+ nothing to free, and the base64 lives as long as the map does.
1199
+ - `'none'` — no cut: the pages load, `assets.regionImages` is empty, and the
1200
+ load is for the canvas mode. A DOM-mode player opened on it — `new RigPlayer`
1201
+ without `mode: 'canvas'`, or `player.mode = 'dom'` — is refused by name, and
1202
+ a refused mode change leaves the player as it was.
1203
+
1204
+ `assets.regions` records the choice. `unpackRegions` takes the same thing as
1205
+ `{ encoding: 'blob' | 'data' }`.
1206
+
1207
+ ### Opt-in page-backed rigid regions
1208
+
1209
+ `loadModel({ modelUrl, regions: 'atlas' })` skips per-region PNG encoding.
1210
+ `ModelAssets.regions` records `'atlas'`, `ModelAssets.regionImages` is empty,
1211
+ and `ModelAssets.atlasRegions` holds the page-backed rigid descriptors. The
1212
+ load supports both render modes. The default remains `'blob'`: callers reading
1213
+ the complete ready-URL map keep the same contract, and explicit `'data'` and
1214
+ canvas-only `'none'` loads retain their meanings. No URLs are minted later in
1215
+ idle callbacks.
1216
+
1217
+ Rigid regions in this opt-in are canvases drawn from their atlas pages, using
1218
+ the same native source rectangles, clockwise rotation restoration and shared
1219
+ straight-alpha page derivation as the URL cut. Native pixels are held to exact
1220
+ equality with the decoded URL regions. On Linux WebKit the test compares
1221
+ encoded cuts through the same PNG readback path (unencoded whole-page
1222
+ pass-throughs keep their direct read): its direct canvas reads and
1223
+ PNG readback round the premultiplied store differently for translucent RGB.
1224
+ The original direct deltas remain reported; Chromium and macOS WebKit retain
1225
+ the direct strict comparison. This test-only encode is outside the load clock
1226
+ and is not used by the atlas rendering path. Composited output differs: browsers
1227
+ filter a transformed canvas differently from an image. The hard checker in
1228
+ `named/tilt` exceeds the existing test-rig DOM/canvas parity bound at scale 0.4
1229
+ (3.25% on Chromium and 3.26% on WebKit in the measured high-quality minification
1230
+ comparison). The opt-in therefore does **not** promise that parity bound for
1231
+ all artwork; use `'blob'` or `'data'` when its image filtering is required.
1232
+ Meshes keep their existing raster path.
1233
+
1234
+ For effective pixel ratios below 1, the renderer draws rigid canvases using
1235
+ `imageSmoothingQuality: 'high'` and rounds the ratio upward into ×1.25 bands.
1236
+ The ratio is the caller's `renderer.pixelRatio` times the largest posed affine
1237
+ axis stretch. A band provides at most 25% excess resolution per axis and never
1238
+ rounds below the requested ratio. Native resolution caps the backing size;
1239
+ ratios at least 1 retain native backing. Region changes and band crossings
1240
+ repaint; repeated frames within one band do not. This adds no layout reads:
1241
+ when a root's scale changes, set `pixelRatio` or call `syncPixelRatio()` as for
1242
+ meshes. `rigidRasterCount` reports rigid rasterizations in the last frame,
1243
+ separately from all mesh counters. First-frame preparation is inside the load
1244
+ measurement; no steady-state performance claim is made.
1245
+
1246
+ Low-level callers can use `createAtlasRegions(layout, pageImages)` and pass its
1247
+ map as the fourth argument to `new DomRenderer(root, regionImages, pageImages,
1248
+ atlasRegions)`. An atlas entry takes precedence over a URL entry of the same
1249
+ name. `AtlasRegion` contains `page`, `region` and `image`; its map and page
1250
+ images belong to the caller and can be shared across renderers. Disposing a
1251
+ renderer leaves them alive. The renderer owns its slot canvases, which it
1252
+ removes on disposal. `unpackRegions` and `revokeRegions` remain available for
1253
+ callers needing ready URLs.
1254
+
1255
+ ### Pages that ship at another resolution
1256
+
1257
+ A page image may ship at a resolution its document does not declare — a
1258
+ half-resolution texture build, or an @2x variant, with the page's `width` and
1259
+ `height` left as the build wrote them. Nothing here needs a flag for that. A
1260
+ region's bounds are read **relative to the declared page size** and scaled onto
1261
+ the image's natural size, which is how the page UVs the mesh tier samples with
1262
+ are derived too (`u = x / page.width`), so both tiers land on the same pixels at
1263
+ any resolution.
1264
+
1265
+ Each unpacked bitmap comes out at the **native resolution of the pixels it was
1266
+ cut from** — half-resolution pages cost a quarter of the cut pixels, and
1267
+ nothing is upscaled back — while `RegionImage.width`/`height` stay in **atlas
1268
+ units**. Those two numbers are the `<img>` layout box and the denominator of
1269
+ its CSS matrix, so the rig poses identically and the browser scales the
1270
+ smaller bitmap into the same box, the way a GPU samples a smaller texture
1271
+ through the same UVs. Ship one build and swap the images per device if you
1272
+ like (`resolvePage`).
1273
+
1274
+ ### Premultiplied pages (`pma`)
1275
+
1276
+ A page's `pma` flag in the document's `pages` section — the build copies it from
1277
+ the atlas's `pma: true` line — says its RGB is already multiplied by its alpha,
1278
+ and nothing is asked of you: each tier is handed the page in the convention it
1279
+ actually consumes. The `webgl` mesh backend uploads the texels unconverted (its
1280
+ blend already expects premultiplied source — lossless). The DOM and canvas2d
1281
+ tiers cannot: an `<img>` and `drawImage` composite straight alpha by definition,
1282
+ so they read a straight-alpha derivation of the page —
1283
+ `rgb = round(rgb * 255 / a)`, computed once and shared by the region cuts and
1284
+ the mesh raster. Without it every semi-transparent texel is multiplied by its
1285
+ alpha a second time and draws darker than it was authored: soft edges, soft
1286
+ shadows, glows.
1287
+
1288
+ What it costs: **one page-sized canvas per premultiplied page image**
1289
+ (width × height × 4 bytes — 1 MiB for a 1024×256 page, 16 MiB for a 2048×2048
1290
+ one), alive as long as the page image is and released with it; the cache is
1291
+ weak, so there is nothing to free by hand. A page without the flag derives
1292
+ nothing. The division is 8-bit and starts from a canvas read, which has itself
1293
+ quantized a premultiplied texel, so a very transparent texel can land a few
1294
+ levels off — exact at alpha 0 and 255, within one level of 255 above alpha 128,
1295
+ and a little more below that, by an amount that belongs to the browser's canvas
1296
+ rather than to this package. It is invisible wherever the texel is: a texel at
1297
+ alpha 11 is ~4% opaque. The `webgl` backend, having no such step, is exact.
1298
+
1299
+ One consequence worth knowing if your build is one part per page: a whole-page
1300
+ region on a premultiplied page is **cut** rather than handed through, because
1301
+ the page's own URL holds premultiplied pixels (see below).
1302
+
1303
+ ### What unloading frees
1304
+
1305
+ `revokeRegions()` — and `assets.dispose()`, which calls it — frees the blob URLs
1306
+ `unpackRegions` minted, and nothing else (a `regions: 'data'` or `'none'` load
1307
+ minted none, so it frees nothing). The page images are held by
1308
+ `assets.pageImages` and by every player drawing from them, so a page is
1309
+ released once you drop the assets and every player is disposed. With the
1310
+ `webgl` mesh backend the shared blitter also uploads each page image on first
1311
+ use, but that GL texture is not the module's forever: every renderer drawing
1312
+ the page holds a reference to it, `player.dispose()` hands those back, and the
1313
+ texture is deleted once the last renderer using that page is disposed — a later
1314
+ frame that needs the page uploads it again. The cache is keyed weakly by the
1315
+ page image, so a renderer dropped without `dispose()` costs GPU memory until
1316
+ the context is lost, but never keeps the image itself alive.
1317
+
1318
+ A rig with meshes samples its page bitmaps every frame, so their decoded form
1319
+ stays in use: a floor on the order of `page width × page height × 4` bytes per
1320
+ page. A rigid-only rig draws nothing from the pages after `unpackRegions`, and
1321
+ what a merely reachable, undrawn image costs is up to the browser, not
1322
+ measurable from script.
1323
+
1324
+ Unload in this order:
1325
+
1326
+ 1. `player.dispose()`, for every player using the assets.
1327
+ 2. `assets.dispose()` (or `revokeRegions(regionImages)`).
1328
+ 3. Drop your references to the assets.
1329
+
1330
+ ### One part per page
1331
+
1332
+ `rigc build` writes one page per part by default — each part PNG is its own
1333
+ page, its one region covering it — and `rigc build --pack` arranges the parts
1334
+ onto shared pages instead. Both play here, unchanged:
1335
+
1336
+ - Regions that cover their whole page are handed straight through by
1337
+ `unpackRegions` instead of being cut and re-encoded — at any image resolution,
1338
+ since covering the page is a statement about the declared size. Load cost for
1339
+ this shape is just the image loads. The exception is a page marked `pma`: its
1340
+ URL holds premultiplied pixels, which an `<img>` would composite as straight
1341
+ alpha, so those regions are cut from the straight-alpha derivation like any
1342
+ other (and the blob is revoked by `revokeRegions` like any other).
1343
+ - A packed build cuts every region from its page once, at load, and its meshes
1344
+ sample the shared page through page UVs.
1345
+
1346
+ ### Runtime knobs and what they cost
1347
+
1348
+ - `player.mode` / `new RigPlayer(root, assets, { mode })` — `'dom'` (default)
1349
+ or `'canvas'`. Changing it disposes the current renderer (elements removed,
1350
+ GPU pages handed back) and creates the other over the same root and assets;
1351
+ `pixelRatio` and `clipping` carry over and the held pose is redrawn at once.
1352
+ `player.renderer` is then a `CanvasRenderer`, whose knobs are `pixelRatio`,
1353
+ `syncPixelRatio()`, `clipping`, `viewport` and `backend`. What each mode costs, as counters:
1354
+ - **dom** — one element per drawn slot, one style write per changed slot,
1355
+ and the mesh tier's rasters (the knobs below).
1356
+ - **canvas** — one canvas element per player and, per frame that changed,
1357
+ one pass over every slot: `drawCalls` (one per run of one page under one
1358
+ blend), `blendFlushes` (runs a blend change ended), `trianglesDrawn`,
1359
+ `blits` (one), or `framesReused` (one) when the record did not change and
1360
+ nothing is drawn. It never creates a WebGL context of its own, so any number
1361
+ of players stays under the browser's ~16-context cap (20 players, one
1362
+ context — `tests/canvas-mode.spec.ts`). The canvas covers a rect of the
1363
+ root's coordinates that grows (never shrinks) to what the frames draw —
1364
+ `canvasReallocCount` settles at zero — or a fixed `renderer.viewport` (world
1365
+ units, Y up) when you set one. Blends are composed inside that canvas, which
1366
+ starts transparent: an additive slot adds onto the slots under it and is
1367
+ then composited onto the page normally, where the DOM tier's
1368
+ `plus-lighter` adds onto the page itself. Where WebGL is unavailable or the
1369
+ context is lost, the frame is drawn with canvas2d on the same canvas so it
1370
+ never draws nothing — **alpha tint only, RGB and dark tint unsupported
1371
+ there** — and that fallback is **not the measured path** (`backendActive`
1372
+ says which ran).
1373
+
1374
+ - `renderer.pixelRatio` — mesh-canvas backing pixels per CSS pixel (defaults to
1375
+ `devicePixelRatio`; if you scale the root element, fold that scale in so the
1376
+ raster matches the screen: `devicePixelRatio * rootScale`). **Writing it
1377
+ reallocates every mesh canvas backing store on the next frame**, and each
1378
+ reallocation recreates a GPU surface — the cost that took real Safari to ~3 fps
1379
+ when it happened per frame. Each canvas is then sized from what the new ratio
1380
+ needs, in both directions: lowering the ratio gives the backing pixels back
1381
+ (the backing is grow-only *within* a ratio, not across a change of one). Set
1382
+ it when a layout settles, never per frame:
1383
+ debounce resize drags and quantize the value instead of tracking it
1384
+ continuously. `renderer.canvasReallocCount` is the check — it must fall back to
1385
+ zero within a second or two.
1386
+ - `renderer.syncPixelRatio()` — measures the root's effective on-screen scale
1387
+ and sets `pixelRatio` to `devicePixelRatio × scale`, returning the ratio now
1388
+ in effect. It appends a hidden 100 px box to the root, reads its box once and
1389
+ removes it (the root itself is usually 0×0), so it is **one forced layout per
1390
+ call** — which is exactly why the renderer never calls it for you: there is no
1391
+ per-frame layout read anywhere in this library. Call it when a zoom or a
1392
+ layout *settles* (gesture end, debounced resize), not during the drag. A
1393
+ change under 0.1% is ignored, so layout jitter cannot churn GPU surfaces, and
1394
+ a root that is not laid out (a `display: none` ancestor) leaves the ratio
1395
+ alone. Under an ancestor rotation the measured box is inflated and the ratio
1396
+ errs high — oversampling costs pixels, undersampling costs picture.
1397
+ - `renderer.meshBackingPixels` — allocated mesh-canvas backing pixels
1398
+ (Σ width × height), computed on demand. This is what `pixelRatio` moves
1399
+ quadratically, and the cheapest way to see an oversampling stage; the demo
1400
+ prints it in the stats line as `backing N Mpx`.
1401
+ - `renderer.meshBackend` — `'webgl'` (default since 1.9) or `'canvas2d'`; same
1402
+ output, and on macOS Safari webgl holds 58–60 fps where canvas2d reads 2–26
1403
+ (see Measured above). Falls back to canvas2d automatically when WebGL is
1404
+ unavailable or the shared context is lost; `meshBackendActive` says which drew. Switching re-rasters every
1405
+ mesh once (no reallocation), so it is fine to expose as a user setting.
1406
+
1407
+ On WebGL context loss (`webglcontextlost`), a player instance falls back to
1408
+ `canvas2d` for the rest of its life and never attempts a restore (#193): the
1409
+ shared context does not request restoration and ignores
1410
+ `webglcontextrestored`, so the very next frame draws on `canvas2d`
1411
+ (`meshBackendActive` in `dom` mode, `backendActive` in `canvas` mode) and
1412
+ stays there.
1413
+ - `renderer.meshBackendFallbackReason` (DOM) and `renderer.backendFallbackReason`
1414
+ (canvas) describe the last render's backend selection, including renders that
1415
+ reuse a raster. Both are `WebGLFallbackReason | null`. The value is `null`
1416
+ before the first render and whenever WebGL is selected successfully.
1417
+
1418
+ - `'not-requested'` means the caller chose `canvas2d`.
1419
+ - `'creation-failed'` means shared WebGL initialization failed. That failure
1420
+ is cached for this instance of the loaded module.
1421
+ - `'context-lost'` means the shared WebGL context was lost.
1422
+ - `'over-grant'` means WebGL could not draw this render within the usable
1423
+ drawing buffer. Successful tiling stays on WebGL.
1424
+ - `renderer.triangleExpand` — how far (canvas px) each triangle edge's clip is
1425
+ moved outward to close antialiased mesh seams (default 0.5). Also re-rasters every mesh once when changed.
1426
+ - `renderer.meshSourceRect` — what a canvas2d mesh triangle is drawn from:
1427
+ `'page'` (the whole page) or `'triangle'` (a sub-rect covering its clip). Both
1428
+ draw the same picture; the default is `'triangle'` on Linux WebKit, which
1429
+ garbles whole-page draws, and `'page'` elsewhere, because macOS Safari ran the
1430
+ sub-rect 12–15% slower (#25). Also on `CanvasRenderer` for its canvas2d
1431
+ fallback. Re-rasters every mesh once when changed.
1432
+ - `renderer.clipping` — apply the clips the frame carries (default `true`).
1433
+ Which slots a clip covers is decided where the frame is made — the player's
1434
+ adapter walks the draw order the way the runtime's draw loop does (one clip in
1435
+ force at a time, a second one met while one is in force ignored, the end slot
1436
+ inside its own clip). What the renderer writes is one CSS `clip-path` per
1437
+ element a clip covers, in that
1438
+ element's own local frame; nothing reaches the raster backends, and a clip is
1439
+ not part of the mesh dirty signature, so a mesh that held still keeps reusing
1440
+ its raster under a moving clip. **Writes happen on change only**: each
1441
+ clip-path is cached exactly as `transform` is, coordinates are quantized to
1442
+ 1/1000 of a local unit so float jitter cannot defeat that cache, and a static
1443
+ polygon over a static pose therefore costs **zero style writes per frame after
1444
+ the first** — `renderer.clipWriteCount` is the check, alongside
1445
+ `clipCount` (clips applied) and `clipSkipCount` (clips in the frame not
1446
+ applied: switched off, or a degenerate polygon; a clip the runtime itself
1447
+ ignores never reaches the frame). **The whole-skeleton fast path**: when one
1448
+ clip covers every slot of the frame, one `clip-path` goes on the root instead
1449
+ of one per element. The root is *your* element, so its inline `clip-path` is **borrowed,
1450
+ not taken** — saved on the first write and put back verbatim when the clip
1451
+ stops covering the frame, when `clipping` goes `false`, and by `dispose()`.
1452
+ Per-element clip-paths and the root clip-path are never both in force for the
1453
+ same clip. Two things to know about that path: the polygon is written in the
1454
+ root's **border box** frame, which is where absolutely-positioned slot elements
1455
+ start too *unless the root has a CSS border* (a border would offset the
1456
+ whole-skeleton clip by its width — keep borders off the render root, which is
1457
+ the normal shape for a 0×0 origin element); and an inverse clip never takes it,
1458
+ because its CSS form needs an outer ring around a box and the root has none.
1459
+ One further consequence of that path: a `clip-path` other than `none` makes an
1460
+ element a stacking context (CSS Masking), so a whole-skeleton clip isolates
1461
+ `mix-blend-mode` slots from backdrops *outside* the root — which a root
1462
+ carrying a `transform` (the usual pan/zoom stage) already does. Per-element
1463
+ clips do not change blending, since a blended slot is its own stacking context
1464
+ either way. Setting `clipping = false` removes every clip-path this renderer
1465
+ wrote.
1466
+
1467
+ **A zoomable stage.** The mesh tier rasters at `world × pixelRatio` in the
1468
+ root's own coordinates, and it cannot see a CSS transform above the root — so
1469
+ the most natural pan/zoom stage, `transform: scale(zoom)` on an ancestor, makes
1470
+ it oversample by `1/zoom²` in backing pixels until the zoom is folded in. The
1471
+ picture stays correct throughout, which is what makes this easy to ship: only
1472
+ the allocation and the frame rate move. Call `syncPixelRatio()` when the zoom
1473
+ settles, or set `pixelRatio = devicePixelRatio * zoom` yourself. Measured
1474
+ on-device (Chromium, dpr 2, stage under `scale(0.25)`, ~2.2 M CSS px on screen):
1475
+
1476
+ | scene | `pixelRatio` | `meshBackingPixels` | fps |
1477
+ | --- | --- | --- | --- |
1478
+ | 57 meshes | `devicePixelRatio` (2) | 139.1 Mpx | 14–21 |
1479
+ | 57 meshes | `dpr × zoom` (0.5) | 9.1 Mpx | 61 |
1480
+ | 92 meshes | `devicePixelRatio` (2) | 141.1 Mpx | 36–39 |
1481
+ | 92 meshes | `dpr × zoom` (0.5) | 9.1 Mpx | 60–61 |
1482
+