spine-html 1.26.0 → 1.27.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.
- package/README.md +26 -9
- package/dist/CanvasRenderer.d.ts.map +1 -1
- package/dist/_play-runtime.js +15022 -0
- package/dist/_play-runtime.js.map +1 -0
- package/dist/composed-camera.d.ts +30 -0
- package/dist/composed-camera.d.ts.map +1 -0
- package/dist/composed-take.d.ts +74 -0
- package/dist/composed-take.d.ts.map +1 -0
- package/dist/composed-take.js +906 -0
- package/dist/composed-take.js.map +1 -0
- package/dist/index.js +11 -14975
- package/dist/index.js.map +1 -1
- package/docs/MIGRATION.md +201 -0
- package/docs/REFERENCE.md +1419 -0
- package/docs/STABILITY.md +31 -0
- package/package.json +16 -1
|
@@ -0,0 +1,1419 @@
|
|
|
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
|
+
#### Camera and handoff
|
|
524
|
+
|
|
525
|
+
| Option | Default as of 2026-11-25 |
|
|
526
|
+
| --- | --- |
|
|
527
|
+
| `camera` | `'fixed'` |
|
|
528
|
+
| `backend` | `'webgl'`. Use `'canvas2d'` to select Canvas 2D. |
|
|
529
|
+
| `autoStart` | `true`. With `false`, call `take.advance(rigElapsed, cameraElapsed = rigElapsed)` in seconds and then `take.render()`. Pointer input and resize observation remain active. |
|
|
530
|
+
| `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. |
|
|
531
|
+
| `transitionMs` | 120 ms in each direction. |
|
|
532
|
+
| `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. |
|
|
533
|
+
| `pointerTurn` | Enabled. Set `false` for camera-only control. |
|
|
534
|
+
|
|
535
|
+
Use `take.setCamera()` with `'fixed'`, `'pan'` or `'parallax'`. Fixed plays
|
|
536
|
+
the authored pose with the camera at rest. Pan uses gain 1 on each plane.
|
|
537
|
+
In Parallax the backdrop defaults to gain −0.55 and the figure stays at gain 0.
|
|
538
|
+
A positive gain moves art opposite the camera. `maxDisplacement: { x, y }`
|
|
539
|
+
sets symmetric pointer bounds in CSS pixels before gains. Supply finite
|
|
540
|
+
nonnegative values and use zero to disable an axis.
|
|
541
|
+
|
|
542
|
+
`mode` is the active camera. `cameraExcursion` gives its configured pointer
|
|
543
|
+
bounds before gains. Use `cameraExcursionFor(mode)` to read those bounds for a
|
|
544
|
+
different mode. `cameraTarget` gives the requested pointer position in Y-up
|
|
545
|
+
CSS pixels. `offsets` maps each plane ID to its displayed shift in Y-down CSS
|
|
546
|
+
pixels, including baked travel.
|
|
547
|
+
|
|
548
|
+
In Parallax, pointer entry ramps the automatic plate motion to its setup
|
|
549
|
+
center before tracking the pointer. Pointer exit ramps back to the current
|
|
550
|
+
automatic phase. The take keeps advancing through the handoff. With discovered
|
|
551
|
+
turn dials, pointer X drives yaw and body and pointer Y drives pitch. Dial
|
|
552
|
+
targets clamp to the compiled endpoints. The handoff blends between these
|
|
553
|
+
targets and the live bone-local values from animation keys or the setup pose.
|
|
554
|
+
`turnReadouts` reports the last posed values and the current pointer request's
|
|
555
|
+
`clamped` status.
|
|
556
|
+
|
|
557
|
+
#### Plates and automatic motion
|
|
558
|
+
|
|
559
|
+
A plate with compiled travel can declare `baked: { bone: 'plate-bone' }`.
|
|
560
|
+
Bind the region's direct root-child bone with a linear translate loop from
|
|
561
|
+
setup center back to setup center. In Parallax, baked travel drives that plate
|
|
562
|
+
outside the stage pointer. Inside, the handoff brings the plate to center and
|
|
563
|
+
pointer motion replaces its baked displacement. An overlay with a comparable
|
|
564
|
+
horizontal baked track can infer its gain by multiplying the backdrop's
|
|
565
|
+
resolved gain by the ratio of the overlay's travel amplitude to the backdrop's.
|
|
566
|
+
Give other overlays an explicit finite gain.
|
|
567
|
+
|
|
568
|
+
For a camera-only sweep in Parallax, give `autoSweep` a positive finite
|
|
569
|
+
`periodSeconds` and finite nonnegative `maxDisplacement` axes in CSS pixels.
|
|
570
|
+
The sine sweep follows the player's track time. Use plates without baked
|
|
571
|
+
travel for this option.
|
|
572
|
+
|
|
573
|
+
The backdrop quad must cover the stage across the selected motion envelope.
|
|
574
|
+
At each displayed state, including Fixed, the layers below the first figure
|
|
575
|
+
slot must composite to opaque pixels across the stage at its backing
|
|
576
|
+
resolution. An overlay can be smaller than the stage and can fill a hole in
|
|
577
|
+
the backdrop when it is opaque and below the figure.
|
|
578
|
+
|
|
579
|
+
#### Composed take refusals
|
|
580
|
+
|
|
581
|
+
Use `ComposedTakeError.code` to handle a refusal. Model and page loading can
|
|
582
|
+
also report their own errors. If a moving camera fails coverage and Fixed
|
|
583
|
+
passes its coverage check, mounting can resolve in Fixed with `take.refusal`
|
|
584
|
+
set. `setCamera()` can switch to Fixed and still throw the coverage refusal.
|
|
585
|
+
A later layout or frame change can also fall back to Fixed. If a frame
|
|
586
|
+
cannot be drawn, the take hides the canvas and stops its frame clock.
|
|
587
|
+
Render-time composition refusals are available on `take.refusal`. A
|
|
588
|
+
successful `setCamera()` clears that status.
|
|
589
|
+
|
|
590
|
+
| Code | Condition |
|
|
591
|
+
| --- | --- |
|
|
592
|
+
| `COMPOSED_STAGE_REQUIRED` | Missing or invalid stage |
|
|
593
|
+
| `COMPOSED_LOOP_REQUIRED` | Missing `loop: true` or a positive-duration animation |
|
|
594
|
+
| `COMPOSED_SLOT_PARTITION` | Missing, repeated or invalid drawable slot binding |
|
|
595
|
+
| `COMPOSED_CROSS_PLANE_CLIP` | An active attachment clip covers multiple planes |
|
|
596
|
+
| `COMPOSED_BACKDROP_COVERAGE` | Invalid plate geometry, inadequate stage coverage or unavailable opacity readback |
|
|
597
|
+
| `COMPOSED_INVALID_DISPLACEMENT` | Invalid excursion, sweep period, transition duration or gain |
|
|
598
|
+
| `COMPOSED_INVALID_CAMERA` | Unrecognized mode |
|
|
599
|
+
| `COMPOSED_PLATE_TRACK` | Unsupported plate track or gain binding, or a sweep combined with baked travel |
|
|
600
|
+
|
|
601
|
+
#### Reusing the demo controls
|
|
602
|
+
|
|
603
|
+
Import `mountComposedParallax` from [`samples/composed-parallax.ts`](https://github.com/rig-c/play/blob/main/samples/composed-parallax.ts)
|
|
604
|
+
to reuse the demo controls with another take. Pass its `take` options and
|
|
605
|
+
`poseDuration`, and optionally pass `planeLabels` and `inferredGains` for the
|
|
606
|
+
readouts. The page supplies the stage, camera control and readouts. The caller
|
|
607
|
+
supplies the fixture selector and model URLs.
|
|
608
|
+
|
|
609
|
+
See the [public fixture and its producer receipts](https://github.com/rig-c/play/blob/main/tests/fixtures/composed-direction/README.md).
|
|
610
|
+
|
|
611
|
+
### Drawing some slots only
|
|
612
|
+
|
|
613
|
+
`slots` is a draw filter — an allow list of slot names or a predicate — settable up
|
|
614
|
+
front and on a live player. The pose is the whole rig's whatever the filter:
|
|
615
|
+
bones, constraints, physics, `bone()`, `adjust`, events and tracks see no filter;
|
|
616
|
+
only the draw does, in both modes, and `bounds()` reads the drawn slots. A
|
|
617
|
+
clipping slot the filter leaves out does not clip. An allow list naming a slot
|
|
618
|
+
the document does not have is refused by name.
|
|
619
|
+
|
|
620
|
+
```ts
|
|
621
|
+
const hand = new RigPlayer(frontRoot, assets, { slots: ['hand_f', 'arm_f_lo'] });
|
|
622
|
+
player.slots = (slot) => !slot.startsWith('weapon');
|
|
623
|
+
```
|
|
624
|
+
|
|
625
|
+
Two players over one `ModelAssets` share the load but each poses the rig. To
|
|
626
|
+
pose it once and draw it twice — a hand drawn again in front of another
|
|
627
|
+
character — give a second renderer this player's pose under another filter:
|
|
628
|
+
|
|
629
|
+
```ts
|
|
630
|
+
const front = new DomRenderer(frontRoot, assets.regionImages, assets.pageImages);
|
|
631
|
+
// each frame, after player.frame(dt):
|
|
632
|
+
front.render(player.posedFrame(['hand_f', 'arm_f_lo']));
|
|
633
|
+
```
|
|
634
|
+
|
|
635
|
+
### Attachment sets (`sets.json`)
|
|
636
|
+
|
|
637
|
+
A build from `@rig-c/parts` (or authored alongside a rig) may ship a `sets.json`
|
|
638
|
+
sidecar beside `skeleton.model.json` declaring named attachment sets — an
|
|
639
|
+
expression, a viseme, a side view — under spec `"rig-parts-sets/1"` or
|
|
640
|
+
`"spine-parts-sets/1"`:
|
|
641
|
+
|
|
642
|
+
```json
|
|
643
|
+
{
|
|
644
|
+
"spec": "rig-parts-sets/1",
|
|
645
|
+
"sets": {
|
|
646
|
+
"smile": {
|
|
647
|
+
"slots": { "face": "face_smile", "prop": "prop_star" },
|
|
648
|
+
"hides": []
|
|
649
|
+
},
|
|
650
|
+
"wink": {
|
|
651
|
+
"slots": { "face": "face_wink" },
|
|
652
|
+
"hides": ["prop"]
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
```
|
|
657
|
+
|
|
658
|
+
`loadModel` probes `sets.json` in the model document's directory by default
|
|
659
|
+
(treating a 404 as "no sets"; pass `setsUrl: null` to skip the probe, or a URL
|
|
660
|
+
string to require one at another path) and validates every slot and attachment
|
|
661
|
+
name against the model document. `player.sets()` (and `assets.sets`) returns the
|
|
662
|
+
declared `readonly RigSet[]` (`{ name, slots, hides }`), and `player.setSet(name)`
|
|
663
|
+
switches the active set at runtime (#134):
|
|
664
|
+
|
|
665
|
+
```ts
|
|
666
|
+
player.sets(); // [{ name: 'smile', slots: { ... }, hides: [] }, ...]
|
|
667
|
+
player.setSet('smile'); // covered slots take the set's attachments; <slot>_still and hides are hidden
|
|
668
|
+
player.set; // 'smile'
|
|
669
|
+
player.setSet(null); // restore base / track attachments
|
|
670
|
+
```
|
|
671
|
+
|
|
672
|
+
The active set is applied immediately to the held pose (including the setup pose
|
|
673
|
+
before `play`) and after track evaluation on every subsequent `advance`, so a
|
|
674
|
+
track key on a covered slot is overridden while the set is active and restored
|
|
675
|
+
on the next frame when cleared with `setSet(null)`. Uncovered slots keep their
|
|
676
|
+
track attachments, mesh deforms and sequence frames untouched; when no set is
|
|
677
|
+
active (`null`), track evaluation runs with zero extra work and produces
|
|
678
|
+
byte-identical poses. An unknown set name throws by name; on a build without
|
|
679
|
+
`sets.json`, `sets()` is empty (`[]`) and `setSet` throws.
|
|
680
|
+
|
|
681
|
+
**Several sets at once** (#168): sets that touch disjoint slots can be active
|
|
682
|
+
together — a mouth viseme driven by audio beside an arm gesture driven by
|
|
683
|
+
input, without building every combination as its own set:
|
|
684
|
+
|
|
685
|
+
```ts
|
|
686
|
+
player.setSets(['viseme_o', 'gesture_chin']); // exactly these, together
|
|
687
|
+
player.removeSet('viseme_o'); // the gesture stays
|
|
688
|
+
player.addSet('viseme_a'); // beside the active ones; already active = no change
|
|
689
|
+
player.activeSets; // ['viseme_a', 'gesture_chin'] in sets.json order
|
|
690
|
+
player.set; // null: several are active (one active → its name)
|
|
691
|
+
player.setSets([]); // restore base / track attachments
|
|
692
|
+
```
|
|
693
|
+
|
|
694
|
+
A set *touches* every slot it covers, every slot it `hides` and the
|
|
695
|
+
`<base>_still` companion it hides. Two active sets touching the same slot are
|
|
696
|
+
refused by name — `sets "viseme_o" and "talk_point" both touch slot "mouth"` —
|
|
697
|
+
and nothing changes; precedence is never guessed. Disjoint sets compose as the
|
|
698
|
+
union of each alone, whatever the order they were named or added in, and every
|
|
699
|
+
rule above (applied to the held pose, after track evaluation, uncovered slots
|
|
700
|
+
untouched) holds for the composition. `setSet(name)` keeps meaning *exactly this
|
|
701
|
+
one* (`setSets([name])`) and `setSet(null)` is `setSets([])`; an unknown or
|
|
702
|
+
repeated name throws by name. `slotIdentity()` reports the list as `sets`
|
|
703
|
+
beside `set`.
|
|
704
|
+
|
|
705
|
+
**Drawn bones** (#170): a set from `@rig-c/parts` that replaces a limb
|
|
706
|
+
(a *gesture* subset set) carries `drawn` — the world rotation, in degrees
|
|
707
|
+
(CCW, Y up), each of its bones was painted at — and its attachments are
|
|
708
|
+
placed in the frame of the bones posed there:
|
|
709
|
+
|
|
710
|
+
```json
|
|
711
|
+
"wave": {
|
|
712
|
+
"slots": { "arm_upper": "arm_upper_wave", "arm_lower": "arm_lower_wave" },
|
|
713
|
+
"drawn": { "shoulder": 50, "elbow": 95 }
|
|
714
|
+
}
|
|
715
|
+
```
|
|
716
|
+
|
|
717
|
+
While such a set is active its bones are posed at those angles, the way
|
|
718
|
+
`rig-parts check --set` poses them: in document order, each drawn bone's
|
|
719
|
+
local rotation is the drawn angle less its world rotation at local 0 under
|
|
720
|
+
its already-posed parents (no constraint applied), computed once when the set
|
|
721
|
+
is activated. On a track that local rotation replaces the clip's rotation
|
|
722
|
+
of that bone on every pose, before `adjust` (so `adjust` still has the last
|
|
723
|
+
word); every other bone keeps playing. Activating or clearing a drawn set
|
|
724
|
+
poses the held pose again at the same time. Two active sets drawing the same
|
|
725
|
+
bone are refused by name, as two sets touching one slot are. A `drawn` naming
|
|
726
|
+
a bone the document does not have is refused when `sets.json` is loaded.
|
|
727
|
+
|
|
728
|
+
**Physics under a drawn bone** (#173). A physics chain hung from a bone a set
|
|
729
|
+
re-poses — a sleeve under a raised arm — reads the jump to the drawn angle as
|
|
730
|
+
motion: the constraint remembers where its bone was and pointed, so the
|
|
731
|
+
switch kicks it (on the test rig `drape`, a 110° raise throws the sleeve's
|
|
732
|
+
tip about 297 units off the arm in the switch itself, against an idle
|
|
733
|
+
frame-to-frame range of 1.5). Every set call takes an option for the chains
|
|
734
|
+
under the bones the switch re-poses:
|
|
735
|
+
|
|
736
|
+
```ts
|
|
737
|
+
player.setSets(['raise'], { physics: 'carry' }); // also setSet, addSet, removeSet
|
|
738
|
+
```
|
|
739
|
+
|
|
740
|
+
- `'carry'` moves each affected constraint's remembered state by the rigid
|
|
741
|
+
turn of its deepest re-posed ancestor, so the chain keeps its pose relative
|
|
742
|
+
to the arm and goes on swinging from there (the switch itself moves the
|
|
743
|
+
sleeve 0 relative to the arm; gravity then re-settles it in the turned pose,
|
|
744
|
+
which is physics and not the switch).
|
|
745
|
+
- `'reset'` restarts each affected constraint at the new pose, as a physics
|
|
746
|
+
`reset` key does: the chain snaps straight along its bones (17 units on the
|
|
747
|
+
same raise) and settles from there.
|
|
748
|
+
- Absent, nothing changes: today's behaviour, frame for frame. This stays the
|
|
749
|
+
default.
|
|
750
|
+
|
|
751
|
+
`'carry'` is recommended: on `drape` it moves the sleeve 0 relative to the arm
|
|
752
|
+
at the switch and 0 at the deactivation, where `'reset'` moves it 17 units at
|
|
753
|
+
the switch and 118 at the deactivation (no option: 297 and 298).
|
|
754
|
+
|
|
755
|
+
A constraint is affected when its bone is a bone whose drawn rotation the call
|
|
756
|
+
adds, removes or changes, or a descendant of one; every other chain is not
|
|
757
|
+
touched. The option does nothing before `play` (the setup pose carries no
|
|
758
|
+
physics state) and nothing when no physics hangs under a re-posed bone. Three limits:
|
|
759
|
+
|
|
760
|
+
- Carry moves the positions and direction the constraint remembers; a
|
|
761
|
+
constraint with `x`/`y` keeps its translation offsets along the world axes,
|
|
762
|
+
unturned.
|
|
763
|
+
- A drawn bone nested under a carried chain reads its new world from the
|
|
764
|
+
chain's state before the carry.
|
|
765
|
+
- A later `seek` replays from the start with the sets then active, as it
|
|
766
|
+
always has, so it does not reproduce a carried switch.
|
|
767
|
+
|
|
768
|
+
**Easing a drawn set in and out** (#174). A drawn set snaps its bones to the
|
|
769
|
+
drawn angles in one frame. `ease` turns them there over a duration instead,
|
|
770
|
+
and swaps the attachments halfway, the way an alternate drawing takes over
|
|
771
|
+
at a middle angle:
|
|
772
|
+
|
|
773
|
+
```ts
|
|
774
|
+
player.setSets(['wave_r'], { ease: 0.5 }); // also setSet, addSet, removeSet
|
|
775
|
+
player.setSets([], { ease: 0.5 }); // and back
|
|
776
|
+
```
|
|
777
|
+
|
|
778
|
+
- **The curve.** Each bone whose drawn rotation the call adds, removes or
|
|
779
|
+
changes turns from what it shows to its new local rotation along the
|
|
780
|
+
shorter way: `start + shortestΔ(start, end) · smoothstep(u)`, with
|
|
781
|
+
`u = elapsed / ease`. Going on, the start is the clip's value at the time
|
|
782
|
+
(it moves with the clip) and the end the drawn local; going off, the start
|
|
783
|
+
is the drawn local and the end the clip's value. So the progress from start
|
|
784
|
+
to end never leaves `[0, 1]` and never turns back, while the clip plays
|
|
785
|
+
underneath. On `@rig-c/parts`' public wind example with its gesture set
|
|
786
|
+
(`wave_r`, 0.5 s), it is 0 to 1 and non-decreasing on every frame, on and
|
|
787
|
+
off; on a clip that holds the arm still, the sleeve's world angle goes
|
|
788
|
+
−119.32° → −110° and back with no overshoot.
|
|
789
|
+
- **The swap.** The held pose draws the attachments it showed until the frame
|
|
790
|
+
whose `u` is nearest ½, then the set's (a tie goes to the later frame; the
|
|
791
|
+
next step is predicted from the current one, so a constant `dt` lands on
|
|
792
|
+
the nearest frame). On the wind example at `frame(1/60)`, 0.5 s swaps on
|
|
793
|
+
frame 15 and 0.25 s on frame 8. `activeSets`, `set` and `slotIdentity().sets`
|
|
794
|
+
name the call's sets from the call on; `slotIdentity().slots` reports what
|
|
795
|
+
the pose draws, so before the swap it shows the previous attachments.
|
|
796
|
+
- **The end.** On the frame the elapsed time reaches `ease`, the player is in
|
|
797
|
+
exactly the instant switch's state: from then on every bone matches an
|
|
798
|
+
instant switch made at the same frame (0° measured) and the slot identity
|
|
799
|
+
too.
|
|
800
|
+
- **Time.** The elapsed time is the player's step (`dt × timeScale`): a
|
|
801
|
+
paused player, or a step of 0, holds the ease where it is. Before `play`
|
|
802
|
+
there is nothing to step and the switch is instant; so is a call that
|
|
803
|
+
re-poses no bone. A `seek` or a skin change lands an ease in flight at
|
|
804
|
+
once.
|
|
805
|
+
- **A call during an ease** starts a new one from the angles shown (no jump:
|
|
806
|
+
reversing a 0.5 s ease at 0.3 makes no frame-to-frame step larger than the
|
|
807
|
+
ease's own), and the attachment swap starts again from what is drawn. A
|
|
808
|
+
call without `ease` during an ease lands it at once.
|
|
809
|
+
- `ease: 0`, or no `ease`, is the instant switch, frame for frame. Anything
|
|
810
|
+
but a finite number at or above 0 is refused by name before anything
|
|
811
|
+
changes.
|
|
812
|
+
|
|
813
|
+
With physics: `ease` and `physics: 'carry'` carry the chains under the eased
|
|
814
|
+
bones on every eased frame — before each step, the turn the frame's blend
|
|
815
|
+
makes is read as #173's switch is (a trial pose at the previous time) and
|
|
816
|
+
the chains are moved by it — so the ease's own turn is not read as motion.
|
|
817
|
+
`physics: 'reset'` with `ease` restarts them once, at the call. On `drape`
|
|
818
|
+
(0.5 s raise, sleeve tips in the arm's frame): the ease alone moves the
|
|
819
|
+
sleeve up to 30 units a frame relative to the arm (the chain reads the turn
|
|
820
|
+
as motion), ease + carry at most 3.9 on the `idle` clip (its idle ranges are
|
|
821
|
+
1.5 hanging and 4.2 raised) and 2.3 on `shift` (0.85 and 0.07), where
|
|
822
|
+
gravity re-settles the chain in the turning arm's frame (with gravity at 0,
|
|
823
|
+
0.83 against 0.84).
|
|
824
|
+
|
|
825
|
+
`sets.json` keys are read strictly. Besides `slots`, `hides` and `drawn`, a
|
|
826
|
+
set may carry `drawnLength`, `registration`, `threshold` and `focus`, which
|
|
827
|
+
parts writes and which place nothing under `check --set`: play reads past them
|
|
828
|
+
by name (validating `focus`, when present, as `[x, y]` of two finite numbers)
|
|
829
|
+
and gives them no meaning. Any other key, on a set or on the document (which
|
|
830
|
+
takes `spec`, `sets` and `threshold`), is refused by name rather than ignored.
|
|
831
|
+
|
|
832
|
+
To switch one driver's set while another stays — a new viseme while a gesture
|
|
833
|
+
holds — name the new list in one call (`setSets(['viseme_a', 'gesture_chin'])`)
|
|
834
|
+
or `removeSet` then `addSet`; the first re-poses once, the second twice.
|
|
835
|
+
|
|
836
|
+
### Slot identity snapshot (`slotIdentity()`)
|
|
837
|
+
|
|
838
|
+
To inspect which attachment key, owning skin and visibility state each slot
|
|
839
|
+
holds on the current frame — for a parts explorer or review overlay — without
|
|
840
|
+
`seek`, `repose`, or restarting physics (#144):
|
|
841
|
+
|
|
842
|
+
```ts
|
|
843
|
+
const snap = player.slotIdentity();
|
|
844
|
+
// {
|
|
845
|
+
// generation: number, // matches player.generation and player.posedFrame().generation
|
|
846
|
+
// set: string | null, // the one active set (player.set); null when none or several
|
|
847
|
+
// sets: readonly string[], // every active set (player.activeSets), sets.json order
|
|
848
|
+
// skin: string | null, // active skin name (player.skin ?? null)
|
|
849
|
+
// slots: readonly [ // every slot in posed draw order (z = 0 .. slots.length - 1)
|
|
850
|
+
// {
|
|
851
|
+
// slot: string,
|
|
852
|
+
// z: number,
|
|
853
|
+
// attachment: string | null, // resolved attachment key when drawn, null when not drawn
|
|
854
|
+
// skin: string | null, // skin owning the resolved attachment ('default' or named skin), or null
|
|
855
|
+
// reason: 'hidden' | 'no-attachment' | 'timeline-null' | 'set-hide' | null,
|
|
856
|
+
// },
|
|
857
|
+
// ...
|
|
858
|
+
// ],
|
|
859
|
+
// }
|
|
860
|
+
```
|
|
861
|
+
|
|
862
|
+
Every slot in the posed draw order (`z = 0 .. slots.length - 1`, hidden and null
|
|
863
|
+
ones included) appears in `snap.slots`:
|
|
864
|
+
|
|
865
|
+
- Drawn slots (`reason: null`) appear in the same `z` order as
|
|
866
|
+
`player.posedFrame().order`, naming the resolved attachment key (`attachment`)
|
|
867
|
+
and the skin that owns it (`skin`).
|
|
868
|
+
- Non-drawn slots report `attachment: null`, `skin: null`, and why they are
|
|
869
|
+
absent from `posedFrame().order`:
|
|
870
|
+
- `'set-hide'` — hidden by an active attachment set (`set.hides` or a
|
|
871
|
+
`<base>_still` companion of a slot the set covers or hides).
|
|
872
|
+
- `'timeline-null'` — cleared by an active attachment timeline key (`null`).
|
|
873
|
+
- `'no-attachment'` — no attachment in the setup pose or under the active skin
|
|
874
|
+
(or a non-drawable attachment kind such as clipping/boundingbox/path/point).
|
|
875
|
+
- `'hidden'` — filtered out by `player.slots` or on an inactive bone under the
|
|
876
|
+
current skin.
|
|
877
|
+
- `snap.generation` ticks monotonically with `player.generation` and
|
|
878
|
+
`player.posedFrame().generation` whenever the held pose, active set, active
|
|
879
|
+
skin or slot filter changes. The returned snapshot is frozen and cached per
|
|
880
|
+
generation, so reading it repeatedly on a held pose is allocation-free and
|
|
881
|
+
mutates no pixel or physics state.
|
|
882
|
+
|
|
883
|
+
### Several tracks
|
|
884
|
+
|
|
885
|
+
A base on track 0, a layer over it, a one-shot played once and mixed back out —
|
|
886
|
+
rig-c's live tracks (`openTracks`), whose mixing is the Spine runtime's
|
|
887
|
+
`AnimationState` held at tolerance 0:
|
|
888
|
+
|
|
889
|
+
```ts
|
|
890
|
+
player.play('idle'); // track 0, as always
|
|
891
|
+
player.play('smile', { track: 1, loop: false, mix: 0.2 }); // held at its end, mixed in over 0.2 s
|
|
892
|
+
player.play('wave', { track: 2, loop: false, mix: 0.1 }); // a one-shot…
|
|
893
|
+
player.queueClear(2, { mix: 0.1 }); // …mixed back out over its last 0.1 s
|
|
894
|
+
player.queue('idle_b', { track: 0, mix: 0.3 }); // after the current idle cycle completes
|
|
895
|
+
player.clear(1, { mix: 0.2 }); // the layer gone, the base showing through
|
|
896
|
+
player.entry(2); // { animation, loop, trackTime, animationTime, duration, alpha, additive } | null
|
|
897
|
+
player.play('blink', { track: 3, alpha: 0.6 }); // the same clip at a weight…
|
|
898
|
+
player.setAlpha(3, 0.85); // …changed while it plays
|
|
899
|
+
player.play('breath', { track: 4, additive: true }); // adds to what the tracks below posed
|
|
900
|
+
```
|
|
901
|
+
|
|
902
|
+
**Weight and additive layers** (rig-c 2.39.0, the runtime's `TrackEntry.alpha` and
|
|
903
|
+
`additive`): `alpha` (0..1, default 1) multiplies every timeline the entry applies;
|
|
904
|
+
`setAlpha(track, alpha)` changes the current entry's weight from the next pose and
|
|
905
|
+
re-poses the held pose. It does not touch events — an entry fires at any alpha, 0
|
|
906
|
+
included, and one mixing out fires none — or attachments: the current entry keeps
|
|
907
|
+
its attachments at any alpha, one mixing out keeps none. `additive: true`, fixed
|
|
908
|
+
when the entry is set or queued, adds the entry's keyed bone and deform values to
|
|
909
|
+
what the tracks below posed instead of replacing them, so a layer keying the same
|
|
910
|
+
bone channels as an idle does not cover its motion; a rotation is added as it
|
|
911
|
+
stands, with no shortest-angle wrap, and an additive entry mixing out fades with its
|
|
912
|
+
alpha and is never held. Colour, attachment and event timelines apply as on a
|
|
913
|
+
replacing entry. A weight below 1 or an additive entry composes, as a mix does.
|
|
914
|
+
|
|
915
|
+
`play(name)` keeps meaning what it meant: a plain play on track 0 runs on rig-c's
|
|
916
|
+
single live track, which poses everything the core poses. The first call that
|
|
917
|
+
composes — a `mix`, a `track` above 0, a `queue`, a `clear` — moves the player onto
|
|
918
|
+
the tracks, carrying the single track over by **replay** (its animation set, pose 0
|
|
919
|
+
taken, stepped to its time in `seekStep` increments — one pose per step played, so
|
|
920
|
+
on a stage that idled a while that is one long frame; the core offers no hand-over
|
|
921
|
+
of a live track's state). To never pay it, stand the player on the tracks from the
|
|
922
|
+
start: `new RigPlayer(root, assets, { tracks: true })`. Pick the single track for a
|
|
923
|
+
rig whose animations key what the tracks do not mix (below); pick the tracks for
|
|
924
|
+
layering. Either way, after the first `mix`, `track` above 0, `queue` or `clear`,
|
|
925
|
+
`seek` and `skin` are refused by name, since the player cannot replay a composition
|
|
926
|
+
to a time — step it forward instead.
|
|
927
|
+
Every entry mixes from the setup pose each step, so `adjust` writes still last one
|
|
928
|
+
pose. **What the tracks do not mix**, in rig-c's words at `play`/`queue`: an
|
|
929
|
+
animation keying a constraint (ik, transform, path, physics, slider), a sequence,
|
|
930
|
+
the draw order, or a path's deform is refused when it is set on the tracks — it
|
|
931
|
+
plays on the single track only. `'event'` carries `track`; a one-shot that is
|
|
932
|
+
mixing out fires nothing. `'complete'` is per track, the player's rule: a looping
|
|
933
|
+
entry each cycle, a held one when it reaches its duration, and an entry that is
|
|
934
|
+
replaced — by `play`, or by the queued entry that starts at its completion less the
|
|
935
|
+
mix — completes no more than it fires.
|
|
936
|
+
|
|
937
|
+
### Adjusting bones
|
|
938
|
+
|
|
939
|
+
A per-pose write to bone locals — a breath's scale, a look's rotation, a mouth
|
|
940
|
+
driven while the body holds still:
|
|
941
|
+
|
|
942
|
+
```ts
|
|
943
|
+
const player = new RigPlayer(root, assets, {
|
|
944
|
+
adjust: (bones) => { bones.bone('mouth').scaleY = 1 + openness; },
|
|
945
|
+
});
|
|
946
|
+
player.adjust = null; // or set it later; setting it re-poses the held pose at once
|
|
947
|
+
```
|
|
948
|
+
|
|
949
|
+
The function runs once per pose, after the animation's timelines and before the
|
|
950
|
+
world transforms, constraints and physics — `@rig-c/core/core`'s `openTrack({ adjust })`,
|
|
951
|
+
which rig-c holds to the Spine runtime at tolerance 0. **A write lasts one
|
|
952
|
+
pose.** The core poses every step from the setup pose, so a value you want held
|
|
953
|
+
is written again each pose and nothing compounds; a 0.8 caller that multiplied a
|
|
954
|
+
channel on a skeleton it kept between frames writes the value it wants, every
|
|
955
|
+
pose. It runs on every pose the animation is applied to, the first one after
|
|
956
|
+
`play` included, and `seek` and a `mode` change keep it.
|
|
957
|
+
|
|
958
|
+
A paused player and a zero step re-pose nothing, so a change the function would
|
|
959
|
+
make is not seen until the next step — unless you ask: setting `player.adjust`
|
|
960
|
+
re-poses the held pose at the same track time, and `player.repose()` does the
|
|
961
|
+
same for a function whose own state changed (the mouth above), without stepping,
|
|
962
|
+
firing events or drawing. A non-finite value, a bone the document does not have,
|
|
963
|
+
or an error the function throws refuses that step in the core's words, and the
|
|
964
|
+
track is reopened by the next `play` or `seek`.
|
|
965
|
+
|
|
966
|
+
The callback also receives a `BoneAdjustContext` from the core:
|
|
967
|
+
|
|
968
|
+
```ts
|
|
969
|
+
player.adjust = (bones, ctx) => {
|
|
970
|
+
bones.bone('head').rotation = 12 * (ctx.trackTime ?? 0);
|
|
971
|
+
};
|
|
972
|
+
```
|
|
973
|
+
|
|
974
|
+
`ctx.trackTime` is the **current track-0 entry's unwrapped seconds**, starting at
|
|
975
|
+
0 for each new entry. Loops do not wrap it, and a nonlooping entry keeps counting
|
|
976
|
+
past its duration. `ctx.animation` names that entry. Without a track-0 entry both
|
|
977
|
+
are null; an explicit empty entry has **numeric trackTime and null animation**.
|
|
978
|
+
Upper tracks supply no fallback. `ctx.globalTime` is the core walk's running sum
|
|
979
|
+
of steps in seconds, so it can differ from a new entry's time. Neither clock is
|
|
980
|
+
wall time, wrapped animation time, nor the physics clock's small lead. Unary
|
|
981
|
+
callbacks remain compatible. The hook runs once after composition, including a
|
|
982
|
+
crossfade, rather than once for each contributing entry.
|
|
983
|
+
|
|
984
|
+
Seek evaluates its replay times (`seekStep` plus any final remainder), independent
|
|
985
|
+
of the currently displayed player time. Exact cache hits may reuse a pose without
|
|
986
|
+
calling the hook. A continuous walk and seek are bit-identical for an **unchanged
|
|
987
|
+
patch and matched history**: the same animation, environment, adjustment, reset
|
|
988
|
+
and step partition. Closed-over callback state still needs `repose()` or the
|
|
989
|
+
adjust setter to invalidate cached poses. Pause, zero advance and renderer mode
|
|
990
|
+
changes add no evaluations; explicit `repose()` keeps the same context time.
|
|
991
|
+
|
|
992
|
+
### Discovering turn dials
|
|
993
|
+
|
|
994
|
+
`discoverTurnDials(model, durations?)` reads the parsed `skeleton.model.json`
|
|
995
|
+
and returns `TurnDial[]` in yaw, pitch, body order. It uses the animation
|
|
996
|
+
durations serialized in the model by default. Pass the matching
|
|
997
|
+
`assets.animations` from `loadModel` to use the runtime durations instead.
|
|
998
|
+
With a supplied list, an animation missing from that list skips its dial.
|
|
999
|
+
|
|
1000
|
+
Each dial carries its `axis`, exact `bone` and `slider` names, writable
|
|
1001
|
+
`channel` in `BoneLocals`, inclusive `min` and `max` in that channel's local
|
|
1002
|
+
units, and a human-readable `provenance` string naming the compiled binding.
|
|
1003
|
+
The recognized bones are `yaw_dial`, `pitch_dial` and `body_yaw_dial`. A
|
|
1004
|
+
`body_turn` animation also identifies a body slider on a custom bone. Matching
|
|
1005
|
+
ignores one nonempty prefix before the first colon, so a single composed actor's
|
|
1006
|
+
dials still use the exact namespaced names when applied.
|
|
1007
|
+
|
|
1008
|
+
An axis needs exactly one slider binding to an existing bone. Discovery skips
|
|
1009
|
+
ambiguous axes, world-space or looping sliders, unsupported channels, missing
|
|
1010
|
+
or nonpositive durations, and mappings that cannot produce a finite,
|
|
1011
|
+
nonconstant range containing zero. The endpoints come from inverting the
|
|
1012
|
+
compiled slider mapping at animation time zero and at its duration, including
|
|
1013
|
+
when the slider scale is negative. If two axes drive the same bone and channel,
|
|
1014
|
+
the earlier discovered axis takes precedence.
|
|
1015
|
+
|
|
1016
|
+
Use `normalizedDial(value, dial)` to map a control from `[-1, 1]` into the
|
|
1017
|
+
dial range. The function clamps input at the ends and interpolates from neutral
|
|
1018
|
+
to each endpoint independently, preserving zero for asymmetric ranges.
|
|
1019
|
+
|
|
1020
|
+
```ts
|
|
1021
|
+
import { discoverTurnDials, normalizedDial, type TurnAxis } from '@rig-c/play';
|
|
1022
|
+
|
|
1023
|
+
const dials = discoverTurnDials(compiledModel, assets.animations);
|
|
1024
|
+
const input: Partial<Record<TurnAxis, number>> = { yaw: 0.5, pitch: -0.25 };
|
|
1025
|
+
player.adjust = (bones) => {
|
|
1026
|
+
for (const dial of dials) {
|
|
1027
|
+
bones.bone(dial.bone)[dial.channel] = normalizedDial(input[dial.axis] ?? 0, dial);
|
|
1028
|
+
}
|
|
1029
|
+
};
|
|
1030
|
+
```
|
|
1031
|
+
|
|
1032
|
+
Both helpers work without a player or a DOM. See the [stability
|
|
1033
|
+
inventory](STABILITY.md#turn-dials) for the public contract.
|
|
1034
|
+
|
|
1035
|
+
### Live physics parameters
|
|
1036
|
+
|
|
1037
|
+
```ts
|
|
1038
|
+
player.play('hang');
|
|
1039
|
+
player.setPhysicsParameters('link_1_phys', { damping: 0.4, wind: 8 });
|
|
1040
|
+
player.readPhysicsParameters('link_1_phys'); // { override, effective }
|
|
1041
|
+
player.clearPhysicsParameters('link_1_phys');
|
|
1042
|
+
```
|
|
1043
|
+
|
|
1044
|
+
`setPhysicsParameters(name, patch)` forwards a per-player patch of `strength`,
|
|
1045
|
+
`damping`, `inertia`, `wind`, `gravity`, and `mix` to the core. Omitted fields keep
|
|
1046
|
+
their standing override. Values are runtime scalars with no clamping, conversion,
|
|
1047
|
+
new clock or solver. The core applies them **after authored/keyed values and
|
|
1048
|
+
sliders, before the integrator**. Unknown constraints, a non-physics constraint,
|
|
1049
|
+
unknown fields and non-finite/non-number values are refused atomically by name.
|
|
1050
|
+
These methods require a live track: before `play`/`queue`, set, read and clear
|
|
1051
|
+
refuse with `no live track` instead of creating one. The model and other players
|
|
1052
|
+
sharing its assets are untouched.
|
|
1053
|
+
|
|
1054
|
+
`PhysicsParameterRead` contains detached readonly snapshots: `override` is the
|
|
1055
|
+
pending patch or null; `effective` is the six values from the last active
|
|
1056
|
+
evaluation, or null until evaluated. An inactive constraint can retain its last
|
|
1057
|
+
active values within that live core instance. Setting or clearing changes no
|
|
1058
|
+
pose, time or physics state, and **does not evaluate**: effective keeps the last
|
|
1059
|
+
values until a normal evaluation (or an explicitly requested `repose()`). Clear
|
|
1060
|
+
removes the patch; authored keys resume at the next evaluation. It preserves
|
|
1061
|
+
integrated history and does not instantly undo the motion caused by old values.
|
|
1062
|
+
|
|
1063
|
+
The player retains the **current standing patch** across new play, seek, skin
|
|
1064
|
+
replay and promotion to composed tracks. Like `environment()`, it records no
|
|
1065
|
+
historical changes. **After a mid-run patch change, a backward seek recomputes the
|
|
1066
|
+
past interval with the patch standing now**, under the standing environment or
|
|
1067
|
+
the environment schedule supplied to `seek`. New single tracks and
|
|
1068
|
+
new composed tracks first evaluate their ordinary authored first pose, then
|
|
1069
|
+
receive the standing patch as pending, with no extra adjustment callback. At
|
|
1070
|
+
seek time 0, effective can therefore still be the initial authored value while
|
|
1071
|
+
override already reports the patch. The next normal core evaluation uses it.
|
|
1072
|
+
Changing entries on existing composed tracks follows that core instance's
|
|
1073
|
+
lifetime. Existing seek/skin restrictions after composition remain unchanged.
|
|
1074
|
+
|
|
1075
|
+
Set/clear invalidate seek caches without re-posing. Seek snapshots retain the
|
|
1076
|
+
public effective read alongside their held pose, so backward and exact cache
|
|
1077
|
+
hits report that pose's evaluation rather than the frontier's latest evaluation.
|
|
1078
|
+
Readback itself never advances, evaluates or resets physics.
|
|
1079
|
+
|
|
1080
|
+
### One load, several players
|
|
1081
|
+
|
|
1082
|
+
One `loadModel` backs any number of players: the regions are cut once, and
|
|
1083
|
+
every player draws from the one `regionImages` map. A player owns none of it —
|
|
1084
|
+
disposing a player leaves the bitmaps alive for the others — so there is exactly
|
|
1085
|
+
one `assets.dispose()`, after the last player is gone:
|
|
1086
|
+
|
|
1087
|
+
```ts
|
|
1088
|
+
const assets = await loadModel({ modelUrl: '/rigs/walk/skeleton.model.json' });
|
|
1089
|
+
const a = new RigPlayer(rootA, assets);
|
|
1090
|
+
const b = new RigPlayer(rootB, assets, { skin: 'winter' });
|
|
1091
|
+
|
|
1092
|
+
a.dispose();
|
|
1093
|
+
b.dispose();
|
|
1094
|
+
assets.dispose();
|
|
1095
|
+
```
|
|
1096
|
+
|
|
1097
|
+
A document is one rig. Two rigs whose builds share page images load as two
|
|
1098
|
+
documents; the images are fetched by URL, so a page both name at the same URL
|
|
1099
|
+
is loaded once by the browser — but each load cuts its own regions and owns its
|
|
1100
|
+
own blob URLs.
|
|
1101
|
+
|
|
1102
|
+
### Loading it yourself
|
|
1103
|
+
|
|
1104
|
+
`loadModel` is a convenience over two calls the package exports: read the
|
|
1105
|
+
document, load its pages, and cut the regions with `unpackRegions`, which takes
|
|
1106
|
+
the document's `pages` section — `{ name, width, height, pma, regions: [{ name,
|
|
1107
|
+
x, y, width, height, degrees }] }` per page — and a map of page images keyed by
|
|
1108
|
+
those names. Use it when the page images do not come from a URL (`resolvePage`
|
|
1109
|
+
on `loadModel` covers the ones that come from another URL), and pair it with
|
|
1110
|
+
`revokeRegions` on unload.
|
|
1111
|
+
|
|
1112
|
+
A region the packer stored turned (`degrees: 90`) is cut upright again, and
|
|
1113
|
+
which way round that is comes from the UVs a runtime assigns such a region,
|
|
1114
|
+
not from the cut: its corners carry `(u2, v2), (u, v2), (u, v), (u2, v)` in the
|
|
1115
|
+
order BL, UL, UR, BR, so the artwork's top-left corner sits at the packed rect's
|
|
1116
|
+
bottom-left and unpacking it is a clockwise turn. Every release up to 0.7.0
|
|
1117
|
+
turned it the other way and drew rotated rigid parts 180° round (#49).
|
|
1118
|
+
|
|
1119
|
+
`unpackRegions` mints one blob URL per region; `revokeRegions` is its
|
|
1120
|
+
counterpart. It only frees URLs `unpackRegions` created, so a map you built
|
|
1121
|
+
yourself and page images reused by the whole-page pass-through survive it — and
|
|
1122
|
+
calling it twice is a no-op. Load once for the page's lifetime and you can
|
|
1123
|
+
ignore it; load and unload repeatedly without it and you leak an atlas per
|
|
1124
|
+
cycle.
|
|
1125
|
+
|
|
1126
|
+
### Loading for the canvas mode only, and `data:` regions
|
|
1127
|
+
|
|
1128
|
+
The region cut makes the rigid tier's bitmaps, which only the DOM mode draws.
|
|
1129
|
+
`loadModel({ regions })` says what to do about it:
|
|
1130
|
+
|
|
1131
|
+
- `'atlas'` — opt-in page-backed rigid canvases; see below for the filtering caveat.
|
|
1132
|
+
- `'blob'` (default) — `blob:` URLs the load owns; `assets.dispose()` frees them.
|
|
1133
|
+
- `'data'` — `data:` URLs instead, for a content policy or a snapshot that does
|
|
1134
|
+
not carry `blob:`. The same PNG bytes, inline; nothing is minted, so there is
|
|
1135
|
+
nothing to free, and the base64 lives as long as the map does.
|
|
1136
|
+
- `'none'` — no cut: the pages load, `assets.regionImages` is empty, and the
|
|
1137
|
+
load is for the canvas mode. A DOM-mode player opened on it — `new RigPlayer`
|
|
1138
|
+
without `mode: 'canvas'`, or `player.mode = 'dom'` — is refused by name, and
|
|
1139
|
+
a refused mode change leaves the player as it was.
|
|
1140
|
+
|
|
1141
|
+
`assets.regions` records the choice. `unpackRegions` takes the same thing as
|
|
1142
|
+
`{ encoding: 'blob' | 'data' }`.
|
|
1143
|
+
|
|
1144
|
+
### Opt-in page-backed rigid regions
|
|
1145
|
+
|
|
1146
|
+
`loadModel({ modelUrl, regions: 'atlas' })` skips per-region PNG encoding.
|
|
1147
|
+
`ModelAssets.regions` records `'atlas'`, `ModelAssets.regionImages` is empty,
|
|
1148
|
+
and `ModelAssets.atlasRegions` holds the page-backed rigid descriptors. The
|
|
1149
|
+
load supports both render modes. The default remains `'blob'`: callers reading
|
|
1150
|
+
the complete ready-URL map keep the same contract, and explicit `'data'` and
|
|
1151
|
+
canvas-only `'none'` loads retain their meanings. No URLs are minted later in
|
|
1152
|
+
idle callbacks.
|
|
1153
|
+
|
|
1154
|
+
Rigid regions in this opt-in are canvases drawn from their atlas pages, using
|
|
1155
|
+
the same native source rectangles, clockwise rotation restoration and shared
|
|
1156
|
+
straight-alpha page derivation as the URL cut. Native pixels are held to exact
|
|
1157
|
+
equality with the decoded URL regions. On Linux WebKit the test compares
|
|
1158
|
+
encoded cuts through the same PNG readback path (unencoded whole-page
|
|
1159
|
+
pass-throughs keep their direct read): its direct canvas reads and
|
|
1160
|
+
PNG readback round the premultiplied store differently for translucent RGB.
|
|
1161
|
+
The original direct deltas remain reported; Chromium and macOS WebKit retain
|
|
1162
|
+
the direct strict comparison. This test-only encode is outside the load clock
|
|
1163
|
+
and is not used by the atlas rendering path. Composited output differs: browsers
|
|
1164
|
+
filter a transformed canvas differently from an image. The hard checker in
|
|
1165
|
+
`named/tilt` exceeds the existing test-rig DOM/canvas parity bound at scale 0.4
|
|
1166
|
+
(3.25% on Chromium and 3.26% on WebKit in the measured high-quality minification
|
|
1167
|
+
comparison). The opt-in therefore does **not** promise that parity bound for
|
|
1168
|
+
all artwork; use `'blob'` or `'data'` when its image filtering is required.
|
|
1169
|
+
Meshes keep their existing raster path.
|
|
1170
|
+
|
|
1171
|
+
For effective pixel ratios below 1, the renderer draws rigid canvases using
|
|
1172
|
+
`imageSmoothingQuality: 'high'` and rounds the ratio upward into ×1.25 bands.
|
|
1173
|
+
The ratio is the caller's `renderer.pixelRatio` times the largest posed affine
|
|
1174
|
+
axis stretch. A band provides at most 25% excess resolution per axis and never
|
|
1175
|
+
rounds below the requested ratio. Native resolution caps the backing size;
|
|
1176
|
+
ratios at least 1 retain native backing. Region changes and band crossings
|
|
1177
|
+
repaint; repeated frames within one band do not. This adds no layout reads:
|
|
1178
|
+
when a root's scale changes, set `pixelRatio` or call `syncPixelRatio()` as for
|
|
1179
|
+
meshes. `rigidRasterCount` reports rigid rasterizations in the last frame,
|
|
1180
|
+
separately from all mesh counters. First-frame preparation is inside the load
|
|
1181
|
+
measurement; no steady-state performance claim is made.
|
|
1182
|
+
|
|
1183
|
+
Low-level callers can use `createAtlasRegions(layout, pageImages)` and pass its
|
|
1184
|
+
map as the fourth argument to `new DomRenderer(root, regionImages, pageImages,
|
|
1185
|
+
atlasRegions)`. An atlas entry takes precedence over a URL entry of the same
|
|
1186
|
+
name. `AtlasRegion` contains `page`, `region` and `image`; its map and page
|
|
1187
|
+
images belong to the caller and can be shared across renderers. Disposing a
|
|
1188
|
+
renderer leaves them alive. The renderer owns its slot canvases, which it
|
|
1189
|
+
removes on disposal. `unpackRegions` and `revokeRegions` remain available for
|
|
1190
|
+
callers needing ready URLs.
|
|
1191
|
+
|
|
1192
|
+
### Pages that ship at another resolution
|
|
1193
|
+
|
|
1194
|
+
A page image may ship at a resolution its document does not declare — a
|
|
1195
|
+
half-resolution texture build, or an @2x variant, with the page's `width` and
|
|
1196
|
+
`height` left as the build wrote them. Nothing here needs a flag for that. A
|
|
1197
|
+
region's bounds are read **relative to the declared page size** and scaled onto
|
|
1198
|
+
the image's natural size, which is how the page UVs the mesh tier samples with
|
|
1199
|
+
are derived too (`u = x / page.width`), so both tiers land on the same pixels at
|
|
1200
|
+
any resolution.
|
|
1201
|
+
|
|
1202
|
+
Each unpacked bitmap comes out at the **native resolution of the pixels it was
|
|
1203
|
+
cut from** — half-resolution pages cost a quarter of the cut pixels, and
|
|
1204
|
+
nothing is upscaled back — while `RegionImage.width`/`height` stay in **atlas
|
|
1205
|
+
units**. Those two numbers are the `<img>` layout box and the denominator of
|
|
1206
|
+
its CSS matrix, so the rig poses identically and the browser scales the
|
|
1207
|
+
smaller bitmap into the same box, the way a GPU samples a smaller texture
|
|
1208
|
+
through the same UVs. Ship one build and swap the images per device if you
|
|
1209
|
+
like (`resolvePage`).
|
|
1210
|
+
|
|
1211
|
+
### Premultiplied pages (`pma`)
|
|
1212
|
+
|
|
1213
|
+
A page's `pma` flag in the document's `pages` section — the build copies it from
|
|
1214
|
+
the atlas's `pma: true` line — says its RGB is already multiplied by its alpha,
|
|
1215
|
+
and nothing is asked of you: each tier is handed the page in the convention it
|
|
1216
|
+
actually consumes. The `webgl` mesh backend uploads the texels unconverted (its
|
|
1217
|
+
blend already expects premultiplied source — lossless). The DOM and canvas2d
|
|
1218
|
+
tiers cannot: an `<img>` and `drawImage` composite straight alpha by definition,
|
|
1219
|
+
so they read a straight-alpha derivation of the page —
|
|
1220
|
+
`rgb = round(rgb * 255 / a)`, computed once and shared by the region cuts and
|
|
1221
|
+
the mesh raster. Without it every semi-transparent texel is multiplied by its
|
|
1222
|
+
alpha a second time and draws darker than it was authored: soft edges, soft
|
|
1223
|
+
shadows, glows.
|
|
1224
|
+
|
|
1225
|
+
What it costs: **one page-sized canvas per premultiplied page image**
|
|
1226
|
+
(width × height × 4 bytes — 1 MiB for a 1024×256 page, 16 MiB for a 2048×2048
|
|
1227
|
+
one), alive as long as the page image is and released with it; the cache is
|
|
1228
|
+
weak, so there is nothing to free by hand. A page without the flag derives
|
|
1229
|
+
nothing. The division is 8-bit and starts from a canvas read, which has itself
|
|
1230
|
+
quantized a premultiplied texel, so a very transparent texel can land a few
|
|
1231
|
+
levels off — exact at alpha 0 and 255, within one level of 255 above alpha 128,
|
|
1232
|
+
and a little more below that, by an amount that belongs to the browser's canvas
|
|
1233
|
+
rather than to this package. It is invisible wherever the texel is: a texel at
|
|
1234
|
+
alpha 11 is ~4% opaque. The `webgl` backend, having no such step, is exact.
|
|
1235
|
+
|
|
1236
|
+
One consequence worth knowing if your build is one part per page: a whole-page
|
|
1237
|
+
region on a premultiplied page is **cut** rather than handed through, because
|
|
1238
|
+
the page's own URL holds premultiplied pixels (see below).
|
|
1239
|
+
|
|
1240
|
+
### What unloading frees
|
|
1241
|
+
|
|
1242
|
+
`revokeRegions()` — and `assets.dispose()`, which calls it — frees the blob URLs
|
|
1243
|
+
`unpackRegions` minted, and nothing else (a `regions: 'data'` or `'none'` load
|
|
1244
|
+
minted none, so it frees nothing). The page images are held by
|
|
1245
|
+
`assets.pageImages` and by every player drawing from them, so a page is
|
|
1246
|
+
released once you drop the assets and every player is disposed. With the
|
|
1247
|
+
`webgl` mesh backend the shared blitter also uploads each page image on first
|
|
1248
|
+
use, but that GL texture is not the module's forever: every renderer drawing
|
|
1249
|
+
the page holds a reference to it, `player.dispose()` hands those back, and the
|
|
1250
|
+
texture is deleted once the last renderer using that page is disposed — a later
|
|
1251
|
+
frame that needs the page uploads it again. The cache is keyed weakly by the
|
|
1252
|
+
page image, so a renderer dropped without `dispose()` costs GPU memory until
|
|
1253
|
+
the context is lost, but never keeps the image itself alive.
|
|
1254
|
+
|
|
1255
|
+
A rig with meshes samples its page bitmaps every frame, so their decoded form
|
|
1256
|
+
stays in use: a floor on the order of `page width × page height × 4` bytes per
|
|
1257
|
+
page. A rigid-only rig draws nothing from the pages after `unpackRegions`, and
|
|
1258
|
+
what a merely reachable, undrawn image costs is up to the browser, not
|
|
1259
|
+
measurable from script.
|
|
1260
|
+
|
|
1261
|
+
Unload in this order:
|
|
1262
|
+
|
|
1263
|
+
1. `player.dispose()`, for every player using the assets.
|
|
1264
|
+
2. `assets.dispose()` (or `revokeRegions(regionImages)`).
|
|
1265
|
+
3. Drop your references to the assets.
|
|
1266
|
+
|
|
1267
|
+
### One part per page
|
|
1268
|
+
|
|
1269
|
+
`rigc build` writes one page per part by default — each part PNG is its own
|
|
1270
|
+
page, its one region covering it — and `rigc build --pack` arranges the parts
|
|
1271
|
+
onto shared pages instead. Both play here, unchanged:
|
|
1272
|
+
|
|
1273
|
+
- Regions that cover their whole page are handed straight through by
|
|
1274
|
+
`unpackRegions` instead of being cut and re-encoded — at any image resolution,
|
|
1275
|
+
since covering the page is a statement about the declared size. Load cost for
|
|
1276
|
+
this shape is just the image loads. The exception is a page marked `pma`: its
|
|
1277
|
+
URL holds premultiplied pixels, which an `<img>` would composite as straight
|
|
1278
|
+
alpha, so those regions are cut from the straight-alpha derivation like any
|
|
1279
|
+
other (and the blob is revoked by `revokeRegions` like any other).
|
|
1280
|
+
- A packed build cuts every region from its page once, at load, and its meshes
|
|
1281
|
+
sample the shared page through page UVs.
|
|
1282
|
+
|
|
1283
|
+
### Runtime knobs and what they cost
|
|
1284
|
+
|
|
1285
|
+
- `player.mode` / `new RigPlayer(root, assets, { mode })` — `'dom'` (default)
|
|
1286
|
+
or `'canvas'`. Changing it disposes the current renderer (elements removed,
|
|
1287
|
+
GPU pages handed back) and creates the other over the same root and assets;
|
|
1288
|
+
`pixelRatio` and `clipping` carry over and the held pose is redrawn at once.
|
|
1289
|
+
`player.renderer` is then a `CanvasRenderer`, whose knobs are `pixelRatio`,
|
|
1290
|
+
`syncPixelRatio()`, `clipping`, `viewport` and `backend`. What each mode costs, as counters:
|
|
1291
|
+
- **dom** — one element per drawn slot, one style write per changed slot,
|
|
1292
|
+
and the mesh tier's rasters (the knobs below).
|
|
1293
|
+
- **canvas** — one canvas element per player and, per frame that changed,
|
|
1294
|
+
one pass over every slot: `drawCalls` (one per run of one page under one
|
|
1295
|
+
blend), `blendFlushes` (runs a blend change ended), `trianglesDrawn`,
|
|
1296
|
+
`blits` (one), or `framesReused` (one) when the record did not change and
|
|
1297
|
+
nothing is drawn. It never creates a WebGL context of its own, so any number
|
|
1298
|
+
of players stays under the browser's ~16-context cap (20 players, one
|
|
1299
|
+
context — `tests/canvas-mode.spec.ts`). The canvas covers a rect of the
|
|
1300
|
+
root's coordinates that grows (never shrinks) to what the frames draw —
|
|
1301
|
+
`canvasReallocCount` settles at zero — or a fixed `renderer.viewport` (world
|
|
1302
|
+
units, Y up) when you set one. Blends are composed inside that canvas, which
|
|
1303
|
+
starts transparent: an additive slot adds onto the slots under it and is
|
|
1304
|
+
then composited onto the page normally, where the DOM tier's
|
|
1305
|
+
`plus-lighter` adds onto the page itself. Where WebGL is unavailable or the
|
|
1306
|
+
context is lost, the frame is drawn with canvas2d on the same canvas so it
|
|
1307
|
+
never draws nothing — **alpha tint only, RGB and dark tint unsupported
|
|
1308
|
+
there** — and that fallback is **not the measured path** (`backendActive`
|
|
1309
|
+
says which ran).
|
|
1310
|
+
|
|
1311
|
+
- `renderer.pixelRatio` — mesh-canvas backing pixels per CSS pixel (defaults to
|
|
1312
|
+
`devicePixelRatio`; if you scale the root element, fold that scale in so the
|
|
1313
|
+
raster matches the screen: `devicePixelRatio * rootScale`). **Writing it
|
|
1314
|
+
reallocates every mesh canvas backing store on the next frame**, and each
|
|
1315
|
+
reallocation recreates a GPU surface — the cost that took real Safari to ~3 fps
|
|
1316
|
+
when it happened per frame. Each canvas is then sized from what the new ratio
|
|
1317
|
+
needs, in both directions: lowering the ratio gives the backing pixels back
|
|
1318
|
+
(the backing is grow-only *within* a ratio, not across a change of one). Set
|
|
1319
|
+
it when a layout settles, never per frame:
|
|
1320
|
+
debounce resize drags and quantize the value instead of tracking it
|
|
1321
|
+
continuously. `renderer.canvasReallocCount` is the check — it must fall back to
|
|
1322
|
+
zero within a second or two.
|
|
1323
|
+
- `renderer.syncPixelRatio()` — measures the root's effective on-screen scale
|
|
1324
|
+
and sets `pixelRatio` to `devicePixelRatio × scale`, returning the ratio now
|
|
1325
|
+
in effect. It appends a hidden 100 px box to the root, reads its box once and
|
|
1326
|
+
removes it (the root itself is usually 0×0), so it is **one forced layout per
|
|
1327
|
+
call** — which is exactly why the renderer never calls it for you: there is no
|
|
1328
|
+
per-frame layout read anywhere in this library. Call it when a zoom or a
|
|
1329
|
+
layout *settles* (gesture end, debounced resize), not during the drag. A
|
|
1330
|
+
change under 0.1% is ignored, so layout jitter cannot churn GPU surfaces, and
|
|
1331
|
+
a root that is not laid out (a `display: none` ancestor) leaves the ratio
|
|
1332
|
+
alone. Under an ancestor rotation the measured box is inflated and the ratio
|
|
1333
|
+
errs high — oversampling costs pixels, undersampling costs picture.
|
|
1334
|
+
- `renderer.meshBackingPixels` — allocated mesh-canvas backing pixels
|
|
1335
|
+
(Σ width × height), computed on demand. This is what `pixelRatio` moves
|
|
1336
|
+
quadratically, and the cheapest way to see an oversampling stage; the demo
|
|
1337
|
+
prints it in the stats line as `backing N Mpx`.
|
|
1338
|
+
- `renderer.meshBackend` — `'webgl'` (default since 1.9) or `'canvas2d'`; same
|
|
1339
|
+
output, and on macOS Safari webgl holds 58–60 fps where canvas2d reads 2–26
|
|
1340
|
+
(see Measured above). Falls back to canvas2d automatically when WebGL is
|
|
1341
|
+
unavailable or the shared context is lost; `meshBackendActive` says which drew. Switching re-rasters every
|
|
1342
|
+
mesh once (no reallocation), so it is fine to expose as a user setting.
|
|
1343
|
+
|
|
1344
|
+
On WebGL context loss (`webglcontextlost`), a player instance falls back to
|
|
1345
|
+
`canvas2d` for the rest of its life and never attempts a restore (#193): the
|
|
1346
|
+
shared context does not request restoration and ignores
|
|
1347
|
+
`webglcontextrestored`, so the very next frame draws on `canvas2d`
|
|
1348
|
+
(`meshBackendActive` in `dom` mode, `backendActive` in `canvas` mode) and
|
|
1349
|
+
stays there.
|
|
1350
|
+
- `renderer.meshBackendFallbackReason` (DOM) and `renderer.backendFallbackReason`
|
|
1351
|
+
(canvas) describe the last render's backend selection, including renders that
|
|
1352
|
+
reuse a raster. Both are `WebGLFallbackReason | null`. The value is `null`
|
|
1353
|
+
before the first render and whenever WebGL is selected successfully.
|
|
1354
|
+
|
|
1355
|
+
- `'not-requested'` means the caller chose `canvas2d`.
|
|
1356
|
+
- `'creation-failed'` means shared WebGL initialization failed. That failure
|
|
1357
|
+
is cached for this instance of the loaded module.
|
|
1358
|
+
- `'context-lost'` means the shared WebGL context was lost.
|
|
1359
|
+
- `'over-grant'` means WebGL could not draw this render within the usable
|
|
1360
|
+
drawing buffer. Successful tiling stays on WebGL.
|
|
1361
|
+
- `renderer.triangleExpand` — how far (canvas px) each triangle edge's clip is
|
|
1362
|
+
moved outward to close antialiased mesh seams (default 0.5). Also re-rasters every mesh once when changed.
|
|
1363
|
+
- `renderer.meshSourceRect` — what a canvas2d mesh triangle is drawn from:
|
|
1364
|
+
`'page'` (the whole page) or `'triangle'` (a sub-rect covering its clip). Both
|
|
1365
|
+
draw the same picture; the default is `'triangle'` on Linux WebKit, which
|
|
1366
|
+
garbles whole-page draws, and `'page'` elsewhere, because macOS Safari ran the
|
|
1367
|
+
sub-rect 12–15% slower (#25). Also on `CanvasRenderer` for its canvas2d
|
|
1368
|
+
fallback. Re-rasters every mesh once when changed.
|
|
1369
|
+
- `renderer.clipping` — apply the clips the frame carries (default `true`).
|
|
1370
|
+
Which slots a clip covers is decided where the frame is made — the player's
|
|
1371
|
+
adapter walks the draw order the way the runtime's draw loop does (one clip in
|
|
1372
|
+
force at a time, a second one met while one is in force ignored, the end slot
|
|
1373
|
+
inside its own clip). What the renderer writes is one CSS `clip-path` per
|
|
1374
|
+
element a clip covers, in that
|
|
1375
|
+
element's own local frame; nothing reaches the raster backends, and a clip is
|
|
1376
|
+
not part of the mesh dirty signature, so a mesh that held still keeps reusing
|
|
1377
|
+
its raster under a moving clip. **Writes happen on change only**: each
|
|
1378
|
+
clip-path is cached exactly as `transform` is, coordinates are quantized to
|
|
1379
|
+
1/1000 of a local unit so float jitter cannot defeat that cache, and a static
|
|
1380
|
+
polygon over a static pose therefore costs **zero style writes per frame after
|
|
1381
|
+
the first** — `renderer.clipWriteCount` is the check, alongside
|
|
1382
|
+
`clipCount` (clips applied) and `clipSkipCount` (clips in the frame not
|
|
1383
|
+
applied: switched off, or a degenerate polygon; a clip the runtime itself
|
|
1384
|
+
ignores never reaches the frame). **The whole-skeleton fast path**: when one
|
|
1385
|
+
clip covers every slot of the frame, one `clip-path` goes on the root instead
|
|
1386
|
+
of one per element. The root is *your* element, so its inline `clip-path` is **borrowed,
|
|
1387
|
+
not taken** — saved on the first write and put back verbatim when the clip
|
|
1388
|
+
stops covering the frame, when `clipping` goes `false`, and by `dispose()`.
|
|
1389
|
+
Per-element clip-paths and the root clip-path are never both in force for the
|
|
1390
|
+
same clip. Two things to know about that path: the polygon is written in the
|
|
1391
|
+
root's **border box** frame, which is where absolutely-positioned slot elements
|
|
1392
|
+
start too *unless the root has a CSS border* (a border would offset the
|
|
1393
|
+
whole-skeleton clip by its width — keep borders off the render root, which is
|
|
1394
|
+
the normal shape for a 0×0 origin element); and an inverse clip never takes it,
|
|
1395
|
+
because its CSS form needs an outer ring around a box and the root has none.
|
|
1396
|
+
One further consequence of that path: a `clip-path` other than `none` makes an
|
|
1397
|
+
element a stacking context (CSS Masking), so a whole-skeleton clip isolates
|
|
1398
|
+
`mix-blend-mode` slots from backdrops *outside* the root — which a root
|
|
1399
|
+
carrying a `transform` (the usual pan/zoom stage) already does. Per-element
|
|
1400
|
+
clips do not change blending, since a blended slot is its own stacking context
|
|
1401
|
+
either way. Setting `clipping = false` removes every clip-path this renderer
|
|
1402
|
+
wrote.
|
|
1403
|
+
|
|
1404
|
+
**A zoomable stage.** The mesh tier rasters at `world × pixelRatio` in the
|
|
1405
|
+
root's own coordinates, and it cannot see a CSS transform above the root — so
|
|
1406
|
+
the most natural pan/zoom stage, `transform: scale(zoom)` on an ancestor, makes
|
|
1407
|
+
it oversample by `1/zoom²` in backing pixels until the zoom is folded in. The
|
|
1408
|
+
picture stays correct throughout, which is what makes this easy to ship: only
|
|
1409
|
+
the allocation and the frame rate move. Call `syncPixelRatio()` when the zoom
|
|
1410
|
+
settles, or set `pixelRatio = devicePixelRatio * zoom` yourself. Measured
|
|
1411
|
+
on-device (Chromium, dpr 2, stage under `scale(0.25)`, ~2.2 M CSS px on screen):
|
|
1412
|
+
|
|
1413
|
+
| scene | `pixelRatio` | `meshBackingPixels` | fps |
|
|
1414
|
+
| --- | --- | --- | --- |
|
|
1415
|
+
| 57 meshes | `devicePixelRatio` (2) | 139.1 Mpx | 14–21 |
|
|
1416
|
+
| 57 meshes | `dpr × zoom` (0.5) | 9.1 Mpx | 61 |
|
|
1417
|
+
| 92 meshes | `devicePixelRatio` (2) | 141.1 Mpx | 36–39 |
|
|
1418
|
+
| 92 meshes | `dpr × zoom` (0.5) | 9.1 Mpx | 60–61 |
|
|
1419
|
+
|