@rig-c/play 0.0.0-stage → 1.8.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 CHANGED
@@ -1,3 +1,963 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <img src="assets/banner.svg" alt="rig-play - plays rigc's compiled model as DOM elements or one canvas" width="100%" />
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ <p align="center">
6
+ <a href="https://www.npmjs.com/package/rig-play"><img src="https://img.shields.io/npm/v/rig-play.svg?style=flat-square&color=FF6B4A" alt="npm version" /></a>
7
+ <a href="https://www.npmjs.com/package/rig-play"><img src="https://img.shields.io/npm/dm/rig-play.svg?style=flat-square&color=EC4899" alt="npm downloads" /></a>
8
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-38BDF8.svg?style=flat-square" alt="license" /></a>
9
+ </p>
10
+
11
+ Plays the rigs [rigc](https://github.com/firejune/rigc) builds — the compiled model
12
+ document `rigc build` writes, `skeleton.model.json` — as **plain DOM**: one
13
+ absolutely-positioned `<img>` per rigid slot, posed with a single CSS `matrix()` write
14
+ per frame, deforming meshes on small per-part canvases; or as **one canvas** per player.
15
+ `spine-html` is the same package under the name it first shipped as.
16
+
17
+ ## Why
18
+
19
+ The package began in 0.x as `spine-html`, an experiment in drawing Spine skeletons
20
+ without a canvas. Every Spine web runtime rasterizes into one, yet the pose itself is
21
+ computed on the CPU, and for a **region attachment** (a rigid part) the bone transform is
22
+ a plain affine map that CSS `transform: matrix()` expresses *exactly* — so the rigid tier
23
+ could live in the DOM, composited by the browser, inspectable in devtools, styled with
24
+ CSS. The idea had been floated on the Spine forum three times since 2014 and never built;
25
+ the blockers named were meshes, clipping and DOM update overhead, and the 0.x line
26
+ answered each of them (per-part mesh canvases, element-level `clip-path`, dirty-skip).
27
+
28
+ At 1.0 it stopped being a Spine runtime. It plays the model document `rigc build` writes,
29
+ poses it through `rig-c/core` — rigc's own posing core, bundled into the package — and
30
+ links nothing from Esoteric Software; a Spine export is refused by name. It gained a
31
+ second render mode that draws the whole frame into one canvas. And it took the name
32
+ `rig-play`, which says what it is; `spine-html` keeps being published with the same
33
+ files, so links to the old name keep working.
34
+
35
+ ### Measured
36
+
37
+ Measured on the 0.x line, on the spineboy exports it then played (PoC, Apple silicon —
38
+ headless and on-device numbers are labeled, they do **not** substitute for each other).
39
+ The renderer tiers they describe carried over; they have not been re-measured since the
40
+ player moved to rigc's model (#60):
41
+
42
+ - Rigid only (spineboy-ess), headless Chromium: 10 skeletons / 180 slot images at
43
+ **~0.03 ms skeleton math + ~0.22 ms DOM writes per frame** — about 1.5% of a
44
+ 60 fps frame budget. On-device Safari: 10 rigid skeletons hold **60 fps**.
45
+ - With meshes (spineboy-pro), headless Chromium: 1 skeleton = **~0.05 ms + ~0.5 ms
46
+ render** (8 mesh canvases, 323 triangles); 10 running skeletons = **~3.5 ms/frame**
47
+ total, smooth.
48
+ - Dirty-skip: 10 *static* skeletons (pose held) = **~0.4 ms/frame** headless and
49
+ **~0.6 ms** on-device Safari — unchanged meshes reuse their raster, so idle or
50
+ held parts cost nothing anywhere.
51
+ - Real Safari (on-device), canvas2d mesh backend: in-callback JS stays **~4–5
52
+ ms/frame** for 10 running meshed skeletons — but the rAF rate tells the real
53
+ story: **meshed ×1 = 37 fps, meshed ×10 = 3–4 fps** (rigid-only ×10 = 60 fps).
54
+ The cost lives outside the frame callback, in the compositor/GPU process:
55
+ Safari antialiases canvas2d **clip paths**, so every triangle pays for an AA
56
+ mask. Chromium doesn't antialias clips and stays smooth. This is what the
57
+ optional WebGL mesh backend (below) removes.
58
+ - Real Safari (on-device), **webgl mesh backend**: meshed ×1 holds **60 fps**
59
+ (vs 37 on canvas2d), and the meshed ×10 stress scene jumps **3–4 → 45 fps** —
60
+ 80 mesh canvases / 3230 triangles redrawn every frame (0 reused, the worst
61
+ case), in-callback JS ~5.8 ms at dpr=1. The per-triangle clip-AA tax is gone;
62
+ the remaining gap to 60 is the blit/compositing cost of a 10-skeleton stress
63
+ scene, not a per-triangle cost.
64
+ - Headless-WebKit numbers are a **software rasterizer** and measured up to 28×
65
+ off real Safari in both directions — useful for visual regression only, never
66
+ as Safari perf evidence.
67
+
68
+ ## Status
69
+
70
+ **Production.** The questions this started as a PoC to answer — how far does the
71
+ DOM actually go, and how cheap is it — are answered with on-device numbers: the
72
+ practical scenario (a character or two, mostly holding pose, a few parts
73
+ deforming) holds **60 fps on every engine measured**, and the 10-skeleton
74
+ stress scene holds 45 fps on the weakest one (Safari, webgl backend). Ships
75
+ with a self-contained test suite (backend visual parity + invariants) and CI.
76
+
77
+ **Two render modes.** `mode: 'dom'` (the default, everything below) draws a rig
78
+ as elements. `mode: 'canvas'` draws the whole frame into **one `<canvas>`** per
79
+ player: every slot as textured triangles from its atlas page through the same
80
+ shared WebGL context the mesh tier's `webgl` backend uses, into one rect, then
81
+ one `drawImage` onto the player's canvas. Tint and dark (two-colour) tint are
82
+ vertex colours, blend modes are batch state, clips are cut on the CPU by
83
+ `rig-c/core`'s clipper — no `clip-path`, no SVG filter, no per-slot element.
84
+ `RigPlayer` swaps between the two in place (`player.mode = 'canvas'`). The
85
+ canvas mode is held against the DOM tier pixel for pixel on the parity suite's
86
+ frozen poses (bad pixels ≤ 1.6% of drawn content, measured, macOS Chromium and
87
+ WebKit); which mode is faster where is **not measured on a device yet**, so the
88
+ default stays `dom`.
89
+
90
+ - ✅ Region attachments (rigid parts): exact affine mapping, draw-order via `z-index`,
91
+ attachment swaps, alpha
92
+ - ✅ Atlas unpacking at load time (90°-packed regions restored to the orientation
93
+ the region's UVs name, held against hand-written UVs on a rigc build whose region
94
+ is packed turned),
95
+ so the rigid per-frame path never touches a canvas — a region that covers its whole
96
+ page is passed through uncut, and `revokeRegions()` frees the rest when a skeleton
97
+ is unloaded
98
+ - ✅ Mesh attachments (deform tier): small per-part canvases sized to the mesh's world
99
+ bounds, interleaved with the rigid `<img>` slots in one stacking context — the DOM
100
+ handles the bones, a rasterizer handles the warps
101
+ - ✅ Blend modes via `mix-blend-mode` (additive = `plus-lighter`)
102
+ - ✅ Crack-free mesh seams on clip-antialiasing browsers (Safari): each triangle's
103
+ clip polygon is expanded 0.5px from its centroid so neighbours overlap — the
104
+ texture is continuous across shared edges, so the overlap is invisible
105
+ (`?expand=0` shows the cracks for comparison)
106
+ - ✅ RGB tinting (skeleton × slot × attachment color) via an SVG `feColorMatrix`
107
+ reference filter per element — an exact channel multiply that works identically on
108
+ `<img>` and `<canvas>` without touching the raster (needs reference-filter support,
109
+ Safari 15+; verified pixel-level on Chromium and WebKit). Dark/two-color tint is
110
+ not expressible this way and stays out of scope
111
+ - ✅ DPR-aware mesh canvas backing store: `renderer.pixelRatio` (defaults to
112
+ `devicePixelRatio`; if you scale the root element, fold that scale in)
113
+ - ✅ Dirty-skip: a mesh whose canvas-space vertices didn't change reuses last frame's
114
+ raster — the CSS translate still tracks it, so parts that hold a pose (or move by
115
+ whole pixels) pay zero raster. 10 frozen spineboys: WebKit ~141 → ~0.5 ms/frame
116
+ - ✅ Clipping attachments as element-level CSS `clip-path`: spine-core's semantics
117
+ (one active clip at a time, applied from the clip's slot through its end slot
118
+ inclusive), with the polygon expressed in each element's own local frame — the
119
+ inverse of the `<img>` matrix for rigid slots, the canvas translate for mesh
120
+ slots. Covers **part masks** (a clip with a real end slot, like the figure test
121
+ rig's `mask` animation) and **whole-skeleton clips** (an end slot that never
122
+ arrives, which takes a fast path: one `clip-path` on the root instead of one per
123
+ element). **Inverse clips** are supported too: the region they keep has a hole
124
+ in it, so it needs two rings, and `polygon()` carries only one — a box and a
125
+ polygon listed inside one `polygon()` become a single self-intersecting ring
126
+ whose even-odd fill leaves a wedge along the seam between them (measured, on a
127
+ corner of spineboy's boot). So an inverse clip is written as a two-subpath
128
+ `path(evenodd, …)` whose outer ring is the element's own box. The whole feature
129
+ is element-level, so both mesh backends see the same thing and neither raster
130
+ path knows clipping exists; `renderer.clipping = false`
131
+ restores the old counted-and-skipped behaviour. Concave polygons go to CSS as
132
+ authored — the convex decomposition spine's CPU clipper performs exists to feed a
133
+ triangle rasterizer and has no job here. Two things this does not do: Spine's
134
+ clipper convexifies an *inverse* polygon (convex hull) where CSS clips it as
135
+ authored, so the two agree exactly when that polygon is convex — which is the
136
+ shape `inverse` is meant for; and the cost of many simultaneous `clip-path`s on
137
+ real-device Safari is **not measured** (the headless numbers that exist are not
138
+ Safari evidence — see Measured above)
139
+ - ✅ Safari mesh cost root-caused by on-device triangulation (two corrections deep):
140
+ the early "~15× slower per-triangle path" was a **headless-WebKit artifact**
141
+ (software rasterization), and the follow-up "on par with Chromium" held only for
142
+ in-callback JS time. Real-Safari rAF rates — rigid ×10 = 60 fps, meshed ×1 =
143
+ 37 fps, meshed ×10 = 3–4 fps with JS flat at ~4–5 ms — put the real cost in the
144
+ GPU process: Safari antialiases canvas2d **clip paths**, so the per-triangle clip
145
+ mapping pays a per-triangle AA-mask tax (the same AA that caused the seam cracks)
146
+ - ✅ Optional WebGL blit backend for the mesh tier: `renderer.meshBackend =
147
+ 'webgl'` (default stays `'canvas2d'`). All dirty meshes are shelf-packed into
148
+ **one shared offscreen WebGL context** (module-level — browsers cap contexts at
149
+ ~16), drawn as textured triangles with premultiplied alpha, then rect-blitted
150
+ onto the same per-part canvases with an unclipped `drawImage` — cheap on Safari.
151
+ Everything element-level is unchanged: z-index interleave, tint filter,
152
+ `mix-blend-mode`, dirty-skip, grow-only backing. GL rasterizes shared triangle
153
+ edges seamlessly, so this path needs no crack overdraw. Falls back to canvas2d
154
+ when WebGL is unavailable or the context is lost. Backend parity verified by
155
+ headless Chromium+WebKit screenshot diffs (glow / clipping / tint scenes;
156
+ sub-pixel edge differences only). On-device Safari, meshed ×10 with every mesh
157
+ redrawn per frame: **3–4 fps (canvas2d) → 45 fps (webgl)**
158
+
159
+ ## Install
160
+
161
+ ```bash
162
+ npm i rig-play
163
+ npm i -D rig-c # the build tool: `rigc build` writes the model rig-play loads
164
+ ```
165
+
166
+ The package plays rigs built by [rigc](https://github.com/firejune/rigc):
167
+ `rigc build` writes a compiled model document, `skeleton.model.json` (spec
168
+ `rigc-compiled/3`), next to the Spine pair and the atlas pages. That document
169
+ is what the player loads, and it states everything posing and drawing need —
170
+ the skeleton, the animations, and where every region sits on its page — so the
171
+ `.atlas` and `skeleton.json` beside it are not fetched. Poses are computed by
172
+ `rig-c/core`, rigc's own posing core, which is bundled into this package: there
173
+ is nothing else to install.
174
+
175
+ ```ts
176
+ import { loadModel, RigPlayer } from 'rig-play';
177
+
178
+ const assets = await loadModel({ modelUrl: '/rigs/walk/skeleton.model.json' });
179
+
180
+ // A positioned element becomes the rig's world origin (Y-up: the rig grows
181
+ // upward from it). Layout and scaling are the caller's.
182
+ const player = new RigPlayer(rootElement, assets);
183
+ player.play('walk'); // looping; { loop: false } holds at the end
184
+
185
+ function frame(delta: number) {
186
+ player.frame(delta); // step the track by delta × timeScale, draw
187
+ }
188
+
189
+ // Unloading (a cutscene ends, a level swaps): elements first, bitmaps second.
190
+ // The unpacked regions are blob URLs — nothing else frees them.
191
+ player.dispose();
192
+ assets.dispose();
193
+ ```
194
+
195
+ The player owns one track: `play(name, { loop })` opens an animation at its first
196
+ pose, `frame(dt)` steps it (or `advance(dt)` then `draw()`, to time the two
197
+ apart), `pause()` / `resume()` hold and release it, `timeScale` scales every
198
+ step, and `seek(t)` moves it to a time. A seek is "reopen, then step to the
199
+ time" in `seekStep` increments (1/60 s by default) — never a jump, because a
200
+ physics rig has history and its pose at a time depends on the steps that
201
+ reached it. `on('event', …)` receives the event keys each step crosses, in the
202
+ runtime's order across a loop's wrap; `on('complete', …)` fires once a step
203
+ completes a cycle. `skin` (a constructor option) poses under a named skin;
204
+ without it the rig is posed the way a fresh Spine skeleton is, with no skin
205
+ set. `player.color` multiplies a whole-rig colour into every slot's tint.
206
+ `player.renderer` is the `DomRenderer` underneath, whose knobs and counters
207
+ are below.
208
+
209
+ **What it refuses, by name.** A Spine export (`.json`, `.skel`) is refused
210
+ before anything is fetched: this package reads compiled models and nothing
211
+ else. A document whose `spec` is not one `rig-c/core` reads is refused with the
212
+ core's own sentence plus "build it with `rigc build`", and so is a
213
+ `rigc-compiled/1` document, which predates the `pages` section.
214
+
215
+ `rig-play` is a third-party renderer and is not affiliated with or endorsed by
216
+ Esoteric Software.
217
+
218
+ ### Drawing your own frames
219
+
220
+ `RigPlayer` is the convenient path; the renderer underneath takes a plain
221
+ record, so anything that can produce one can draw through it:
222
+
223
+ ```ts
224
+ import { DomRenderer, type PosedFrame } from 'rig-play';
225
+
226
+ const renderer = new DomRenderer(rootElement, assets.regionImages, assets.pageImages);
227
+ renderer.render(frame); // frame: PosedFrame
228
+ ```
229
+
230
+ ```ts
231
+ PosedFrame { order: PosedSlot[] } // the slots that draw, in draw order
232
+ PosedSlot = { slot; z; blend: 'Normal'|'Additive'|'Multiply'|'Screen';
233
+ tint: [r, g, b, a]; dark?: [r, g, b];
234
+ clip?: { polygon: number[]; inverse: boolean; convex: boolean } } // world space, Y up
235
+ & ( { kind: 'region'; region: string; corners: number[] /* BL, UL, UR, BR */;
236
+ page: string; pma: boolean; uvs: number[] /* page UVs at the corners */ }
237
+ | { kind: 'mesh'; page: string; pma: boolean; vertices: number[];
238
+ uvs: number[]; triangles: number[]; sequence: number } )
239
+ ```
240
+
241
+ `player.posedFrame()` returns the record the player would draw. Two things the
242
+ renderer reads off it by identity rather than by value: every slot a clip
243
+ covers carries the **same** `clip` object (one that covers every slot of the
244
+ frame takes the one-`clip-path`-on-the-root path), and a mesh's `uvs` and
245
+ `triangles` are the same arrays from frame to frame for the same texture
246
+ mapping (a new array re-rasters the mesh).
247
+
248
+ ### Reading the pose
249
+
250
+ Two reads off the pose the player holds — the last `frame`/`advance`/`seek`,
251
+ or the setup pose before `play` — for framing a stage around a rig:
252
+
253
+ ```ts
254
+ const head = player.bone('head'); // { x, y, a, b, c, d, rotationX, rotationY, scaleX, scaleY, active }
255
+ const box = player.bounds(); // { x, y, width, height } | null — world units, Y up
256
+ ```
257
+
258
+ `bone` is the core's world transform for that bone (`rig-c/core`'s `RawBone`,
259
+ unchanged), and an unknown name is refused by name. `bounds` is the box of
260
+ every region's four corners and every mesh's vertices in the frame record the
261
+ renderer takes; a slot under a clip counts only inside the clip polygon's own
262
+ box, an inverse clip removes nothing, and bounding boxes, paths and points do
263
+ not draw and do not count. Both cost nothing until called and read the same
264
+ numbers in `dom` and `canvas` mode.
265
+
266
+ ### Drawing some slots only
267
+
268
+ `slots` is a draw filter — an allow list of slot names or a predicate — settable up
269
+ front and on a live player. The pose is the whole rig's whatever the filter:
270
+ bones, constraints, physics, `bone()`, `adjust`, events and tracks see no filter;
271
+ only the draw does, in both modes, and `bounds()` reads the drawn slots. A
272
+ clipping slot the filter leaves out does not clip. An allow list naming a slot
273
+ the document does not have is refused by name.
274
+
275
+ ```ts
276
+ const hand = new RigPlayer(frontRoot, assets, { slots: ['hand_f', 'arm_f_lo'] });
277
+ player.slots = (slot) => !slot.startsWith('weapon');
278
+ ```
279
+
280
+ Two players over one `ModelAssets` share the load but each poses the rig. To
281
+ pose it once and draw it twice — a hand drawn again in front of another
282
+ character — give a second renderer this player's pose under another filter:
283
+
284
+ ```ts
285
+ const front = new DomRenderer(frontRoot, assets.regionImages, assets.pageImages);
286
+ // each frame, after player.frame(dt):
287
+ front.render(player.posedFrame(['hand_f', 'arm_f_lo']));
288
+ ```
289
+
290
+ ### Several tracks
291
+
292
+ A base on track 0, a layer over it, a one-shot played once and mixed back out —
293
+ rig-c's live tracks (`openTracks`), whose mixing is the Spine runtime's
294
+ `AnimationState` held at tolerance 0:
295
+
296
+ ```ts
297
+ player.play('idle'); // track 0, as always
298
+ player.play('smile', { track: 1, loop: false, mix: 0.2 }); // held at its end, mixed in over 0.2 s
299
+ player.play('wave', { track: 2, loop: false, mix: 0.1 }); // a one-shot…
300
+ player.queueClear(2, { mix: 0.1 }); // …mixed back out over its last 0.1 s
301
+ player.queue('idle_b', { track: 0, mix: 0.3 }); // after the current idle cycle completes
302
+ player.clear(1, { mix: 0.2 }); // the layer gone, the base showing through
303
+ player.entry(2); // { animation, loop, trackTime, animationTime, duration, alpha, additive } | null
304
+ player.play('blink', { track: 3, alpha: 0.6 }); // the same clip at a weight…
305
+ player.setAlpha(3, 0.85); // …changed while it plays
306
+ player.play('breath', { track: 4, additive: true }); // adds to what the tracks below posed
307
+ ```
308
+
309
+ **Weight and additive layers** (rig-c 2.39.0, the runtime's `TrackEntry.alpha` and
310
+ `additive`): `alpha` (0..1, default 1) multiplies every timeline the entry applies;
311
+ `setAlpha(track, alpha)` changes the current entry's weight from the next pose and
312
+ re-poses the held pose. It does not touch events — an entry fires at any alpha, 0
313
+ included, and one mixing out fires none — or attachments: the current entry keeps
314
+ its attachments at any alpha, one mixing out keeps none. `additive: true`, fixed
315
+ when the entry is set or queued, adds the entry's keyed bone and deform values to
316
+ what the tracks below posed instead of replacing them, so a layer keying the same
317
+ bone channels as an idle does not cover its motion; a rotation is added as it
318
+ stands, with no shortest-angle wrap, and an additive entry mixing out fades with its
319
+ alpha and is never held. Colour, attachment and event timelines apply as on a
320
+ replacing entry. A weight below 1 or an additive entry composes, as a mix does.
321
+
322
+ `play(name)` keeps meaning what it meant: a plain play on track 0 runs on rig-c's
323
+ single live track, which poses everything the core poses. The first call that
324
+ composes — a `mix`, a `track` above 0, a `queue`, a `clear` — moves the player onto
325
+ the tracks, carrying the single track over by **replay** (its animation set, pose 0
326
+ taken, stepped to its time in `seekStep` increments — one pose per step played, so
327
+ on a stage that idled a while that is one long frame; the core offers no hand-over
328
+ of a live track's state). To never pay it, stand the player on the tracks from the
329
+ start: `new RigPlayer(root, assets, { tracks: true })`. Pick the single track for a
330
+ rig whose animations key what the tracks do not mix (below); pick the tracks for
331
+ layering. Either way, after the first `mix`, `track` above 0, `queue` or `clear`,
332
+ `seek` and `skin` are refused by name, since the player cannot replay a composition
333
+ to a time — step it forward instead.
334
+ Every entry mixes from the setup pose each step, so `adjust` writes still last one
335
+ pose. **What the tracks do not mix**, in rig-c's words at `play`/`queue`: an
336
+ animation keying a constraint (ik, transform, path, physics, slider), a sequence,
337
+ the draw order, or a path's deform is refused when it is set on the tracks — it
338
+ plays on the single track only. `'event'` carries `track`; a one-shot that is
339
+ mixing out fires nothing. `'complete'` is per track, the player's rule: a looping
340
+ entry each cycle, a held one when it reaches its duration, and an entry that is
341
+ replaced — by `play`, or by the queued entry that starts at its completion less the
342
+ mix — completes no more than it fires.
343
+
344
+ ### Adjusting bones
345
+
346
+ A per-pose write to bone locals — a breath's scale, a look's rotation, a mouth
347
+ driven while the body holds still:
348
+
349
+ ```ts
350
+ const player = new RigPlayer(root, assets, {
351
+ adjust: (bones) => { bones.bone('mouth').scaleY = 1 + openness; },
352
+ });
353
+ player.adjust = null; // or set it later; setting it re-poses the held pose at once
354
+ ```
355
+
356
+ The function runs once per pose, after the animation's timelines and before the
357
+ world transforms, constraints and physics — `rig-c/core`'s `openTrack({ adjust })`,
358
+ which rig-c holds to the Spine runtime at tolerance 0. **A write lasts one
359
+ pose.** The core poses every step from the setup pose, so a value you want held
360
+ is written again each pose and nothing compounds; a 0.8 caller that multiplied a
361
+ channel on a skeleton it kept between frames writes the value it wants, every
362
+ pose. It runs on every pose the animation is applied to, the first one after
363
+ `play` included, and `seek` and a `mode` change keep it.
364
+
365
+ A paused player and a zero step re-pose nothing, so a change the function would
366
+ make is not seen until the next step — unless you ask: setting `player.adjust`
367
+ re-poses the held pose at the same track time, and `player.repose()` does the
368
+ same for a function whose own state changed (the mouth above), without stepping,
369
+ firing events or drawing. A non-finite value, a bone the document does not have,
370
+ or an error the function throws refuses that step in the core's words, and the
371
+ track is reopened by the next `play` or `seek`.
372
+
373
+ ### One load, several players
374
+
375
+ One `loadModel` backs any number of players: the regions are cut once, and
376
+ every player draws from the one `regionImages` map. A player owns none of it —
377
+ disposing a player leaves the bitmaps alive for the others — so there is exactly
378
+ one `assets.dispose()`, after the last player is gone:
379
+
380
+ ```ts
381
+ const assets = await loadModel({ modelUrl: '/rigs/walk/skeleton.model.json' });
382
+ const a = new RigPlayer(rootA, assets);
383
+ const b = new RigPlayer(rootB, assets, { skin: 'winter' });
384
+
385
+ a.dispose();
386
+ b.dispose();
387
+ assets.dispose();
388
+ ```
389
+
390
+ A document is one rig. Two rigs whose builds share page images load as two
391
+ documents; the images are fetched by URL, so a page both name at the same URL
392
+ is loaded once by the browser — but each load cuts its own regions and owns its
393
+ own blob URLs.
394
+
395
+ ### Loading it yourself
396
+
397
+ `loadModel` is a convenience over two calls the package exports: read the
398
+ document, load its pages, and cut the regions with `unpackRegions`, which takes
399
+ the document's `pages` section — `{ name, width, height, pma, regions: [{ name,
400
+ x, y, width, height, degrees }] }` per page — and a map of page images keyed by
401
+ those names. Use it when the page images do not come from a URL (`resolvePage`
402
+ on `loadModel` covers the ones that come from another URL), and pair it with
403
+ `revokeRegions` on unload.
404
+
405
+ A region the packer stored turned (`degrees: 90`) is cut upright again, and
406
+ which way round that is comes from the UVs a runtime assigns such a region,
407
+ not from the cut: its corners carry `(u2, v2), (u, v2), (u, v), (u2, v)` in the
408
+ order BL, UL, UR, BR, so the artwork's top-left corner sits at the packed rect's
409
+ bottom-left and unpacking it is a clockwise turn. Every release up to 0.7.0
410
+ turned it the other way and drew rotated rigid parts 180° round (#49).
411
+
412
+ `unpackRegions` mints one blob URL per region; `revokeRegions` is its
413
+ counterpart. It only frees URLs `unpackRegions` created, so a map you built
414
+ yourself and page images reused by the whole-page pass-through survive it — and
415
+ calling it twice is a no-op. Load once for the page's lifetime and you can
416
+ ignore it; load and unload repeatedly without it and you leak an atlas per
417
+ cycle.
418
+
419
+ ### Loading for the canvas mode only, and `data:` regions
420
+
421
+ The region cut makes the rigid tier's bitmaps, which only the DOM mode draws.
422
+ `loadModel({ regions })` says what to do about it:
423
+
424
+ - `'blob'` (default) — `blob:` URLs the load owns; `assets.dispose()` frees them.
425
+ - `'data'` — `data:` URLs instead, for a content policy or a snapshot that does
426
+ not carry `blob:`. The same PNG bytes, inline; nothing is minted, so there is
427
+ nothing to free, and the base64 lives as long as the map does.
428
+ - `'none'` — no cut: the pages load, `assets.regionImages` is empty, and the
429
+ load is for the canvas mode. A DOM-mode player opened on it — `new RigPlayer`
430
+ without `mode: 'canvas'`, or `player.mode = 'dom'` — is refused by name, and
431
+ a refused mode change leaves the player as it was.
432
+
433
+ `assets.regions` records the choice. `unpackRegions` takes the same thing as
434
+ `{ encoding: 'blob' | 'data' }`.
435
+
436
+ ### Pages that ship at another resolution
437
+
438
+ A page image may ship at a resolution its document does not declare — a
439
+ half-resolution texture build, or an @2x variant, with the page's `width` and
440
+ `height` left as the build wrote them. Nothing here needs a flag for that. A
441
+ region's bounds are read **relative to the declared page size** and scaled onto
442
+ the image's natural size, which is how the page UVs the mesh tier samples with
443
+ are derived too (`u = x / page.width`), so both tiers land on the same pixels at
444
+ any resolution.
445
+
446
+ Each unpacked bitmap comes out at the **native resolution of the pixels it was
447
+ cut from** — half-resolution pages cost a quarter of the cut pixels, and
448
+ nothing is upscaled back — while `RegionImage.width`/`height` stay in **atlas
449
+ units**. Those two numbers are the `<img>` layout box and the denominator of
450
+ its CSS matrix, so the rig poses identically and the browser scales the
451
+ smaller bitmap into the same box, the way a GPU samples a smaller texture
452
+ through the same UVs. Ship one build and swap the images per device if you
453
+ like (`resolvePage`).
454
+
455
+ ### Premultiplied pages (`pma`)
456
+
457
+ A page's `pma` flag in the document's `pages` section — the build copies it from
458
+ the atlas's `pma: true` line — says its RGB is already multiplied by its alpha,
459
+ and nothing is asked of you: each tier is handed the page in the convention it
460
+ actually consumes. The `webgl` mesh backend uploads the texels unconverted (its
461
+ blend already expects premultiplied source — lossless). The DOM and canvas2d
462
+ tiers cannot: an `<img>` and `drawImage` composite straight alpha by definition,
463
+ so they read a straight-alpha derivation of the page —
464
+ `rgb = round(rgb * 255 / a)`, computed once and shared by the region cuts and
465
+ the mesh raster. Without it every semi-transparent texel is multiplied by its
466
+ alpha a second time and draws darker than it was authored: soft edges, soft
467
+ shadows, glows.
468
+
469
+ What it costs: **one page-sized canvas per premultiplied page image**
470
+ (width × height × 4 bytes — 1 MiB for a 1024×256 page, 16 MiB for a 2048×2048
471
+ one), alive as long as the page image is and released with it; the cache is
472
+ weak, so there is nothing to free by hand. A page without the flag derives
473
+ nothing. The division is 8-bit and starts from a canvas read, which has itself
474
+ quantized a premultiplied texel, so a very transparent texel can land a few
475
+ levels off — exact at alpha 0 and 255, within one level of 255 above alpha 128,
476
+ and a little more below that, by an amount that belongs to the browser's canvas
477
+ rather than to this package. It is invisible wherever the texel is: a texel at
478
+ alpha 11 is ~4% opaque. The `webgl` backend, having no such step, is exact.
479
+
480
+ One consequence worth knowing if your build is one part per page: a whole-page
481
+ region on a premultiplied page is **cut** rather than handed through, because
482
+ the page's own URL holds premultiplied pixels (see below).
483
+
484
+ ### What unloading frees
485
+
486
+ `revokeRegions()` — and `assets.dispose()`, which calls it — frees the blob URLs
487
+ `unpackRegions` minted, and nothing else (a `regions: 'data'` or `'none'` load
488
+ minted none, so it frees nothing). The page images are held by
489
+ `assets.pageImages` and by every player drawing from them, so a page is
490
+ released once you drop the assets and every player is disposed. With the
491
+ `webgl` mesh backend the shared blitter also uploads each page image on first
492
+ use, but that GL texture is not the module's forever: every renderer drawing
493
+ the page holds a reference to it, `player.dispose()` hands those back, and the
494
+ texture is deleted once the last renderer using that page is disposed — a later
495
+ frame that needs the page uploads it again. The cache is keyed weakly by the
496
+ page image, so a renderer dropped without `dispose()` costs GPU memory until
497
+ the context is lost, but never keeps the image itself alive.
498
+
499
+ A rig with meshes samples its page bitmaps every frame, so their decoded form
500
+ stays in use: a floor on the order of `page width × page height × 4` bytes per
501
+ page. A rigid-only rig draws nothing from the pages after `unpackRegions`, and
502
+ what a merely reachable, undrawn image costs is up to the browser, not
503
+ measurable from script.
504
+
505
+ Unload in this order:
506
+
507
+ 1. `player.dispose()`, for every player using the assets.
508
+ 2. `assets.dispose()` (or `revokeRegions(regionImages)`).
509
+ 3. Drop your references to the assets.
510
+
511
+ ### One part per page
512
+
513
+ `rigc build` writes one page per part by default — each part PNG is its own
514
+ page, its one region covering it — and `rigc build --pack` arranges the parts
515
+ onto shared pages instead. Both play here, unchanged:
516
+
517
+ - Regions that cover their whole page are handed straight through by
518
+ `unpackRegions` instead of being cut and re-encoded — at any image resolution,
519
+ since covering the page is a statement about the declared size. Load cost for
520
+ this shape is just the image loads. The exception is a page marked `pma`: its
521
+ URL holds premultiplied pixels, which an `<img>` would composite as straight
522
+ alpha, so those regions are cut from the straight-alpha derivation like any
523
+ other (and the blob is revoked by `revokeRegions` like any other).
524
+ - A packed build cuts every region from its page once, at load, and its meshes
525
+ sample the shared page through page UVs.
526
+
527
+ ### Runtime knobs and what they cost
528
+
529
+ - `player.mode` / `new RigPlayer(root, assets, { mode })` — `'dom'` (default)
530
+ or `'canvas'`. Changing it disposes the current renderer (elements removed,
531
+ GPU pages handed back) and creates the other over the same root and assets;
532
+ `pixelRatio` and `clipping` carry over and the held pose is redrawn at once.
533
+ `player.renderer` is then a `CanvasRenderer`, whose knobs are `pixelRatio`,
534
+ `syncPixelRatio()`, `clipping`, `viewport` and `backend`. What each mode costs, as counters:
535
+ - **dom** — one element per drawn slot, one style write per changed slot,
536
+ and the mesh tier's rasters (the knobs below).
537
+ - **canvas** — one canvas element per player and, per frame that changed,
538
+ one pass over every slot: `drawCalls` (one per run of one page under one
539
+ blend), `blendFlushes` (runs a blend change ended), `trianglesDrawn`,
540
+ `blits` (one), or `framesReused` (one) when the record did not change and
541
+ nothing is drawn. It never creates a WebGL context of its own, so any number
542
+ of players stays under the browser's ~16-context cap (20 players, one
543
+ context — `tests/canvas-mode.spec.ts`). The canvas covers a rect of the
544
+ root's coordinates that grows (never shrinks) to what the frames draw —
545
+ `canvasReallocCount` settles at zero — or a fixed `renderer.viewport` (world
546
+ units, Y up) when you set one. Blends are composed inside that canvas, which
547
+ starts transparent: an additive slot adds onto the slots under it and is
548
+ then composited onto the page normally, where the DOM tier's
549
+ `plus-lighter` adds onto the page itself. Where WebGL is unavailable or the
550
+ context is lost, the frame is drawn with canvas2d on the same canvas so it
551
+ never draws nothing — **alpha tint only, RGB and dark tint unsupported
552
+ there** — and that fallback is **not the measured path** (`backendActive`
553
+ says which ran).
554
+
555
+ - `renderer.pixelRatio` — mesh-canvas backing pixels per CSS pixel (defaults to
556
+ `devicePixelRatio`; if you scale the root element, fold that scale in so the
557
+ raster matches the screen: `devicePixelRatio * rootScale`). **Writing it
558
+ reallocates every mesh canvas backing store on the next frame**, and each
559
+ reallocation recreates a GPU surface — the cost that took real Safari to ~3 fps
560
+ when it happened per frame. Each canvas is then sized from what the new ratio
561
+ needs, in both directions: lowering the ratio gives the backing pixels back
562
+ (the backing is grow-only *within* a ratio, not across a change of one). Set
563
+ it when a layout settles, never per frame:
564
+ debounce resize drags and quantize the value instead of tracking it
565
+ continuously. `renderer.canvasReallocCount` is the check — it must fall back to
566
+ zero within a second or two.
567
+ - `renderer.syncPixelRatio()` — measures the root's effective on-screen scale
568
+ and sets `pixelRatio` to `devicePixelRatio × scale`, returning the ratio now
569
+ in effect. It appends a hidden 100 px box to the root, reads its box once and
570
+ removes it (the root itself is usually 0×0), so it is **one forced layout per
571
+ call** — which is exactly why the renderer never calls it for you: there is no
572
+ per-frame layout read anywhere in this library. Call it when a zoom or a
573
+ layout *settles* (gesture end, debounced resize), not during the drag. A
574
+ change under 0.1% is ignored, so layout jitter cannot churn GPU surfaces, and
575
+ a root that is not laid out (a `display: none` ancestor) leaves the ratio
576
+ alone. Under an ancestor rotation the measured box is inflated and the ratio
577
+ errs high — oversampling costs pixels, undersampling costs picture.
578
+ - `renderer.meshBackingPixels` — allocated mesh-canvas backing pixels
579
+ (Σ width × height), computed on demand. This is what `pixelRatio` moves
580
+ quadratically, and the cheapest way to see an oversampling stage; the demo
581
+ prints it in the stats line as `backing N Mpx`.
582
+ - `renderer.meshBackend` — `'canvas2d'` (default) or `'webgl'`; same output, but
583
+ heavy deforming scenes on Safari want `'webgl'` (see Measured above). Falls back
584
+ to canvas2d automatically when WebGL is unavailable. Switching re-rasters every
585
+ mesh once (no reallocation), so it is fine to expose as a user setting.
586
+ - `renderer.triangleExpand` — clip overdraw in px that closes antialiased mesh
587
+ seams (default 0.5). Also re-rasters every mesh once when changed.
588
+ - `renderer.clipping` — apply the clips the frame carries (default `true`).
589
+ Which slots a clip covers is decided where the frame is made — the player's
590
+ adapter walks the draw order the way the runtime's draw loop does (one clip in
591
+ force at a time, a second one met while one is in force ignored, the end slot
592
+ inside its own clip). What the renderer writes is one CSS `clip-path` per
593
+ element a clip covers, in that
594
+ element's own local frame; nothing reaches the raster backends, and a clip is
595
+ not part of the mesh dirty signature, so a mesh that held still keeps reusing
596
+ its raster under a moving clip. **Writes happen on change only**: each
597
+ clip-path is cached exactly as `transform` is, coordinates are quantized to
598
+ 1/1000 of a local unit so float jitter cannot defeat that cache, and a static
599
+ polygon over a static pose therefore costs **zero style writes per frame after
600
+ the first** — `renderer.clipWriteCount` is the check, alongside
601
+ `clipCount` (clips applied) and `clipSkipCount` (clips in the frame not
602
+ applied: switched off, or a degenerate polygon; a clip the runtime itself
603
+ ignores never reaches the frame). **The whole-skeleton fast path**: when one
604
+ clip covers every slot of the frame, one `clip-path` goes on the root instead
605
+ of one per element. The root is *your* element, so its inline `clip-path` is **borrowed,
606
+ not taken** — saved on the first write and put back verbatim when the clip
607
+ stops covering the frame, when `clipping` goes `false`, and by `dispose()`.
608
+ Per-element clip-paths and the root clip-path are never both in force for the
609
+ same clip. Two things to know about that path: the polygon is written in the
610
+ root's **border box** frame, which is where absolutely-positioned slot elements
611
+ start too *unless the root has a CSS border* (a border would offset the
612
+ whole-skeleton clip by its width — keep borders off the render root, which is
613
+ the normal shape for a 0×0 origin element); and an inverse clip never takes it,
614
+ because its CSS form needs an outer ring around a box and the root has none.
615
+ One further consequence of that path: a `clip-path` other than `none` makes an
616
+ element a stacking context (CSS Masking), so a whole-skeleton clip isolates
617
+ `mix-blend-mode` slots from backdrops *outside* the root — which a root
618
+ carrying a `transform` (the usual pan/zoom stage) already does. Per-element
619
+ clips do not change blending, since a blended slot is its own stacking context
620
+ either way. Setting `clipping = false` removes every clip-path this renderer
621
+ wrote.
622
+
623
+ **A zoomable stage.** The mesh tier rasters at `world × pixelRatio` in the
624
+ root's own coordinates, and it cannot see a CSS transform above the root — so
625
+ the most natural pan/zoom stage, `transform: scale(zoom)` on an ancestor, makes
626
+ it oversample by `1/zoom²` in backing pixels until the zoom is folded in. The
627
+ picture stays correct throughout, which is what makes this easy to ship: only
628
+ the allocation and the frame rate move. Call `syncPixelRatio()` when the zoom
629
+ settles, or set `pixelRatio = devicePixelRatio * zoom` yourself. Measured
630
+ on-device (Chromium, dpr 2, stage under `scale(0.25)`, ~2.2 M CSS px on screen):
631
+
632
+ | scene | `pixelRatio` | `meshBackingPixels` | fps |
633
+ | --- | --- | --- | --- |
634
+ | 57 meshes | `devicePixelRatio` (2) | 139.1 Mpx | 14–21 |
635
+ | 57 meshes | `dpr × zoom` (0.5) | 9.1 Mpx | 61 |
636
+ | 92 meshes | `devicePixelRatio` (2) | 141.1 Mpx | 36–39 |
637
+ | 92 meshes | `dpr × zoom` (0.5) | 9.1 Mpx | 60–61 |
638
+
639
+ ## Coming from spine-html 0.8
640
+
641
+ This is not a drop-in upgrade. 0.8 drew a Spine export (`.json` or `.skel`, plus its
642
+ `.atlas`) that `@esotericsoftware/spine-core` parsed and posed: the caller built the
643
+ `Skeleton` and the `AnimationState`, advanced them each frame, and handed the skeleton to
644
+ `renderer.render(skeleton)`. 1.0 loads one file, the `skeleton.model.json` that
645
+ `rigc build` writes, poses it through `rig-c/core` (bundled into the package, with no peer
646
+ dependency), and `RigPlayer` owns the track, so the caller's frame is `player.frame(dt)`.
647
+ A Spine export is refused by name before anything is fetched: the data has to be a rigc
648
+ build, and this package declares no loader for anything else.
649
+
650
+ What did not move: a positioned root element is still the rig's origin (Y up) with its
651
+ layout and scaling left to the caller, the DOM tier keeps its knobs under a new class
652
+ name, and unloading is still elements first, bitmaps second.
653
+
654
+ ### 0.8 → 1.0
655
+
656
+ | 0.8.0 (`spine-html`) | 1.0.0 (`rig-play`) | Note |
657
+ | --- | --- | --- |
658
+ | `npm i spine-html @esotericsoftware/spine-core` | `npm i rig-play`, and `npm i -D rig-c` for the build tool | 0.8 declared spine-core as a peer dependency (`>=4.0.0 <4.4.0`). 1.0.0 declares no dependencies and no peer dependencies. |
659
+ | `loadSkeletonAssets(options)` | `loadModel(options)` | One URL instead of two. The `.atlas` and `skeleton.json` a build writes beside the document are not fetched. |
660
+ | `LoadSkeletonAssetsOptions.atlasUrl`, `skeletonUrl` | `LoadModelOptions.modelUrl` | |
661
+ | `resolvePage(pageName, atlasUrl)` | `resolvePage(pageName, modelUrl)` | The default now resolves a page name against the model URL's directory. |
662
+ | `crossOrigin`, `fetch` | `crossOrigin`, `fetch` | Unchanged. |
663
+ | `scale` (`LoadSkeletonAssetsOptions`, `LoadSkeletonJsonOptions`) | none | See below. |
664
+ | `SkeletonAssets` | `ModelAssets` | |
665
+ | `SkeletonAssets.data` | `ModelAssets.document`, `animations`, `skins`, `stage`, `spec` | `document` is opaque (`ModelDocument`); the player poses it. What a caller used to read off the skeleton data is stated as `animations` (name and duration), `skins` (names) and `stage` (the stage the build declared, or null). |
666
+ | `SkeletonAssets.atlas` | `ModelAssets.pageImages` | The page images, keyed by page name. There is no atlas object; where each region sits is in the document's `pages` section. |
667
+ | `SkeletonAssets.regionImages` | `ModelAssets.regionImages` | Same `Map<string, RegionImage>`. |
668
+ | `SkeletonAssets.dispose()`, `AtlasAssets.dispose()` | `ModelAssets.dispose()` | Same contract: frees the blob URLs the load minted, idempotent, called after the players are disposed. |
669
+ | `loadAtlasAssets` + `loadSkeletonJson` (one atlas, several skeletons) | none | One `loadModel` backs any number of `RigPlayer`s of the same rig. Two rigs are two loads, and each cuts its own regions. See below. |
670
+ | `loadSkeletonBinary` from `spine-html/binary` | none | 1.0.0 has one entry point. A `.skel` URL is refused by name. |
671
+ | `unpackRegions(atlas, pageImages)` | `unpackRegions(pages, pageImages)` | The first argument is the document's `pages` section (`readonly PageLayout[]`) instead of a `TextureAtlas`. |
672
+ | `revokeRegions(images)` | `revokeRegions(images)` | Unchanged. |
673
+ | `RegionImage` | `RegionImage` | Unchanged (`url`, `width`, `height`, in atlas units). |
674
+ | `DomTexture` | none | Not exported; there is no atlas page to attach a texture to. |
675
+ | `new Skeleton(assets.data)` and `new AnimationState(new AnimationStateData(assets.data))` | `new RigPlayer(root, assets, options?)` | The player holds the pose and the track. |
676
+ | `state.setAnimation(0, 'walk', true)` | `player.play('walk', { loop: true })` | `loop` defaults to true. `play` opens the animation at its first pose with the physics reset there. `player.current` names what is playing. |
677
+ | `skeleton.findSlot('x').attachment = null` to hide a slot, or a second skeleton with slots emptied | `RigPlayerOptions.slots`, `player.slots`, `player.posedFrame(slots)` | A draw filter since 1.6.0 — the pose is the whole rig's; a clipping slot left out does not clip. See *Drawing some slots only*. |
678
+ | `state.setAnimation(1, 'smile', false)` with a mix, `addAnimation`, `setEmptyAnimation`, `addEmptyAnimation`, `getCurrent(track)`, `entry.alpha`, `entry.additive` | `player.play(name, { track, loop, mix, alpha, additive })`, `player.queue(name, { track, loop, mix, delay, alpha, additive })`, `player.clear(track, { mix })`, `player.queueClear(track, { mix, delay })`, `player.setAlpha(track, alpha)`, `player.entry(track)` | Since 1.5.0, rig-c's live tracks: the runtime's mixing at tolerance 0. Constraint, sequence, draw-order and path-deform timelines are not mixed and are refused on the tracks. See *Several tracks*. |
679
+ | `state.update(delta)`, `state.apply(skeleton)`, `skeleton.update(delta)`, `skeleton.updateWorldTransform(Physics.update)`, `renderer.render(skeleton)` | `player.frame(dt)` | Or `player.advance(dt)` then `player.draw()`, to time the two apart. |
680
+ | time scale (the caller's own, on the spine-core side) | `player.timeScale` | Multiplies every step. 0 holds the pose without re-posing it; a negative value is not stepped. |
681
+ | holding a pose (the caller stopped advancing) | `player.pause()`, `player.resume()` | `frame` keeps drawing the held pose. |
682
+ | moving to a time (the caller's own, on the spine-core side) | `player.seek(time)`, `RigPlayerOptions.seekStep`, `player.time` | A seek reopens the animation and steps forward in `seekStep` increments (1/60 s by default). Events and completes crossed on the way are not fired. |
683
+ | events (the caller's own listener on the spine-core side) | `player.on('event', listener)`, `player.on('complete', listener)` | `'event'` hands a `RigEvent` (`name`, `time`, `int`, `float`, `string`, `track`); `'complete'` hands `{ animation, track }`. `on` returns a function that removes the listener. |
684
+ | skin (set by the caller on its `Skeleton`) | `RigPlayerOptions.skin`, `player.skin` | A constructor option, and settable on a live player since 1.4.0: the pose re-resolves under the new skin and the track keeps its animation, loop and time (reopened and stepped there, as `seek` does). The names are in `ModelAssets.skins`. Without it the rig is posed with no skin set. |
685
+ | `SpineHtmlRenderer` | `DomRenderer`, reached as `player.renderer` | In `mode: 'dom'`, the default. `mode: 'canvas'` is new and makes `player.renderer` a `CanvasRenderer`. |
686
+ | `new SpineHtmlRenderer(root, regionImages)` | `new DomRenderer(root, regionImages, pages?)` | Only for drawing your own frames; `RigPlayer` constructs its renderer. `pages` is the page-image map the mesh tier samples (`ModelAssets.pageImages`). A hand-built `regionImages` map is still accepted. |
687
+ | `renderer.render(skeleton)` | `renderer.render(frame)` | Takes a `PosedFrame`, not a skeleton. `player.posedFrame()` returns the one the player would draw. |
688
+ | `renderer.pixelRatio` | `player.renderer.pixelRatio` | On both renderers. Carried over when `player.mode` changes. |
689
+ | `renderer.syncPixelRatio()` | `player.renderer.syncPixelRatio()` | On both renderers, the same meaning and the same deadband (since 1.3.0; before it, DOM mode only). |
690
+ | `renderer.meshBackingPixels` | `DomRenderer.meshBackingPixels` | DOM mode only. |
691
+ | `renderer.meshBackend`, `meshBackendActive`, type `MeshBackend` | `DomRenderer.meshBackend`, `meshBackendActive`, type `MeshBackend` | Same values (`'canvas2d'` default, `'webgl'`). Also settable up front as `RigPlayerOptions.meshBackend`. |
692
+ | `renderer.triangleExpand` | `DomRenderer.triangleExpand` | Same default (0.5). |
693
+ | `renderer.clipping` | `player.renderer.clipping` | On both renderers. Carried over when `player.mode` changes. |
694
+ | `clipCount`, `clipSkipCount`, `clipWriteCount` | same names on `DomRenderer` | `clipSkipCount` counts less than it did: a second clip met while one is in force, and a clip on an inactive bone, no longer reach the frame, so they are not counted. |
695
+ | `meshCount`, `meshReuseCount`, `canvasReallocCount`, `triangleCount` | same names on `DomRenderer` | |
696
+ | tint: skeleton × slot × attachment colour | `player.color` × slot × attachment | `player.color` is `[r, g, b, a]` and takes the place of the skeleton's colour. The product arrives as `tint` on each `PosedSlot`. |
697
+ | dark (two-colour) tint: unsupported | `DomRenderer`: unsupported. `CanvasRenderer`: drawn | Carried as `dark` on a `PosedSlot`. The canvas mode's canvas2d fallback draws alpha only. |
698
+ | `renderer.dispose()` | `player.dispose()` | Then `assets.dispose()`, as before. `DomRenderer.dispose()` and `CanvasRenderer.dispose()` exist for a renderer you constructed yourself. |
699
+ | `skeleton.findBone('head').worldX`, `.worldY`, `.a` … `.d` | `player.bone('head')` | `{ x, y, a, b, c, d, rotationX, rotationY, scaleX, scaleY, active }`, the core's world transform for the pose the player holds (the setup pose before `play`). An unknown name is refused by name. Since 1.1.0. |
700
+ | `bone.scaleY = …` on a `Skeleton` between `state.apply` and `updateWorldTransform` | `RigPlayerOptions.adjust`, `player.adjust`, `player.repose()` | A function called once per pose with the pose's bone locals (`bones.bone('mouth').scaleY = v`). A write lasts one pose: the core poses every step from the setup pose, so write the value you want, every pose — nothing compounds. See *Adjusting bones*. Since 1.2.0. |
701
+ | `skeleton.getBounds(offset, size)` | `player.bounds()` | `{ x, y, width, height }` or null, world units, Y up: the box of every drawn region's corners and mesh's vertices, a slot under a clip counted inside the clip's own box. `ModelAssets.stage` remains the declared framing, not this box. Since 1.1.0. |
702
+
703
+ ### No counterpart in 1.0.0
704
+
705
+ Things a 0.8 caller could do because it held the spine-core objects, or through a 0.8
706
+ export, for which 1.0.0 declares nothing:
707
+
708
+ - **A Spine export as input.** `loadSkeletonJson`, `loadSkeletonBinary`, `loadAtlasAssets`,
709
+ the `spine-html/binary` entry and `DomTexture` have no counterpart, and neither does
710
+ choosing which spine-core generation reads the data. `loadModel` reads a compiled model
711
+ document and nothing else.
712
+ - **Scaling the skeleton as it is read.** `LoadModelOptions` declares no `scale`. Scaling
713
+ the root element is still the caller's.
714
+ - **One unpacked atlas shared by different skeletons.** A document is one rig, and each
715
+ `loadModel` cuts its own regions and owns its own blob URLs. Sharing is per rig: one
716
+ load, several players.
717
+ - **Changing one slot from code** (its attachment, its colour). `RigPlayer` declares only
718
+ the whole-rig `color`. The frame record is a plain object, so a caller that draws its
719
+ own frames through `DomRenderer.render` or `CanvasRenderer.render` decides what is in
720
+ it.
721
+ - **Choosing how physics is stepped each frame.** 0.8's loop passed `Physics.update`
722
+ itself; 1.0.0 declares no physics option. `play` and `seek` reset physics at the
723
+ animation's first pose and every step advances it.
724
+ - **Track callbacks other than the two declared.** `on` accepts `'event'` and
725
+ `'complete'`.
726
+
727
+ Knobs on `DomRenderer` that `CanvasRenderer` does not declare:
728
+
729
+ - `meshBackend` and `meshBackendActive`. The canvas mode has its own pair, `backend` and
730
+ `backendActive` (type `CanvasBackend`, `'webgl'` by default).
731
+ - `triangleExpand`, `meshBackingPixels`, `clipWriteCount`, `meshCount`, `meshReuseCount`,
732
+ `triangleCount`. The canvas mode's counters are `drawCalls`, `blendFlushes`,
733
+ `trianglesDrawn`, `framesReused` and `blits`.
734
+
735
+ Both declare `pixelRatio`, `clipping`, `clipCount`, `clipSkipCount`, `canvasReallocCount`,
736
+ `render` and `dispose`. Only `pixelRatio` and `clipping` carry over when `player.mode`
737
+ changes.
738
+
739
+ ### Before and after
740
+
741
+ 0.8.0:
742
+
743
+ ```ts
744
+ import { Skeleton, AnimationState, AnimationStateData, Physics } from '@esotericsoftware/spine-core';
745
+ import { loadSkeletonAssets, SpineHtmlRenderer } from 'spine-html';
746
+ const assets = await loadSkeletonAssets({ atlasUrl: '/hero/hero.atlas', skeletonUrl: '/hero/hero.json' });
747
+ const skeleton = new Skeleton(assets.data);
748
+ const state = new AnimationState(new AnimationStateData(assets.data));
749
+ state.setAnimation(0, 'walk', true);
750
+ const renderer = new SpineHtmlRenderer(rootElement, assets.regionImages);
751
+ function frame(delta: number) {
752
+ state.update(delta);
753
+ state.apply(skeleton);
754
+ skeleton.update(delta);
755
+ skeleton.updateWorldTransform(Physics.update);
756
+ renderer.render(skeleton);
757
+ }
758
+ renderer.dispose(); assets.dispose(); // on unload
759
+ ```
760
+
761
+ 1.0.0:
762
+
763
+ ```ts
764
+ import { loadModel, RigPlayer } from 'rig-play';
765
+ const assets = await loadModel({ modelUrl: '/rigs/walk/skeleton.model.json' });
766
+ const player = new RigPlayer(rootElement, assets);
767
+ player.play('walk', { loop: true });
768
+ function frame(delta: number) {
769
+ player.frame(delta);
770
+ }
771
+ player.dispose(); assets.dispose(); // on unload
772
+ ```
773
+
774
+ ## Demo (this repository)
775
+
776
+ ```bash
777
+ bun install
778
+ bun run dev
779
+ ```
780
+
781
+ The demo plays rigc's own gallery rigs (`walk`, `flex`, `squash`, `portrait`,
782
+ `nod`, `look`, `ride`), each built by `rigc build` from a pinned rigc tag into
783
+ `public/rigs/<name>/` on first `dev`/`build` — and each again with `--pack` into
784
+ `public/rigs/<name>-packed/`. The same step builds this repository's test rigs
785
+ (`tests/rigs/`: `figure`, `glow`, `turned`), which `?rig=` also reaches; nothing
786
+ is downloaded but the rigc tag's gallery sources. `bun run fetch-assets` runs it
787
+ manually, and it is idempotent.
788
+
789
+ Debug knobs (query string): `?rig=flex` `?anim=wave` `?count=10` pick the scene,
790
+ `?tint=ff8080` tints the whole rig, `?dpr=2` overrides the mesh-canvas backing
791
+ ratio, `?timescale=0` freezes the pose (every mesh should report "reused"),
792
+ `?expand=0` disables the crack-closing clip overdraw, `?backend=webgl` rasterizes
793
+ meshes through the shared WebGL blitter (also a live header select; the stats line
794
+ names the active backend), `?clipping=0` turns clips back off (they are then
795
+ counted and skipped), and `?time=1.2` seeks every instance to the same pose for
796
+ deterministic captures.
797
+
798
+ ## Tests
799
+
800
+ ```bash
801
+ bun run test # builds + serves the demo, then runs chromium + webkit
802
+ ```
803
+
804
+ Playwright drives the demo (`tests/`, config in `playwright.config.ts`; CI
805
+ runs the same suite on ubuntu, one job). Every scene is a rig built by
806
+ `rigc build` and posed by `rig-c/core` through `RigPlayer` — rigc's gallery rigs,
807
+ and three test rigs authored in this repository (`tests/rigs/`) for what the
808
+ gallery does not carry: `figure` (clipping attachments in rigc's format —
809
+ convex, inverse, nested, whole-skeleton — rigid parts on turned bones, two grid
810
+ meshes), `glow` (additive slots with slot colours over two weighted meshes) and
811
+ `turned` (a region packed turned 90° on a hand-packed page). No Spine runtime
812
+ is installed or compared against: the pose is rig-c's, held to spine-core at
813
+ tolerance 0 by rig-c's own CI, and a pose doubt is a rigc issue. The visual
814
+ checks are **A/B within one run**: no golden snapshots are committed (they rot
815
+ across platforms/GPUs) — instead the same deterministic pose (`?time` +
816
+ `?timescale=0`) is screenshotted twice in the same engine and the buffers are
817
+ diffed directly with a shift-tolerant comparison, so missing parts, wrong
818
+ colors, and tint/blend/clip divergence fail regardless of platform.
819
+
820
+ **The picture gate** is the two render modes drawing the same picture: every
821
+ scene captured in the DOM mode and in the canvas mode and diffed — bad pixels at
822
+ most 1.5% of drawn content on the test-rig scenes (measured floors 0.007–0.524%,
823
+ macOS Chromium; each scene's own feature dropped from the canvas mode — tint,
824
+ additive blend, clipping, a mesh — scores 4.2–77%) and 2.5% on the gallery
825
+ scenes (floors 0.585–1.553%, Chromium and WebKit). The DOM tier's two mesh
826
+ backends get the same A/B (`?backend=canvas2d` against `?backend=webgl`, at most
827
+ 0.5%). Hairline seams are guarded by a deterministic canary (`?expand=0` must
828
+ change the canvas2d raster), the canvas2d source sub-rect by another (expand 32
829
+ against 8), and counter tests pin the dirty-skip / grow-only-backing /
830
+ clip-counter invariants plus the region corner order (BL, UL, UR, BR) and the
831
+ turned-region UVs, read off rig-c's pose against hand-written numbers.
832
+
833
+ Clipping gets its own oracle (`tests/clipping.spec.ts`), because a clip-path
834
+ that went through the wrong transform still parses and still counts as applied.
835
+ A clipped capture is compared against the **unclipped** capture of the same
836
+ slots masked in **screen space** by the world polygon — built once through the
837
+ stage transform, never through an element's local frame, so the check cannot
838
+ agree with the renderer by sharing its mistake. What it asserts is occupancy,
839
+ not pixel values: outside a 3 px band around the polygon's outline (where the
840
+ browser's clip-path antialiasing and the canvas `ctx.clip()` the oracle uses
841
+ legitimately differ), **no artwork may survive where the polygon excludes it
842
+ and none may go missing where it does not** — both counts absolute, no budget.
843
+ Pixel values are logged but not asserted, because a clipped element is drawn
844
+ through a mask and its silhouettes come out a shade different all over the
845
+ picture; a control capture, clipped by a polygon that removes nothing, pins
846
+ that down by coming back byte-identical to the unclipped one.
847
+
848
+ The loading path is not observable in a rendered frame, so it gets its own
849
+ page (`tests/harness.html`, a second build entry) that exposes the library to
850
+ the specs directly. Its oracle is the browser: a revoked object URL stops
851
+ resolving, so blob ownership — every unpacked URL freed, nothing the caller
852
+ owns touched, nothing stranded by a failed load — is asserted rather than
853
+ assumed.
854
+
855
+ ## Benchmark: DOM mode vs canvas mode
856
+
857
+ ```bash
858
+ bun run bench:dev # the page, for a person to watch (and for Safari)
859
+ bun run bench # drives it in a headed Chromium and writes a report
860
+ ```
861
+
862
+ `bench/` is a separate vite project — not part of the library, and not part of
863
+ what `bun run build` emits — that plays the same rigc gallery build in both
864
+ render modes side by side, each with its own stats line in the demo's style.
865
+ Scenes by query string: `?scene=mesh` (`portrait-packed` turning its head, the
866
+ deform tier working every frame), `?scene=held` (the same pose frozen, where
867
+ unchanged meshes reuse their raster and an unchanged frame is reused),
868
+ `?scene=rigid` (`walk-packed`, region attachments only) and
869
+ `?scene=many&count=N` independent players; `?rig=` and `?model=` name another
870
+ build. All four take `&count=N` up to 64 (a page limit, so that a cell stays
871
+ something you can see), laid out on one grid whose per-rig scale shrinks with
872
+ the column count, so a step up in count adds rigs rather than cropping the ones
873
+ already there.
874
+
875
+ **The two sides draw the same picture.** Both place rigs with one derivation and
876
+ clip each to the same rect — the pane for a grid, the rig's own cell for `many`
877
+ — with `overflow: hidden` on a box, the way a page embeds a player, and then
878
+ *check* it: each side reports `origin Δpx`, the largest gap between where the
879
+ grid puts a rig and where that side drew it, and the report table carries it per
880
+ row. (`contain: layout paint` is deliberately not used: paint containment clips
881
+ to the same edge `overflow: hidden` does, and what it adds past the clip — a
882
+ stacking context, a containing block, an independent formatting context —
883
+ changes how one side is composited and buys the comparison nothing.) Both modes
884
+ share the package's single WebGL context however many players there are; the
885
+ canvas side's stats line says how many contexts the page holds.
886
+
887
+ `scripts/bench.mjs` walks `bench/scenes.json`, opens each scene in a **headed**
888
+ Chromium (a hidden page throttles `requestAnimationFrame`, so a headless
889
+ reading would be the browser's power policy rather than either mode's cost),
890
+ runs a fixed number of frames per mode — one at a time, because rAF has a single
891
+ cadence per document — and writes JSON plus a markdown table with the
892
+ conditions attached: browser version, device pixel ratio, window size, GPU
893
+ string, and the load average before and after. Over a threshold it stamps the
894
+ whole report `INVALID: load average too high` and exits non-zero, because a
895
+ benchmark on a busy machine measures the machine. `--corpus <dir>` points it at
896
+ local rigc builds that never enter this repository.
897
+
898
+ > **Numbers pending.** No comparison table is published yet. A reading taken on
899
+ > a loaded machine, a CI runner or a headless browser would not be worth
900
+ > printing. The table will be taken the way every other number in this README
901
+ > was: the two stats lines read on a real device, on a quiet machine, per scene
902
+ > and per engine — including Safari, which stays manual because no automation
903
+ > preserves what is being measured there. Until then the instrument exists and
904
+ > the measurement does not.
905
+
906
+ The server is part of the test: a run tests whatever is being served on its
907
+ port. Two checkouts of this repository on one machine (a worktree, a second
908
+ clone) default to the same port 4321 and reuse an existing server, so the
909
+ second run quietly tests the first one's build — green, and about the wrong
910
+ tree. Give each concurrent checkout its own port with `TEST_PORT`
911
+ (`TEST_PORT=4333 bun run test`); setting it also disables server reuse, so a
912
+ busy port fails the run instead of being borrowed. Unset, nothing changes:
913
+ port 4321, reuse unless `CI`.
914
+
915
+ Standing rule: **headless numbers are never Safari performance evidence** —
916
+ nothing in the suite asserts timing, and headless-WebKit fps/ms readings do
917
+ not transfer (software rasterizer, measured up to 28× off real Safari). The
918
+ perf oracle is the demo's stats line on a real device.
919
+
920
+ ## How it works
921
+
922
+ 1. `loadModel` reads the rig's compiled model document (`rig-c/core`'s `readModel`),
923
+ and `RigPlayer` opens an animation on a live track (`openTrack`): bones,
924
+ constraints, physics, deform and draw order are posed by the core — all
925
+ CPU-side, renderer-agnostic — one `dt` at a time.
926
+ 2. At load time each region of the document's `pages` section is cut into its own
927
+ bitmap (rotation restored), one blob URL per region — except regions that already
928
+ cover their whole page, which are used as they are.
929
+ 3. Per frame, the pose becomes a `PosedFrame`: for each slot in draw order, a region's
930
+ four world corners (order **BL, UL, UR, BR**) or a mesh's world vertices, page UVs
931
+ and triangles, its tint, blend and clip. For a region: flip Y (the frame is Y-up),
932
+ derive the affine from three corners, write one `matrix()` string. That's the
933
+ whole rigid render path.
934
+
935
+ ## License
936
+
937
+ rig-play's own code is MIT (see [LICENSE](LICENSE)). That says nothing about Spine,
938
+ so here is what is true of this package and this repository, stated plainly:
939
+
940
+ 1. The published package — `rig-play`, and `spine-html`, the same files — **links
941
+ nothing from Esoteric Software**. Its one module bundles the renderer and
942
+ `rig-c/core` (MIT), which poses rigc's model document; no part of the
943
+ [Spine Runtimes](https://github.com/EsotericSoftware/spine-runtimes) is in it or
944
+ required beside it.
945
+ 2. This repository links no Spine runtime either, since #63: no package of Esoteric
946
+ Software's npm scope is a dependency of any kind, and the lockfile names none.
947
+ `tests/package.spec.ts` asserts both.
948
+ 3. `rigc build`, which this repository runs to make its fixtures, also writes Spine
949
+ skeleton data (`skeleton.json` and `skeleton.atlas`) beside each model document.
950
+ Nothing here reads it, and it is neither committed nor published.
951
+ 4. A product that plays that Spine data with a Spine Runtime has integrated the Spine
952
+ Runtimes, whose licence permits it **under Section 2 of the
953
+ [Spine Editor License Agreement](https://esotericsoftware.com/spine-editor-license)**,
954
+ or otherwise on the condition that **each user of the product obtains their own
955
+ Spine Editor license** — the licence's own two routes, restated, not a term of
956
+ this project.
957
+
958
+ > **What a consumer does with rigc's Spine-format output is governed by Esoteric
959
+ > Software's terms**, not by this package — rig-play neither adds those terms nor
960
+ > removes them.
961
+
962
+ No example assets of Esoteric Software's are fetched or redistributed. See
963
+ [NOTICE.md](NOTICE.md) for the full notice.