@openbone/player 0.0.0-stage → 0.3.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 UX Century and OpenBone contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,223 @@
1
- # Temporary Holding Version
1
+ # @openbone/player
2
2
 
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.
3
+ A drop-in `<openbone-player>` web component and a `Player` class for OpenBone animations in the browser.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@openbone/player)](https://www.npmjs.com/package/@openbone/player)
6
+ [![MIT licence](https://img.shields.io/badge/licence-MIT-blue)](https://github.com/UXCentury/open-bone/blob/main/LICENSE)
7
+
8
+ [OpenBone](https://github.com/UXCentury/open-bone) is open-source 2D skeletal animation: Spine-style rigging,
9
+ Rive-style state machines and an MCP server for AI agents. This package is the quickest way to put an OpenBone file on
10
+ a web page. It loads a `.obone` or `.obonb` document and its images, runs the animation or state machine with
11
+ [`@openbone/runtime`](https://www.npmjs.com/package/@openbone/runtime), draws with
12
+ [`@openbone/render-webgl`](https://www.npmjs.com/package/@openbone/render-webgl) (falling back to
13
+ [`@openbone/render-canvas`](https://www.npmjs.com/package/@openbone/render-canvas) when WebGL2 is missing), routes
14
+ pointer events to state machine listeners, plays sounds with Web Audio and runs document scripts in the QuickJS sandbox
15
+ from [`@openbone/scripting`](https://www.npmjs.com/package/@openbone/scripting). For PixiJS, Phaser, Three.js or
16
+ CanvasKit, use the engine packages instead (see [Documentation](#documentation)).
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install @openbone/player
22
+ ```
23
+
24
+ `esbuild` is an optional peer dependency. You only need it for `@openbone/player/bundle` (see
25
+ [Script-tag player](#script-tag-player-no-bundler)).
26
+
27
+ ## Quick start
28
+
29
+ With a bundler (Vite, webpack, esbuild…). The knight below is `examples/knight.obone` from the repository; its state
30
+ machine is called `knight`, with a `walk` boolean and `attack` and `salute` triggers.
31
+
32
+ ```html
33
+ <openbone-player src="/knight.obone" state-machine="knight" style="width: 600px; height: 400px"></openbone-player>
34
+ <button id="attack">Attack</button>
35
+
36
+ <script type="module">
37
+ import { definePlayerElement } from "@openbone/player";
38
+
39
+ definePlayerElement(); // registers <openbone-player>
40
+
41
+ const knight = document.querySelector("openbone-player");
42
+ knight.addEventListener("openbone-load", () => knight.setInput("walk", true));
43
+ knight.addEventListener("openbone-event", (e) => console.log("event", e.detail.name));
44
+ knight.addEventListener("openbone-state", (e) => console.log(e.detail.layer, e.detail.from, "->", e.detail.to));
45
+ document.querySelector("#attack").addEventListener("click", () => knight.fire("attack"));
46
+ </script>
47
+ ```
48
+
49
+ Images and sounds load relative to the document's URL. The element is 400 × 300 px unless you size it with CSS.
50
+
51
+ ## API
52
+
53
+ ### Exports
54
+
55
+ | Export | |
56
+ |---|---|
57
+ | `definePlayerElement(tag?)` | Registers the element (default tag `openbone-player`). Safe to call more than once. |
58
+ | `OpenBonePlayerElement` | The element class. |
59
+ | `Player` | Plays a document on a canvas you own. The element wraps one. |
60
+ | `PlayerOptions` | Options type for `Player`. |
61
+ | `setScriptHostFactory(factory)` | Replaces how players create the script sandbox (for example `() => Promise.resolve(null)` to never load QuickJS). |
62
+ | `WebAudioBackend`, `WebAudioOptions` | The Web Audio playback used by the player. Also at `@openbone/player/audio`. |
63
+
64
+ ### `<openbone-player>` attributes
65
+
66
+ | Attribute | Default | |
67
+ |---|---|---|
68
+ | `src` | | URL of a `.obone` (JSON) or `.obonb` (binary) file. Changing it reloads. |
69
+ | `state-machine` | first | State machine to run, by name or id. |
70
+ | `animation` | | Play this animation instead of a state machine. |
71
+ | `skin` | default skin | Skin (outfit) by name or id. Changing it switches the outfit without reloading. |
72
+ | `fit` | `contain` | `contain`, `cover` or `none` (actual size, centred). |
73
+ | `renderer` | `webgl` | `webgl` or `canvas`. WebGL falls back to Canvas 2D when WebGL2 is not available. |
74
+ | `background` | the file's | Any CSS colour (`#fff`, `rebeccapurple`, `rgb(0 0 0 / 50%)`, …), or `transparent` / `none`. |
75
+ | `autoplay` | on | `autoplay="false"` loads and draws the first frame, then waits for `play()`. |
76
+ | `scripts` | on | `scripts="none"` never runs the document's scripts. |
77
+ | `audio` / `muted` | on | `audio="off"` disables sound; `muted` loads sounds but starts muted. |
78
+
79
+ Changing `skin` switches the skin in place. Changing any other attribute, including setting `src` after the element is
80
+ on the page, reloads the player with the new settings.
81
+
82
+ ### Element methods and events
83
+
84
+ | Method | |
85
+ |---|---|
86
+ | `setInput(name, value)` | Set a state machine input (boolean, number or string). |
87
+ | `fire(name)` | Fire a trigger input. |
88
+ | `setText(slot, text)` | Show fixed text (or an `{input}` template) in a slot's text attachment; `null` restores it. |
89
+ | `setSkin(name)` | Switch skin (updates the `skin` attribute); `null` shows the default skin. |
90
+ | `play()` / `pause()` | Start or stop playback and sound. |
91
+ | `player` | The underlying `Player`, or `null` before the element is connected. |
92
+
93
+ | Event | `detail` |
94
+ |---|---|
95
+ | `openbone-load` | none: the document, images and script sandbox are ready. |
96
+ | `openbone-event` | The fired event: `name`, `id`, `time`, `int`, `float`, `string`, `animation`. |
97
+ | `openbone-state` | A state change: `layer`, `from` (or `null`), `to`. |
98
+
99
+ Events bubble and cross the shadow root.
100
+
101
+ ### `Player`
102
+
103
+ ```ts
104
+ import { Player } from "@openbone/player";
105
+
106
+ const canvas = document.querySelector<HTMLCanvasElement>("#c")!; // give it a CSS size
107
+ const player = new Player({
108
+ canvas,
109
+ src: "/knight.obone",
110
+ stateMachine: "knight",
111
+ fit: "contain",
112
+ onEvent: (e) => console.log("event", e.name, e.int, e.float, e.string),
113
+ onStateChange: (e) => console.log(e.layer, e.from, "->", e.to),
114
+ });
115
+ await player.ready; // the document, its images and (if needed) the script sandbox are loaded
116
+
117
+ player.setInput("walk", true);
118
+ player.fire("salute");
119
+ player.speed = 0.5;
120
+ ```
121
+
122
+ `PlayerOptions`:
123
+
124
+ | Option | |
125
+ |---|---|
126
+ | `canvas` | The canvas to draw on. It follows its CSS size (a `ResizeObserver`) at the device pixel ratio. |
127
+ | `src` | A URL, or an already parsed `OpenBoneDocument`. |
128
+ | `baseUrl` | Folder for relative image and audio paths (default: the folder of `src`). |
129
+ | `resolveImageUrl(src)`, `resolveAudioUrl(asset)` | Map asset paths to URLs yourself (overrides `baseUrl`). |
130
+ | `stateMachine`, `animation`, `skin`, `autoplay`, `fit`, `renderer`, `background` | As the attributes above. `background: null` is transparent. |
131
+ | `scripts` | `"quickjs"` (default when the document has scripts), `"none"`, or your own `ScriptHost`. |
132
+ | `audio` | `true` (default), `false` or `"muted"`. |
133
+ | `audioContext` | Share an existing `AudioContext` instead of creating one. |
134
+ | `onEvent`, `onStateChange`, `onLoad` | Callbacks. |
135
+
136
+ Members: `ready` (promise), `play()`, `pause()`, `playing`, `speed` (sounds follow it), `setInput`, `getInput`,
137
+ `fire`, `setText`, `setSkin`, `skins`, `playAnimation(name, loop?)`, `setFit(fit)`, `setMuted(muted)`, `muted`,
138
+ `audio`, `instance` (the runtime `OpenBoneInstance`), `stateMachine`, `doc`, `clientToSkeleton(clientX, clientY)`,
139
+ `boundingBoxes()` and `dispose()`.
140
+
141
+ `boundingBoxes()` returns the active bounding boxes in skeleton space with point, segment, AABB and overlap queries
142
+ (see `@openbone/runtime`); `clientToSkeleton` converts page coordinates through the current fit:
143
+
144
+ ```ts
145
+ canvas.addEventListener("click", (e) => {
146
+ const hit = player.boundingBoxes().containsPoint(...player.clientToSkeleton(e.clientX, e.clientY));
147
+ if (hit) console.log("clicked", hit.slot.data.name);
148
+ });
149
+ ```
150
+
151
+ ### Pointer input
152
+
153
+ Pointer down, up and move over the canvas are converted to skeleton space and sent to the state machine, so listeners
154
+ on bounding boxes (hover, click) work without extra code. Leaving the canvas ends hovers.
155
+
156
+ ### Audio
157
+
158
+ Sounds load with the document and play through Web Audio. Browsers only allow sound after a user gesture, so audio
159
+ unlocks on the first click or key press; one-shot sounds requested before that are dropped. `pause()` pauses sounds
160
+ where they are and `play()` resumes them.
161
+
162
+ ### Scripts
163
+
164
+ Documents with scripts load the QuickJS sandbox on demand (a dynamic import of `@openbone/scripting`). Pass
165
+ `scripts: "none"` (or the `scripts="none"` attribute) to skip it. If your bundler pre-bundles dependencies, exclude
166
+ `quickjs-emscripten` so it can find its `.wasm` file; the repository's Vite configs use
167
+ `optimizeDeps: { exclude: ["quickjs-emscripten"] }`.
168
+
169
+ ### Disposal
170
+
171
+ Removing the element from the page disposes its player. With a `Player` of your own, call `dispose()`: it stops the
172
+ render loop and the sounds and frees the WebGL resources.
173
+
174
+ ## Script-tag player (no bundler)
175
+
176
+ The npm package ships ES modules, not a prebuilt script. `@openbone/player/bundle` (Node only, needs `esbuild`)
177
+ builds a self-contained player for plain `<script src>` use:
178
+
179
+ ```ts
180
+ import { mkdir, writeFile } from "node:fs/promises";
181
+ import { buildScriptsAddon, buildWebBundle, quickJsWasmBytes } from "@openbone/player/bundle";
182
+
183
+ await mkdir("public", { recursive: true });
184
+ // Classic script that defines <openbone-player> and window.OpenBone. "lazy": the script sandbox is fetched
185
+ // from next to the player, only for animations that have scripts.
186
+ await writeFile("public/openbone-player.js", await buildWebBundle({ format: "iife", scripts: "lazy" }));
187
+ await writeFile("public/openbone-scripts.js", await buildScriptsAddon());
188
+ await writeFile("public/quickjs.wasm", quickJsWasmBytes());
189
+ ```
190
+
191
+ ```html
192
+ <script src="openbone-player.js"></script>
193
+ <openbone-player src="walker.obone" state-machine="character" style="width: 600px; height: 380px"></openbone-player>
194
+ ```
195
+
196
+ Including the script registers `<openbone-player>` and sets `window.OpenBone` to `{ Player, OpenBonePlayerElement,
197
+ definePlayerElement, parseDocument, version }`.
198
+
199
+ `buildWebBundle` options: `format` (`"iife"` or `"esm"`), `minify` (default true) and `scripts` (`true` inlines
200
+ QuickJS in one file, `"lazy"` loads `openbone-scripts.js` and `quickjs.wasm` from the player's folder only when
201
+ needed, `false` leaves the sandbox out and skips scripts with a warning). Set `window.OPENBONE_SCRIPTS_BASE` to load
202
+ the lazy files from another folder. `buildPlayerBundle()` builds the variant used by the WebView packages.
203
+
204
+ You can also skip the build: the OpenBone editor's **Web** export (and the MCP server's `export_file` with format
205
+ `web`) writes the player, your animation and a demo page as a ZIP, or as one self-contained HTML file.
206
+
207
+ ## Documentation
208
+
209
+ - [Architecture](https://github.com/UXCentury/open-bone/blob/main/docs/architecture.md): runtime model, rendering, audio and scripts
210
+ - [File format](https://github.com/UXCentury/open-bone/blob/main/docs/format.md): `.obone` and `.obonb`
211
+ - [Engine exports](https://github.com/UXCentury/open-bone/blob/main/docs/engine-exports.md): WebView packages and the host bridge
212
+ - [Runtime specification](https://github.com/UXCentury/open-bone/blob/main/docs/runtime-spec.md)
213
+ - Related packages: [`@openbone/runtime`](https://www.npmjs.com/package/@openbone/runtime),
214
+ [`@openbone/render-webgl`](https://www.npmjs.com/package/@openbone/render-webgl),
215
+ [`@openbone/render-canvas`](https://www.npmjs.com/package/@openbone/render-canvas),
216
+ [`@openbone/pixi`](https://www.npmjs.com/package/@openbone/pixi),
217
+ [`@openbone/phaser`](https://www.npmjs.com/package/@openbone/phaser),
218
+ [`@openbone/three`](https://www.npmjs.com/package/@openbone/three),
219
+ [`@openbone/canvaskit`](https://www.npmjs.com/package/@openbone/canvaskit)
220
+
221
+ ## License
222
+
223
+ MIT, © UX Century and OpenBone contributors. See [LICENSE](https://github.com/UXCentury/open-bone/blob/main/LICENSE).
@@ -0,0 +1,90 @@
1
+ import { type AudioAsset, type OpenBoneDocument } from "@openbone/core";
2
+ import type { AudioCommand } from "@openbone/runtime";
3
+ export interface WebAudioOptions {
4
+ /** Base URL for relative audio paths. */
5
+ baseUrl?: string;
6
+ /** Map an asset to the URL to load (overrides baseUrl), e.g. for files read from disk. */
7
+ resolveUrl?: (asset: AudioAsset) => string;
8
+ /** Use an existing context instead of creating one on first use. */
9
+ context?: AudioContext;
10
+ /** Called for every command handled (and for dropped/failed ones), for debugging. */
11
+ onLog?: (message: string, cmd?: AudioCommand) => void;
12
+ }
13
+ /**
14
+ * Plays the runtime's AudioCommands with the Web Audio API: resolves and decodes assets (cached per URL),
15
+ * routes each sound through its bus into the master, applies fades, and follows the document's mix
16
+ * (call `syncMix()` after changing bus/master values). Browsers block audio until a user gesture, so the
17
+ * context is resumed by the first pointer/key event (see `unlock`); one-shots requested before that are skipped.
18
+ */
19
+ export declare class WebAudioBackend {
20
+ doc: OpenBoneDocument;
21
+ private opts;
22
+ ctx: AudioContext | null;
23
+ private master;
24
+ private buses;
25
+ private buffers;
26
+ private voices;
27
+ private hostMuted;
28
+ private unbind;
29
+ constructor(doc: OpenBoneDocument, opts?: WebAudioOptions);
30
+ /** True once the browser lets the context play. */
31
+ get unlocked(): boolean;
32
+ get muted(): boolean;
33
+ /** Mute everything (independent of the document's own mute). */
34
+ setMuted(m: boolean): void;
35
+ setDocument(doc: OpenBoneDocument): void;
36
+ setBaseUrl(url: string): void;
37
+ /** Create (if needed) and resume the context now. Call it from a user gesture (a click) so the browser allows sound. */
38
+ activate(): AudioContext | null;
39
+ private context;
40
+ private masterNode;
41
+ private busNode;
42
+ /** Mutes set while playing by "mix" commands (mute buttons): bus id, "" = master. They win over the document. */
43
+ private mixMutes;
44
+ private isMuted;
45
+ /** Apply the document's master/bus volumes and mutes (and the host mute, and mute buttons) to the graph. */
46
+ syncMix(): void;
47
+ /** Effective gain a sound on `busId` gets from the mix right now (master x bus, 0 when muted). */
48
+ busGain(busId: string | null): number;
49
+ url(asset: AudioAsset): string;
50
+ /** Fetch and decode an asset (cached by URL). */
51
+ load(asset: AudioAsset): Promise<AudioBuffer | null>;
52
+ /** Start decoding every asset in the document. */
53
+ preload(): Promise<(AudioBuffer | null)[]>;
54
+ /** Resume the context on the first user gesture on `target` (default: window). Safe to call more than once. */
55
+ unlock(target?: EventTarget): void;
56
+ /** Handle one runtime command. Pass this to `instance.on("audio", ...)`. */
57
+ handle: (cmd: AudioCommand) => void;
58
+ private play;
59
+ /** (Re)start a voice's buffer from `offset` seconds into the file, at the sound's rate × the backend's speed. */
60
+ private startSource;
61
+ /** Where a voice is in its file now (seconds). */
62
+ private position;
63
+ private speed;
64
+ private pausedAll;
65
+ /**
66
+ * Playback speed for everything this backend plays (sounds already playing change too), like a player's speed
67
+ * control: 2 plays twice as fast and an octave higher.
68
+ */
69
+ setSpeed(speed: number): void;
70
+ /** Pause every voice where it is (resumeAll continues them from there). */
71
+ pauseAll(): void;
72
+ /** Continue every paused voice from where it was paused. */
73
+ resumeAll(): void;
74
+ /**
75
+ * A short grain of a sound at `offset` seconds into its file, for scrubbing a timeline: fades in and out over a few
76
+ * milliseconds so dragging sounds like a tape head rather than clicks.
77
+ */
78
+ scrub(assetId: string, offset: number, o?: {
79
+ duration?: number;
80
+ volume?: number;
81
+ rate?: number;
82
+ bus?: string | null;
83
+ }): void;
84
+ private stop;
85
+ /** Stop every voice (optionally fading). */
86
+ stopAll(fade?: number): void;
87
+ /** Number of voices currently playing or loading. */
88
+ get activeVoices(): number;
89
+ dispose(): void;
90
+ }