@openbone/pixi 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,148 @@
1
- # Temporary Holding Version
1
+ # @openbone/pixi
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
+ OpenBone runtime for PixiJS v8: an OpenBone document as a Pixi `Container`.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@openbone/pixi)](https://www.npmjs.com/package/@openbone/pixi)
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 plays OpenBone documents inside a PixiJS v8
10
+ scene, with state machines, pointer listeners, events, skins, scripts and sound. Playback comes from
11
+ [`@openbone/engine-kit`](https://www.npmjs.com/package/@openbone/engine-kit) and
12
+ [`@openbone/runtime`](https://www.npmjs.com/package/@openbone/runtime); drawing uses Pixi meshes built from the same
13
+ batches as the reference renderer, [`@openbone/render-webgl`](https://www.npmjs.com/package/@openbone/render-webgl).
14
+ For a page without Pixi, use [`@openbone/player`](https://www.npmjs.com/package/@openbone/player).
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ npm install @openbone/pixi pixi.js
20
+ ```
21
+
22
+ `pixi.js` v8 is a peer dependency (`^8.0.0`).
23
+
24
+ ## Quick start
25
+
26
+ ```ts
27
+ import { Application } from "pixi.js";
28
+ import { OpenBone, loadOpenBone } from "@openbone/pixi";
29
+
30
+ const app = new Application();
31
+ await app.init({ preference: "webgl", width: 900, height: 600, background: "#1b1e24" });
32
+ document.body.appendChild(app.canvas);
33
+
34
+ // Loads the document, its images (atlas pages when packed) and, when it has scripts, the script sandbox.
35
+ const knight = await OpenBone.from("/knight.obone", { stateMachine: "knight" });
36
+ knight.position.set(knight.asset.doc.originX, knight.asset.doc.originY); // skeleton origin, in stage pixels
37
+ app.stage.addChild(knight);
38
+
39
+ knight.setInput("walk", true);
40
+ knight.onOpenBone("stateChange", (e) => console.log(e.layer, e.from, "->", e.to));
41
+ knight.onOpenBone("event", (e) => console.log("event", e.name));
42
+ setTimeout(() => knight.fire("attack"), 500);
43
+
44
+ // Load once, then make several copies that share the textures.
45
+ const asset = await loadOpenBone("/button.obone");
46
+ for (let i = 0; i < 2; i++) {
47
+ const button = await OpenBone.from(asset);
48
+ button.scale.set(0.5);
49
+ button.position.set(100 + i * 250 + asset.doc.originX * 0.5, 20 + asset.doc.originY * 0.5);
50
+ app.stage.addChild(button);
51
+ }
52
+ ```
53
+
54
+ `knight.obone` and `button.obone` are in the repository's `examples/` folder. The container's position is the
55
+ skeleton origin; at scale 1, one skeleton unit is one pixel, with y down like the rest of Pixi.
56
+
57
+ ## API
58
+
59
+ | Export | |
60
+ |---|---|
61
+ | `OpenBone` | The display object (a `Container`). `await OpenBone.from(src, options)` loads and creates it. |
62
+ | `loadOpenBone(src, options)` | Loads a document and its textures into an `OpenBoneAsset` that many objects can share. |
63
+ | `OpenBoneAsset` | `{ doc, baseUrl, textures }` (Pixi textures by image or atlas page id). |
64
+ | `OpenBoneOptions`, `LoadOptions`, `DriverOptions`, `InputValue`, `OpenBoneSource` | Option and value types. |
65
+ | `BatchMesh`, `PIXI_BLEND` | The mesh class used per batch, and the blend mode mapping. |
66
+
67
+ `src` is a URL, bytes (`ArrayBuffer` or `Uint8Array` of a `.obone` or `.obonb` file), a parsed document or, for
68
+ `OpenBone.from`, an `OpenBoneAsset`.
69
+
70
+ ### Options
71
+
72
+ | Option | Default | |
73
+ |---|---|---|
74
+ | `stateMachine` / `animation` / `loop` | first state machine, else first animation | What to run. |
75
+ | `skin` | default skin | Skin (outfit) by name or id. |
76
+ | `scripts` | `"quickjs"` when the document has scripts | `"none"` or your own `ScriptHost`. |
77
+ | `audio` | `true` | `false` or `"muted"`. |
78
+ | `audioContext`, `audioBaseUrl`, `resolveAudioUrl`, `unlockTarget` | | Sound setup (see engine-kit). |
79
+ | `onEvent`, `onStateChange` | | Callbacks. |
80
+ | `autoUpdate` | `true` | Advance on a Pixi ticker. Set `false` and call `update(dt)` (seconds) yourself. |
81
+ | `ticker` | `Ticker.shared` | The ticker used when `autoUpdate` is on. |
82
+ | `interactive` | `true` | Route Pixi pointer events to the state machine. |
83
+ | `resolution` | `devicePixelRatio` | Pixel ratio that text is rasterised at. |
84
+ | `baseUrl`, `fetch` (loading) | the document's folder | Where relative image and audio paths load from, and the fetch to use. |
85
+ | `resolveImageUrl(src)` (loading) | | Map an image path to the URL to load. |
86
+
87
+ ### Methods and properties
88
+
89
+ | Member | |
90
+ |---|---|
91
+ | `setInput(name, value)`, `getInput(name)`, `fire(name)` | State machine inputs and triggers. |
92
+ | `play(animation, loop?)`, `useStateMachine(name?)` | Switch to an animation or a state machine. |
93
+ | `setSkin(name)`, `setText(slot, text)` | Outfit, and text for a slot's text attachment (`null` restores it). |
94
+ | `pause()`, `resume()`, `paused`, `speed` | Playback. Pausing also pauses sounds; `speed` changes their rate too. |
95
+ | `update(dt)`, `redraw()` | Advance and rebuild the meshes; rebuild only (after changing the pose by hand). |
96
+ | `onOpenBone(name, fn)` | Listen to `"event"`, `"stateChange"` or `"audio"`. Returns an unsubscribe function. |
97
+ | `artboard` | The artboard rectangle in the container's space (y down). |
98
+ | `boundingBoxes()`, `toSkeleton(global)`, `fromSkeleton(x, y)` | Bounding-box queries in skeleton space (y up), and conversion from / to Pixi global coordinates: `obj.boundingBoxes().containsPoint(...obj.toSkeleton(e.global))`. |
99
+ | `drawCalls` | Batches drawn in the last update. |
100
+ | `driver`, `instance`, `skeleton`, `stateMachine`, `asset` | Lower-level access. |
101
+ | `destroy()` | Stops ticking, stops sounds and frees text and particle textures. Shared asset textures are kept. |
102
+
103
+ ### Pointer input
104
+
105
+ With a state machine and `interactive` on, the object listens to `pointerdown`, `pointerup`, `pointerupoutside` and
106
+ `globalpointermove`, with the artboard as hit area. Points are converted to skeleton space for the state machine's
107
+ listeners. Moving off the artboard ends hovers.
108
+
109
+ ### Sound and scripts
110
+
111
+ Sounds play with Web Audio and unlock on the first click or key press. Documents with scripts load the QuickJS
112
+ sandbox in `OpenBone.from`. If you use Vite, exclude `quickjs-emscripten` from dependency pre-bundling
113
+ (`optimizeDeps: { exclude: ["quickjs-emscripten"] }`) so it finds its `.wasm` file, as the repository's demo does.
114
+
115
+ ## How it draws
116
+
117
+ Each frame the pose is grouped into render-webgl's batches (one per texture or atlas page and blend mode). Each batch
118
+ is one `Mesh` with a small vertex-coloured shader, so meshes, weights, tints, per-vertex particle colours and sprite
119
+ sequences look as in the editor. Batches with a two-colour tint (a slot `dark` colour) switch to a second shader with
120
+ a per-vertex dark colour; other batches never upload it. Premultiplied atlas pages are uploaded as they are; other
121
+ images are premultiplied on upload.
122
+
123
+ - **Clipping** masks become stencil masks (`Graphics`).
124
+ - **Blend modes** map to Pixi's `normal`, `add`, `multiply` and `screen`, which use the same GL blend functions.
125
+ - **Text** attachments are rasterised to canvas textures. **Particles** use the built-in soft sprite.
126
+ - Pack an atlas when exporting for the fewest draw calls (`drawCalls`).
127
+
128
+ The shader is GLSL, so use Pixi's WebGL renderer (`preference: "webgl"`, Pixi's default).
129
+
130
+ ## Demo
131
+
132
+ From a checkout: `pnpm --filter @openbone/examples engines`, then open http://localhost:5190/pixi/ (add
133
+ `?example=campfire`, `rocket`, `crash`… for other examples).
134
+
135
+ ## Documentation
136
+
137
+ - [Architecture](https://github.com/UXCentury/open-bone/blob/main/docs/architecture.md): runtime model and rendering
138
+ - [File format](https://github.com/UXCentury/open-bone/blob/main/docs/format.md)
139
+ - [Demo source](https://github.com/UXCentury/open-bone/blob/main/examples/engines/pixi/main.ts)
140
+ - Related packages: [`@openbone/engine-kit`](https://www.npmjs.com/package/@openbone/engine-kit),
141
+ [`@openbone/phaser`](https://www.npmjs.com/package/@openbone/phaser),
142
+ [`@openbone/three`](https://www.npmjs.com/package/@openbone/three),
143
+ [`@openbone/canvaskit`](https://www.npmjs.com/package/@openbone/canvaskit),
144
+ [`@openbone/player`](https://www.npmjs.com/package/@openbone/player)
145
+
146
+ ## License
147
+
148
+ MIT, © UX Century and OpenBone contributors. See [LICENSE](https://github.com/UXCentury/open-bone/blob/main/LICENSE).
@@ -0,0 +1,116 @@
1
+ import { type OpenBoneDocument } from "@openbone/core";
2
+ import { type Batch, type DriverOptions, type FetchOptions, type InputValue, OpenBoneDriver, type OpenBoneSource } from "@openbone/engine-kit";
3
+ import { Container, Geometry, Mesh, Shader, Texture, Ticker } from "pixi.js";
4
+ export type { DriverOptions, InputValue, OpenBoneSource } from "@openbone/engine-kit";
5
+ /** A loaded document and its textures, shareable by many OpenBone objects. */
6
+ export interface OpenBoneAsset {
7
+ doc: OpenBoneDocument;
8
+ baseUrl: string;
9
+ /** Pixi textures by image / atlas page id. */
10
+ textures: Map<string, Texture>;
11
+ }
12
+ export interface LoadOptions extends FetchOptions {
13
+ /** Map an image path from the document to the URL to load (overrides baseUrl). */
14
+ resolveImageUrl?: (src: string) => string;
15
+ }
16
+ /** Load a .obone / .obonb document and its images (atlas pages when packed) as Pixi textures. */
17
+ export declare function loadOpenBone(src: OpenBoneSource, opts?: LoadOptions): Promise<OpenBoneAsset>;
18
+ export interface OpenBoneOptions extends DriverOptions {
19
+ /** Advance with Pixi's shared ticker (default true). Set false and call `update(dt)` yourself. */
20
+ autoUpdate?: boolean;
21
+ /** Ticker to use when autoUpdate is on (default Ticker.shared). */
22
+ ticker?: Ticker;
23
+ /** Route Pixi pointer events to the state machine's listeners (default true). */
24
+ interactive?: boolean;
25
+ /** Screen pixels per CSS pixel used to rasterise text (default devicePixelRatio). */
26
+ resolution?: number;
27
+ }
28
+ /** render-webgl blend modes as Pixi's (premultiplied) blend modes: identical GL blend functions. */
29
+ export declare const PIXI_BLEND: {
30
+ readonly normal: "normal";
31
+ readonly additive: "add";
32
+ readonly multiply: "multiply";
33
+ readonly screen: "screen";
34
+ };
35
+ /**
36
+ * One batch drawn as a Pixi Mesh with OpenBone's vertex-coloured shader. Batches with a dark colour switch to the
37
+ * two-colour shader and fill the `aDark` attribute; the others never upload it.
38
+ */
39
+ export declare class BatchMesh extends Mesh<Geometry, Shader> {
40
+ private plainShader;
41
+ private darkShader;
42
+ /** True while this mesh draws a two-colour (dark) tint batch. */
43
+ twoColor: boolean;
44
+ constructor();
45
+ set(b: Batch, texture: Texture): void;
46
+ }
47
+ /**
48
+ * An OpenBone document as a Pixi v8 display object. Skeleton origin is at the container's position, y down like
49
+ * the rest of Pixi (skeleton units = pixels at scale 1). Draws one Mesh per batch (same batches as render-webgl:
50
+ * one per atlas page / texture and blend mode), clipping masks as stencil masks, text through canvas textures.
51
+ */
52
+ export declare class OpenBone extends Container {
53
+ readonly driver: OpenBoneDriver;
54
+ readonly asset: OpenBoneAsset;
55
+ /** Holds the meshes in skeleton space (y up): scale.y = -1. */
56
+ readonly view: Container<import("pixi.js").ContainerChild>;
57
+ private meshes;
58
+ private runs;
59
+ private text;
60
+ private textTextures;
61
+ private dot;
62
+ private ticker;
63
+ private resolution;
64
+ /** Draw calls (batches) in the last update. */
65
+ drawCalls: number;
66
+ constructor(asset: OpenBoneAsset, driver: OpenBoneDriver, opts?: OpenBoneOptions);
67
+ /** Load a document (URL, bytes or parsed) and create the display object; waits for images and the script sandbox. */
68
+ static from(src: OpenBoneSource | OpenBoneAsset, opts?: OpenBoneOptions & LoadOptions): Promise<OpenBone>;
69
+ private tick;
70
+ get instance(): import("@openbone/runtime").OpenBoneInstance;
71
+ get skeleton(): import("@openbone/runtime").Skeleton;
72
+ get stateMachine(): import("@openbone/runtime").StateMachineInstance | null;
73
+ get speed(): number;
74
+ set speed(v: number);
75
+ /** True while paused (update() keeps drawing but time stands still). */
76
+ paused: boolean;
77
+ /** Pause the animation and its sounds. */
78
+ pause(): void;
79
+ /** Continue after pause(). */
80
+ resume(): void;
81
+ /** Advance by `dt` seconds and rebuild the meshes. */
82
+ update(dt: number): void;
83
+ setInput(name: string, value: InputValue): void;
84
+ getInput(name: string): InputValue | undefined;
85
+ fire(name: string): void;
86
+ setText(slot: string, text: string | null): void;
87
+ setSkin(name: string | null): void;
88
+ play(animation: string, loop?: boolean): void;
89
+ useStateMachine(name?: string): import("@openbone/runtime").StateMachineInstance;
90
+ /** Listen to "event", "stateChange" or "audio"; returns an unsubscribe function. */
91
+ onOpenBone: OpenBoneDriver["on"];
92
+ private textureFor;
93
+ /** Rebuild the meshes from the current pose (call after changing the pose by hand). */
94
+ redraw(): void;
95
+ /** A point in Pixi global (stage) coordinates, e.g. a pointer event's `global`, to skeleton space (y up). */
96
+ toSkeleton(global: {
97
+ x: number;
98
+ y: number;
99
+ }): [number, number];
100
+ /** Skeleton space (y up) to Pixi global (stage) coordinates. */
101
+ fromSkeleton(x: number, y: number): {
102
+ x: number;
103
+ y: number;
104
+ };
105
+ /** The active bounding boxes (skeleton space): `obj.boundingBoxes().containsPoint(...obj.toSkeleton(e.global))`. */
106
+ boundingBoxes(): import("@openbone/runtime").SkeletonBounds;
107
+ /** The artboard rectangle in this container's space (y down). */
108
+ get artboard(): {
109
+ x: number;
110
+ y: number;
111
+ width: number;
112
+ height: number;
113
+ };
114
+ private bindPointer;
115
+ destroy(options?: Parameters<Container["destroy"]>[0]): void;
116
+ }
package/dist/index.js ADDED
@@ -0,0 +1,369 @@
1
+ import { filterParts, premultipliedTextures, textureSamplings } from "@openbone/core";
2
+ import { OpenBoneDriver, TextRasterizer, buildBatches, loadDocument, loadTextures, particleDotCanvas, } from "@openbone/engine-kit";
3
+ import { PARTICLE_DOT_TEXTURE } from "@openbone/runtime";
4
+ import { CanvasSource, Container, Geometry, GlProgram, Graphics, ImageSource, Mesh, Shader, Texture, Ticker, } from "pixi.js";
5
+ /** Load a .obone / .obonb document and its images (atlas pages when packed) as Pixi textures. */
6
+ export async function loadOpenBone(src, opts = {}) {
7
+ const { doc, baseUrl } = await loadDocument(src, opts);
8
+ const images = await loadTextures(doc, baseUrl, { resolveImageUrl: opts.resolveImageUrl });
9
+ const textures = new Map();
10
+ // Premultiplied atlas pages are uploaded as they are; straight-alpha images are premultiplied on upload.
11
+ const pma = premultipliedTextures(doc);
12
+ // Atlas pages sample with the atlas's filter / wrap settings; everything else linear + clamp (Pixi's default).
13
+ const sampling = textureSamplings(doc);
14
+ for (const [id, img] of images)
15
+ textures.set(id, new Texture({ source: new ImageSource({ resource: img, alphaMode: pma.has(id) ? "premultiplied-alpha" : "premultiply-alpha-on-upload", ...pixiSampling(sampling.get(id)) }) }));
16
+ return { doc, baseUrl, textures };
17
+ }
18
+ const PIXI_WRAP = { clamp: "clamp-to-edge", repeat: "repeat", mirroredRepeat: "mirror-repeat" };
19
+ /** Pixi texture style options for an atlas page's sampling (empty = Pixi's defaults). */
20
+ function pixiSampling(s) {
21
+ if (!s)
22
+ return {};
23
+ const { texel, mip } = filterParts(s.min);
24
+ return {
25
+ minFilter: texel,
26
+ magFilter: s.mag,
27
+ addressModeU: PIXI_WRAP[s.wrapX],
28
+ addressModeV: PIXI_WRAP[s.wrapY],
29
+ ...(mip !== "none" ? { autoGenerateMipmaps: true, mipmapFilter: mip } : {}),
30
+ };
31
+ }
32
+ const VERTEX = `
33
+ in vec2 aPosition;
34
+ in vec2 aUV;
35
+ in vec4 aColor;
36
+ out vec2 vUV;
37
+ out vec4 vColor;
38
+ uniform mat3 uProjectionMatrix;
39
+ uniform mat3 uWorldTransformMatrix;
40
+ uniform vec4 uWorldColorAlpha;
41
+ uniform vec2 uResolution;
42
+ uniform mat3 uTransformMatrix;
43
+ uniform vec4 uColor;
44
+ uniform float uRound;
45
+ void main() {
46
+ mat3 mvp = uProjectionMatrix * uWorldTransformMatrix * uTransformMatrix;
47
+ gl_Position = vec4((mvp * vec3(aPosition, 1.0)).xy, 0.0, 1.0);
48
+ vUV = aUV;
49
+ // Straight vertex colour -> premultiplied, times the container's (premultiplied) tint and alpha.
50
+ vColor = vec4(aColor.rgb * aColor.a, aColor.a) * uColor * uWorldColorAlpha;
51
+ }`;
52
+ const FRAGMENT = `
53
+ in vec2 vUV;
54
+ in vec4 vColor;
55
+ uniform sampler2D uTexture;
56
+ out vec4 finalColor;
57
+ void main() {
58
+ finalColor = texture(uTexture, vUV) * vColor;
59
+ }`;
60
+ // Two-colour tint (batches with a dark colour): rgb = dark + (light - dark) × texture rgb, on premultiplied texels.
61
+ // The container's tint colours the dark colour too; its alpha fades both.
62
+ const DARK_VERTEX = `
63
+ in vec2 aPosition;
64
+ in vec2 aUV;
65
+ in vec4 aColor;
66
+ in vec3 aDark;
67
+ out vec2 vUV;
68
+ out vec4 vColor;
69
+ out vec3 vDark;
70
+ uniform mat3 uProjectionMatrix;
71
+ uniform mat3 uWorldTransformMatrix;
72
+ uniform vec4 uWorldColorAlpha;
73
+ uniform vec2 uResolution;
74
+ uniform mat3 uTransformMatrix;
75
+ uniform vec4 uColor;
76
+ uniform float uRound;
77
+ void main() {
78
+ mat3 mvp = uProjectionMatrix * uWorldTransformMatrix * uTransformMatrix;
79
+ gl_Position = vec4((mvp * vec3(aPosition, 1.0)).xy, 0.0, 1.0);
80
+ vUV = aUV;
81
+ vec4 tint = uColor * uWorldColorAlpha;
82
+ vColor = vec4(aColor.rgb * aColor.a, aColor.a) * tint;
83
+ vDark = aDark * (tint.a > 0.0 ? tint.rgb / tint.a : vec3(1.0));
84
+ }`;
85
+ const DARK_FRAGMENT = `
86
+ in vec2 vUV;
87
+ in vec4 vColor;
88
+ in vec3 vDark;
89
+ uniform sampler2D uTexture;
90
+ out vec4 finalColor;
91
+ void main() {
92
+ vec4 t = texture(uTexture, vUV);
93
+ finalColor = vec4(vDark * (t.a - t.rgb) * vColor.a + t.rgb * vColor.rgb, t.a * vColor.a);
94
+ }`;
95
+ /** render-webgl blend modes as Pixi's (premultiplied) blend modes: identical GL blend functions. */
96
+ export const PIXI_BLEND = { normal: "normal", additive: "add", multiply: "multiply", screen: "screen" };
97
+ let program = null;
98
+ const glProgram = () => (program ??= GlProgram.from({ vertex: VERTEX, fragment: FRAGMENT, name: "openbone-mesh" }));
99
+ let darkProgram = null;
100
+ const glDarkProgram = () => (darkProgram ??= GlProgram.from({ vertex: DARK_VERTEX, fragment: DARK_FRAGMENT, name: "openbone-mesh-dark" }));
101
+ /**
102
+ * One batch drawn as a Pixi Mesh with OpenBone's vertex-coloured shader. Batches with a dark colour switch to the
103
+ * two-colour shader and fill the `aDark` attribute; the others never upload it.
104
+ */
105
+ export class BatchMesh extends Mesh {
106
+ plainShader;
107
+ darkShader = null;
108
+ /** True while this mesh draws a two-colour (dark) tint batch. */
109
+ twoColor = false;
110
+ constructor() {
111
+ const geometry = new Geometry({
112
+ attributes: {
113
+ aPosition: { buffer: new Float32Array(8), format: "float32x2" },
114
+ aUV: { buffer: new Float32Array(8), format: "float32x2" },
115
+ aColor: { buffer: new Float32Array(16), format: "float32x4" },
116
+ aDark: { buffer: new Float32Array(12), format: "float32x3" },
117
+ },
118
+ indexBuffer: new Uint16Array(6),
119
+ });
120
+ const shader = new Shader({ glProgram: glProgram(), resources: { uTexture: Texture.WHITE.source } });
121
+ super({ geometry, shader, texture: Texture.WHITE });
122
+ this.plainShader = shader;
123
+ }
124
+ set(b, texture) {
125
+ const g = this.geometry;
126
+ g.attributes.aPosition.buffer.data = b.vertices;
127
+ g.attributes.aUV.buffer.data = b.uvs;
128
+ g.attributes.aColor.buffer.data = b.colors;
129
+ g.indexBuffer.data = b.indices;
130
+ this.twoColor = !!b.dark;
131
+ if (b.dark) {
132
+ g.attributes.aDark.buffer.data = b.dark;
133
+ this.darkShader ??= new Shader({ glProgram: glDarkProgram(), resources: { uTexture: texture.source } });
134
+ }
135
+ const shader = b.dark ? this.darkShader : this.plainShader;
136
+ if (this.shader !== shader)
137
+ this.shader = shader;
138
+ if (this.texture !== texture || shader.resources.uTexture !== texture.source) {
139
+ this.texture = texture;
140
+ shader.resources.uTexture = texture.source;
141
+ }
142
+ this.blendMode = PIXI_BLEND[b.blend] ?? "normal";
143
+ }
144
+ }
145
+ /** A clipping mask's run of batches: drawn inside a Graphics stencil mask of the clip polygon. */
146
+ class ClipRun extends Container {
147
+ maskShape = new Graphics();
148
+ set(clip) {
149
+ const g = this.maskShape;
150
+ g.clear();
151
+ g.poly(Array.from(clip.polygon), true).fill(0xffffff);
152
+ this.mask = g;
153
+ }
154
+ }
155
+ /**
156
+ * An OpenBone document as a Pixi v8 display object. Skeleton origin is at the container's position, y down like
157
+ * the rest of Pixi (skeleton units = pixels at scale 1). Draws one Mesh per batch (same batches as render-webgl:
158
+ * one per atlas page / texture and blend mode), clipping masks as stencil masks, text through canvas textures.
159
+ */
160
+ export class OpenBone extends Container {
161
+ driver;
162
+ asset;
163
+ /** Holds the meshes in skeleton space (y up): scale.y = -1. */
164
+ view = new Container();
165
+ meshes = [];
166
+ runs = [];
167
+ text = new TextRasterizer();
168
+ textTextures = new Map();
169
+ dot = null;
170
+ ticker = null;
171
+ resolution;
172
+ /** Draw calls (batches) in the last update. */
173
+ drawCalls = 0;
174
+ constructor(asset, driver, opts = {}) {
175
+ super();
176
+ this.asset = asset;
177
+ this.driver = driver;
178
+ this.resolution = opts.resolution ?? (typeof devicePixelRatio !== "undefined" ? devicePixelRatio : 1);
179
+ this.view.scale.y = -1;
180
+ this.addChild(this.view);
181
+ if (opts.interactive !== false && asset.doc.stateMachines.length)
182
+ this.bindPointer();
183
+ if (opts.autoUpdate !== false) {
184
+ this.ticker = opts.ticker ?? Ticker.shared;
185
+ this.ticker.add(this.tick, this);
186
+ }
187
+ this.redraw();
188
+ }
189
+ /** Load a document (URL, bytes or parsed) and create the display object; waits for images and the script sandbox. */
190
+ static async from(src, opts = {}) {
191
+ const asset = isAsset(src) ? src : await loadOpenBone(src, opts);
192
+ const driver = await OpenBoneDriver.create(asset.doc, asset.baseUrl, opts);
193
+ return new OpenBone(asset, driver, opts);
194
+ }
195
+ tick(t) {
196
+ this.update(t.deltaMS / 1000);
197
+ }
198
+ get instance() {
199
+ return this.driver.instance;
200
+ }
201
+ get skeleton() {
202
+ return this.driver.skeleton;
203
+ }
204
+ get stateMachine() {
205
+ return this.driver.stateMachine;
206
+ }
207
+ get speed() {
208
+ return this.driver.speed;
209
+ }
210
+ set speed(v) {
211
+ this.driver.speed = v;
212
+ }
213
+ /** True while paused (update() keeps drawing but time stands still). */
214
+ paused = false;
215
+ /** Pause the animation and its sounds. */
216
+ pause() {
217
+ this.paused = true;
218
+ this.driver.pause();
219
+ }
220
+ /** Continue after pause(). */
221
+ resume() {
222
+ this.paused = false;
223
+ this.driver.resume();
224
+ }
225
+ /** Advance by `dt` seconds and rebuild the meshes. */
226
+ update(dt) {
227
+ if (!this.paused)
228
+ this.driver.advance(dt);
229
+ this.redraw();
230
+ }
231
+ setInput(name, value) {
232
+ this.driver.setInput(name, value);
233
+ }
234
+ getInput(name) {
235
+ return this.driver.getInput(name);
236
+ }
237
+ fire(name) {
238
+ this.driver.fire(name);
239
+ }
240
+ setText(slot, text) {
241
+ this.driver.setText(slot, text);
242
+ }
243
+ setSkin(name) {
244
+ this.driver.setSkin(name);
245
+ this.redraw();
246
+ }
247
+ play(animation, loop = true) {
248
+ this.driver.play(animation, loop);
249
+ }
250
+ useStateMachine(name) {
251
+ return this.driver.useStateMachine(name);
252
+ }
253
+ /** Listen to "event", "stateChange" or "audio"; returns an unsubscribe function. */
254
+ onOpenBone = (name, fn) => this.driver.on(name, fn);
255
+ textureFor(b) {
256
+ if (b.text) {
257
+ const wt = this.view.worldTransform;
258
+ const r = this.text.get(b.text.id, b.text.draw, Math.sqrt(Math.abs(wt.a * wt.d - wt.b * wt.c)) * this.resolution);
259
+ if (!r)
260
+ return Texture.EMPTY;
261
+ let e = this.textTextures.get(b.text.id);
262
+ if (!e || e.version !== r.version) {
263
+ e?.tex.destroy(true);
264
+ e = { tex: new Texture({ source: new CanvasSource({ resource: r.canvas }) }), version: r.version };
265
+ this.textTextures.set(b.text.id, e);
266
+ }
267
+ return e.tex;
268
+ }
269
+ if (!b.texture)
270
+ return Texture.WHITE;
271
+ if (b.texture === PARTICLE_DOT_TEXTURE) {
272
+ if (!this.dot) {
273
+ const c = particleDotCanvas();
274
+ this.dot = c ? new Texture({ source: new CanvasSource({ resource: c }) }) : Texture.WHITE;
275
+ }
276
+ return this.dot;
277
+ }
278
+ return this.asset.textures.get(b.texture) ?? Texture.WHITE;
279
+ }
280
+ /** Rebuild the meshes from the current pose (call after changing the pose by hand). */
281
+ redraw() {
282
+ const tex = this.asset.textures;
283
+ const batches = buildBatches(this.driver.instance.drawList(), {
284
+ hasTexture: (id) => id === PARTICLE_DOT_TEXTURE || tex.has(id),
285
+ });
286
+ for (const id of this.text.nextFrame()) {
287
+ this.textTextures.get(id)?.tex.destroy(true);
288
+ this.textTextures.delete(id);
289
+ }
290
+ this.view.removeChildren();
291
+ for (const r of this.runs)
292
+ r.removeChildren();
293
+ let run = null;
294
+ let clip;
295
+ let runCount = 0;
296
+ batches.forEach((b, i) => {
297
+ const mesh = (this.meshes[i] ??= new BatchMesh());
298
+ mesh.set(b, this.textureFor(b));
299
+ if (b.clip !== clip) {
300
+ clip = b.clip;
301
+ run = null;
302
+ if (clip) {
303
+ run = this.runs[runCount] ??= new ClipRun();
304
+ runCount++;
305
+ run.set(clip);
306
+ this.view.addChild(run.maskShape, run);
307
+ }
308
+ }
309
+ (run ?? this.view).addChild(mesh);
310
+ });
311
+ for (let i = batches.length; i < this.meshes.length; i++)
312
+ this.meshes[i].destroy({ children: true });
313
+ this.meshes.length = batches.length;
314
+ for (let i = runCount; i < this.runs.length; i++) {
315
+ this.runs[i].maskShape.destroy();
316
+ this.runs[i].destroy();
317
+ }
318
+ this.runs.length = runCount;
319
+ this.drawCalls = batches.length;
320
+ }
321
+ /** A point in Pixi global (stage) coordinates, e.g. a pointer event's `global`, to skeleton space (y up). */
322
+ toSkeleton(global) {
323
+ const p = this.view.toLocal(global);
324
+ return [p.x, p.y];
325
+ }
326
+ /** Skeleton space (y up) to Pixi global (stage) coordinates. */
327
+ fromSkeleton(x, y) {
328
+ const p = this.view.toGlobal({ x, y });
329
+ return { x: p.x, y: p.y };
330
+ }
331
+ /** The active bounding boxes (skeleton space): `obj.boundingBoxes().containsPoint(...obj.toSkeleton(e.global))`. */
332
+ boundingBoxes() {
333
+ return this.driver.boundingBoxes();
334
+ }
335
+ /** The artboard rectangle in this container's space (y down). */
336
+ get artboard() {
337
+ const d = this.asset.doc;
338
+ return { x: -d.originX, y: -d.originY, width: d.width, height: d.height };
339
+ }
340
+ bindPointer() {
341
+ this.eventMode = "static";
342
+ const a = this.artboard;
343
+ this.hitArea = { contains: (x, y) => x >= a.x && y >= a.y && x <= a.x + a.width && y <= a.y + a.height };
344
+ const send = (type) => (e) => {
345
+ const p = e.getLocalPosition(this.view);
346
+ const inside = this.hitArea.contains(p.x, -p.y);
347
+ if (type === "move" && !inside)
348
+ return this.driver.pointerLeave();
349
+ this.driver.pointer(type, p.x, p.y);
350
+ };
351
+ this.on("pointerdown", send("down"));
352
+ this.on("pointerup", send("up"));
353
+ this.on("pointerupoutside", send("up"));
354
+ this.on("globalpointermove", send("move"));
355
+ }
356
+ destroy(options) {
357
+ this.ticker?.remove(this.tick, this);
358
+ this.driver.dispose();
359
+ for (const e of this.textTextures.values())
360
+ e.tex.destroy(true);
361
+ this.dot?.destroy(true);
362
+ for (const r of this.runs)
363
+ r.maskShape.destroy();
364
+ super.destroy(options ?? { children: true });
365
+ }
366
+ }
367
+ function isAsset(x) {
368
+ return !!x && typeof x === "object" && "textures" in x && "doc" in x;
369
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@openbone/pixi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "OpenBone runtime for PixiJS v8: a Container that plays OpenBone documents",
5
+ "keywords": [
6
+ "openbone",
7
+ "skeletal-animation",
8
+ "2d-animation",
9
+ "animation",
10
+ "pixi",
11
+ "pixijs"
12
+ ],
13
+ "homepage": "https://github.com/UXCentury/open-bone/tree/main/packages/pixi#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/UXCentury/open-bone/issues"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/UXCentury/open-bone.git",
20
+ "directory": "packages/pixi"
21
+ },
22
+ "license": "MIT",
23
+ "type": "module",
24
+ "sideEffects": false,
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "default": "./dist/index.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist"
33
+ ],
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "dependencies": {
38
+ "@openbone/core": "0.3.0",
39
+ "@openbone/engine-kit": "0.3.0",
40
+ "@openbone/runtime": "0.3.0"
41
+ },
42
+ "peerDependencies": {
43
+ "pixi.js": "^8.0.0"
44
+ },
45
+ "devDependencies": {
46
+ "esbuild": "^0.28.2",
47
+ "pixi.js": "^8.22.0",
48
+ "@openbone/render-webgl": "0.3.0"
49
+ },
50
+ "scripts": {
51
+ "build": "node ../build.mjs"
52
+ },
53
+ "main": "./dist/index.js",
54
+ "types": "./dist/index.d.ts"
6
55
  }