@openbone/canvaskit 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,161 @@
1
- # Temporary Holding Version
1
+ # @openbone/canvaskit
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 CanvasKit (Skia compiled to WebAssembly): a renderer and a player.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@openbone/canvaskit)](https://www.npmjs.com/package/@openbone/canvaskit)
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 draws OpenBone skeletons on any CanvasKit
10
+ canvas: a browser WebGL or software surface, or a headless surface in Node. `CanvasKitPlayer` adds a render loop,
11
+ fit, pointer input, state machines, events, skins, scripts and sound for an HTML canvas. Playback comes from
12
+ [`@openbone/engine-kit`](https://www.npmjs.com/package/@openbone/engine-kit); drawing follows the batches of the
13
+ reference renderer, [`@openbone/render-webgl`](https://www.npmjs.com/package/@openbone/render-webgl).
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ npm install @openbone/canvaskit canvaskit-wasm
19
+ ```
20
+
21
+ `canvaskit-wasm` (BSD-3-Clause) is a peer dependency (`>=0.39.0`). Its `canvaskit.wasm` file must be reachable by
22
+ `CanvasKitInit`'s `locateFile`. For the Node example, also install `@openbone/runtime`.
23
+
24
+ ## Quick start: in a page
25
+
26
+ ```ts
27
+ import CanvasKitInit from "canvaskit-wasm";
28
+ import { CanvasKitPlayer } from "@openbone/canvaskit";
29
+
30
+ const ck = await CanvasKitInit({ locateFile: (file) => `/canvaskit/${file}` }); // where you serve canvaskit.wasm
31
+ const canvas = document.querySelector<HTMLCanvasElement>("#stage")!; // give it a CSS size
32
+
33
+ const player = await CanvasKitPlayer.create(ck, canvas, "/knight.obone", { stateMachine: "knight", fit: "contain" });
34
+ player.setInput("walk", true);
35
+ player.on("stateChange", (e) => console.log(e.layer, e.from, "->", e.to));
36
+ new ResizeObserver(() => player.resize()).observe(canvas);
37
+ ```
38
+
39
+ `knight.obone` is in the repository's `examples/` folder. The player draws at the device pixel ratio, fits the
40
+ artboard into the canvas and sends pointer events over it to the state machine.
41
+
42
+ ## Quick start: a PNG in Node
43
+
44
+ ```ts
45
+ import { readFile, writeFile } from "node:fs/promises";
46
+ import { pathToFileURL } from "node:url";
47
+ import CanvasKitInit from "canvaskit-wasm";
48
+ import { CanvasKitRenderer, loadOpenBone } from "@openbone/canvaskit";
49
+ import { OpenBoneInstance } from "@openbone/runtime";
50
+
51
+ const ck = await CanvasKitInit();
52
+
53
+ // Node's fetch has no file: URLs, so hand loadOpenBone a fetch that reads files.
54
+ const readFetch = (async (url: string | URL | Request) => new Response(await readFile(new URL(String(url))))) as typeof fetch;
55
+ const file = pathToFileURL(process.argv[2] ?? "knight.obone");
56
+ const asset = await loadOpenBone(ck, file, { fetch: readFetch }); // images resolve next to the file
57
+
58
+ const knight = new OpenBoneInstance(asset.doc);
59
+ knight.play("idle");
60
+ knight.advance(0.5);
61
+
62
+ const scale = 0.5;
63
+ const surface = ck.MakeSurface(asset.doc.width * scale, asset.doc.height * scale)!;
64
+ const renderer = new CanvasKitRenderer(ck, (id) => asset.images.get(id));
65
+ const canvas = surface.getCanvas();
66
+ canvas.clear(ck.TRANSPARENT);
67
+ renderer.render(canvas, knight, { x: 0, y: 0, zoom: scale });
68
+ surface.flush();
69
+ await writeFile("knight-ck.png", surface.makeImageSnapshot().encodeToBytes()!);
70
+ ```
71
+
72
+ Over HTTP(S) no custom `fetch` is needed: `loadOpenBone(ck, "https://cdn.example.com/knight.obone")`.
73
+
74
+ ## API
75
+
76
+ | Export | |
77
+ |---|---|
78
+ | `CanvasKitPlayer` | `await CanvasKitPlayer.create(ck, canvas, src, options)` plays a document on an HTML canvas. |
79
+ | `CanvasKitRenderer` | `new CanvasKitRenderer(ck, images, { fonts? })`; `render(canvas, skeletonOrInstance, view?)` draws one frame on any CanvasKit `Canvas`. |
80
+ | `loadOpenBone(ck, src, options)` | Loads a document and decodes its images (atlas pages when packed) with Skia. Works in browsers and Node. |
81
+ | `OpenBoneAsset` | `{ doc, baseUrl, images }` (CanvasKit images by image or atlas page id). Shareable by many players. |
82
+ | `PlayerOptions`, `CanvasKitRendererOptions`, `LoadOptions`, `View`, `DriverOptions`, `InputValue`, `OpenBoneSource` | Option and value types. |
83
+
84
+ `src` is a URL, bytes (`ArrayBuffer` or `Uint8Array` of a `.obone` or `.obonb` file), a parsed document or, for
85
+ `CanvasKitPlayer.create`, an `OpenBoneAsset`.
86
+
87
+ ### `CanvasKitRenderer`
88
+
89
+ - `render(canvas, target, view)`: `view` is `{ x, y, zoom }` in canvas pixels (the artboard's top-left lands at
90
+ `x, y`). The canvas's current matrix applies on top, so you can also position the skeleton with `canvas.concat`.
91
+ It does not clear the canvas.
92
+ - `CanvasKitRenderer.matrix(doc, view)`: the skeleton-to-canvas matrix for a view.
93
+ - `drawCalls`: `drawVertices` calls in the last render. `dispose()` frees shaders, paints and cached images.
94
+ - `fonts(family, weight)`: return a `Typeface` to draw text attachments natively with Skia. Without it, text is
95
+ rasterised with a 2D canvas where one exists (so in Node, text is skipped unless you pass `fonts`).
96
+
97
+ ### `CanvasKitPlayer` options
98
+
99
+ | Option | Default | |
100
+ |---|---|---|
101
+ | `stateMachine` / `animation` / `loop` | first state machine, else first animation | What to run. |
102
+ | `skin` | default skin | Skin (outfit) by name or id. |
103
+ | `scripts` | `"quickjs"` when the document has scripts | `"none"` or your own `ScriptHost`. |
104
+ | `audio` | `true` | `false` or `"muted"`. Sound unlocks on the first click or key press. |
105
+ | `fit` | `contain` | `contain`, `cover` or `none`. |
106
+ | `background` | the document's | A CSS colour; `null` for transparent. |
107
+ | `surface` | `webgl` | `webgl` (falls back to software when WebGL is unavailable) or `software`. |
108
+ | `autoplay` | `true` | Start the render loop right away. |
109
+ | `fonts` | | As for the renderer. |
110
+ | `baseUrl`, `fetch`, `resolveImageUrl` | | Loading, as in `loadOpenBone`. |
111
+ | `audioContext`, `audioBaseUrl`, `resolveAudioUrl`, `unlockTarget`, `onEvent`, `onStateChange` | | As in engine-kit. |
112
+
113
+ ### `CanvasKitPlayer` methods
114
+
115
+ | Member | |
116
+ |---|---|
117
+ | `setInput(name, value)`, `getInput(name)`, `fire(name)` | State machine inputs and triggers. |
118
+ | `playAnimation(name, loop?)` | Play an animation instead of the state machine. |
119
+ | `setSkin(name)`, `setText(slot, text)` | Outfit, and text for a slot's text attachment (`null` restores it). |
120
+ | `play()`, `pause()`, `playing` | The render loop; pausing also pauses sounds. |
121
+ | `resize()` | Call after the canvas changed size (the player does not observe it). |
122
+ | `draw()` | Draw the current pose once. |
123
+ | `boundingBoxes()`, `clientToSkeleton(clientX, clientY)` | Bounding-box queries in skeleton space (y up), and page coordinates to skeleton space through the fit: `player.boundingBoxes().containsPoint(...player.clientToSkeleton(e.clientX, e.clientY))`. |
124
+ | `on(name, fn)` | Listen to `"event"`, `"stateChange"` or `"audio"`. Returns an unsubscribe function. |
125
+ | `driver`, `instance`, `stateMachine`, `renderer`, `asset`, `ck`, `canvas` | Lower-level access (playback speed is `driver.speed`). |
126
+ | `dispose()` | Stops the loop and sounds, removes pointer listeners and frees the surface and renderer. |
127
+
128
+ ## How it draws
129
+
130
+ One `drawVertices` per render-webgl batch: positions, texture coordinates (scaled to the image) and per-vertex
131
+ colours modulating the image shader, so meshes, weights, tints, sequences and particles match the reference renderer.
132
+
133
+ - **Two-colour tint**: slots with a `dark` colour draw through a colour-matrix filter
134
+ (`rgb = dark + (light − dark) × rgb`), one `drawVertices` per run of items with the same light and dark colour.
135
+ Batches without one are untouched.
136
+ - **Blend modes** map to Skia's `SrcOver`, `Plus`, `Multiply` and `Screen`.
137
+ - **Clipping** masks are anti-aliased clip paths.
138
+ - **Premultiplied alpha**: premultiplied atlas pages are labelled as premultiplied images, Skia's own format, so they
139
+ blend correctly without conversion.
140
+ - **Particles** use the built-in soft sprite.
141
+
142
+ ## Demo
143
+
144
+ From a checkout: `pnpm --filter @openbone/examples engines`, then open http://localhost:5190/canvaskit/
145
+ (`?example=campfire`, `rocket`, `crash`…).
146
+
147
+ ## Documentation
148
+
149
+ - [Architecture](https://github.com/UXCentury/open-bone/blob/main/docs/architecture.md): runtime model and rendering
150
+ - [File format](https://github.com/UXCentury/open-bone/blob/main/docs/format.md)
151
+ - [Demo source](https://github.com/UXCentury/open-bone/blob/main/examples/engines/canvaskit/main.ts)
152
+ - Related packages: [`@openbone/engine-kit`](https://www.npmjs.com/package/@openbone/engine-kit),
153
+ [`@openbone/pixi`](https://www.npmjs.com/package/@openbone/pixi),
154
+ [`@openbone/phaser`](https://www.npmjs.com/package/@openbone/phaser),
155
+ [`@openbone/three`](https://www.npmjs.com/package/@openbone/three),
156
+ [`@openbone/render-canvas`](https://www.npmjs.com/package/@openbone/render-canvas)
157
+
158
+ ## License
159
+
160
+ MIT, © UX Century and OpenBone contributors. CanvasKit is © Google, BSD-3-Clause. See
161
+ [LICENSE](https://github.com/UXCentury/open-bone/blob/main/LICENSE).
@@ -0,0 +1,121 @@
1
+ import { type OpenBoneDocument } from "@openbone/core";
2
+ import { type DriverOptions, type FetchOptions, type InputValue, OpenBoneDriver, type OpenBoneSource } from "@openbone/engine-kit";
3
+ import { type OpenBoneInstance, type Skeleton } from "@openbone/runtime";
4
+ import type { Canvas, CanvasKit, Image, Typeface } from "canvaskit-wasm";
5
+ export type { DriverOptions, InputValue, OpenBoneSource } from "@openbone/engine-kit";
6
+ /** A loaded document and its images decoded as CanvasKit images (atlas pages when packed). */
7
+ export interface OpenBoneAsset {
8
+ doc: OpenBoneDocument;
9
+ baseUrl: string;
10
+ images: Map<string, Image>;
11
+ }
12
+ export interface LoadOptions extends FetchOptions {
13
+ resolveImageUrl?: (src: string) => string;
14
+ }
15
+ /** Load a .obone / .obonb document and decode its images with CanvasKit (works in browsers and Node). */
16
+ export declare function loadOpenBone(ck: CanvasKit, src: OpenBoneSource, opts?: LoadOptions): Promise<OpenBoneAsset>;
17
+ export interface CanvasKitRendererOptions {
18
+ /**
19
+ * Fonts for text attachments, drawn natively by Skia: return a typeface for a CSS family and weight. Without it
20
+ * (or when it returns null), text is rasterised with a 2D canvas like the other renderers, where one exists.
21
+ */
22
+ fonts?: (family: string, weight: number) => Typeface | null | undefined;
23
+ }
24
+ export interface View {
25
+ x: number;
26
+ y: number;
27
+ zoom: number;
28
+ }
29
+ /**
30
+ * Draws OpenBone skeletons on a CanvasKit (Skia) canvas, in render-webgl's batches: one `drawVertices` per
31
+ * texture / blend mode run (vertex colours modulate the image shader), clipping masks as clip paths.
32
+ */
33
+ export declare class CanvasKitRenderer {
34
+ ck: CanvasKit;
35
+ images: (id: string) => Image | null | undefined;
36
+ private opts;
37
+ private paint;
38
+ private shaders;
39
+ private dot;
40
+ private text;
41
+ private textImages;
42
+ private fontCache;
43
+ private blend;
44
+ /** drawVertices calls in the last render. */
45
+ drawCalls: number;
46
+ constructor(ck: CanvasKit, images: (id: string) => Image | null | undefined, opts?: CanvasKitRendererOptions);
47
+ private image;
48
+ /** Atlas page sampling (filter / wrap) of the current document, and of the batch being drawn. */
49
+ private sampling;
50
+ private samplingDoc;
51
+ private curSampling;
52
+ private sampledShaders;
53
+ private shader;
54
+ /** Skeleton (y up) → canvas pixels for a view (artboard pan/zoom, like render-webgl's `view`). */
55
+ static matrix(doc: OpenBoneDocument, view?: View): number[];
56
+ /**
57
+ * Draw a skeleton (or an instance's skeleton). `view` maps the artboard onto the canvas; the canvas's current
58
+ * matrix applies on top, so you can also position it yourself with `view` left at its default.
59
+ */
60
+ render(canvas: Canvas, target: Skeleton | OpenBoneInstance, view?: View): void;
61
+ /**
62
+ * One batch. With a two-colour tint, runs of items that share a light and dark colour each draw as their own
63
+ * call through a colour-matrix filter (Skia has no second vertex colour); plain items in it keep their vertex
64
+ * colours. Batches without a dark colour are a single drawVertices, as before.
65
+ */
66
+ private drawBatch;
67
+ private drawGeometry;
68
+ private font;
69
+ /** Text with Skia's own font rendering (when `fonts` gives a typeface). */
70
+ private drawNativeText;
71
+ dispose(): void;
72
+ }
73
+ export interface PlayerOptions extends DriverOptions, LoadOptions, CanvasKitRendererOptions {
74
+ /** How the artboard fits the canvas (default "contain"). */
75
+ fit?: "contain" | "cover" | "none";
76
+ /** Background colour (CSS); default the document's, null for transparent. */
77
+ background?: string | null;
78
+ /** Start playing right away (default true). */
79
+ autoplay?: boolean;
80
+ /** "webgl" (default, falls back to software) or "software". */
81
+ surface?: "webgl" | "software";
82
+ }
83
+ /** Plays a document on an HTML canvas with CanvasKit: render loop, fit, pointer input to the state machine. */
84
+ export declare class CanvasKitPlayer {
85
+ readonly ck: CanvasKit;
86
+ readonly canvas: HTMLCanvasElement;
87
+ readonly asset: OpenBoneAsset;
88
+ readonly driver: OpenBoneDriver;
89
+ private opts;
90
+ readonly renderer: CanvasKitRenderer;
91
+ private surface;
92
+ private raf;
93
+ private last;
94
+ private view;
95
+ private unbind;
96
+ playing: boolean;
97
+ private constructor();
98
+ static create(ck: CanvasKit, canvas: HTMLCanvasElement, src: OpenBoneSource | OpenBoneAsset, opts?: PlayerOptions): Promise<CanvasKitPlayer>;
99
+ private makeSurface;
100
+ /** Call after the canvas changed size. */
101
+ resize(): void;
102
+ /** Page (client) coordinates, e.g. a pointer event's clientX/clientY, to skeleton space (y up), through the current fit. */
103
+ clientToSkeleton(clientX: number, clientY: number): [number, number];
104
+ /** The active bounding boxes (skeleton space): `player.boundingBoxes().containsPoint(...player.clientToSkeleton(e.clientX, e.clientY))`. */
105
+ boundingBoxes(): import("@openbone/runtime").SkeletonBounds;
106
+ private bindPointer;
107
+ draw(): void;
108
+ play(): void;
109
+ pause(): void;
110
+ get instance(): OpenBoneInstance;
111
+ get stateMachine(): import("@openbone/runtime").StateMachineInstance | null;
112
+ setInput(name: string, value: InputValue): void;
113
+ getInput(name: string): InputValue | undefined;
114
+ fire(name: string): void;
115
+ setText(slot: string, text: string | null): void;
116
+ setSkin(name: string | null): void;
117
+ playAnimation(name: string, loop?: boolean): void;
118
+ /** Listen to "event", "stateChange" or "audio"; returns an unsubscribe function. */
119
+ on: OpenBoneDriver["on"];
120
+ dispose(): void;
121
+ }
package/dist/index.js ADDED
@@ -0,0 +1,420 @@
1
+ import { filterParts, premultipliedTextures, textureSamplings } from "@openbone/core";
2
+ import { OpenBoneDriver, TextRasterizer, buildBatches, loadDocument, loadTextures, particleDotPixels, tintMatrix, tintRuns, } from "@openbone/engine-kit";
3
+ import { PARTICLE_DOT_SIZE, PARTICLE_DOT_TEXTURE, drawTextBox } from "@openbone/runtime";
4
+ /** Load a .obone / .obonb document and decode its images with CanvasKit (works in browsers and Node). */
5
+ export async function loadOpenBone(ck, src, opts = {}) {
6
+ const { doc, baseUrl } = await loadDocument(src, opts);
7
+ const fetchFn = opts.fetch ?? fetch;
8
+ const pma = premultipliedTextures(doc);
9
+ const images = await loadTextures(doc, baseUrl, {
10
+ resolveImageUrl: opts.resolveImageUrl,
11
+ load: async (url, req) => {
12
+ try {
13
+ const res = await fetchFn(url);
14
+ if (!res.ok)
15
+ return null;
16
+ const img = ck.MakeImageFromEncoded(new Uint8Array(await res.arrayBuffer()));
17
+ if (!img || !pma.has(req.id))
18
+ return img;
19
+ // A premultiplied atlas page: Skia decodes PNGs as straight alpha, so take its bytes as they are in the
20
+ // file and label them premultiplied (Skia's own format), which draws them with the matching blend.
21
+ const info = { width: img.width(), height: img.height(), colorType: ck.ColorType.RGBA_8888, colorSpace: ck.ColorSpace.SRGB };
22
+ const px = img.readPixels(0, 0, { ...info, alphaType: ck.AlphaType.Unpremul });
23
+ img.delete();
24
+ return px ? ck.MakeImage({ ...info, alphaType: ck.AlphaType.Premul }, px, info.width * 4) : null;
25
+ }
26
+ catch {
27
+ return null;
28
+ }
29
+ },
30
+ });
31
+ return { doc, baseUrl, images };
32
+ }
33
+ /**
34
+ * Draws OpenBone skeletons on a CanvasKit (Skia) canvas, in render-webgl's batches: one `drawVertices` per
35
+ * texture / blend mode run (vertex colours modulate the image shader), clipping masks as clip paths.
36
+ */
37
+ export class CanvasKitRenderer {
38
+ ck;
39
+ images;
40
+ opts;
41
+ paint;
42
+ shaders = new Map();
43
+ dot = null;
44
+ text = new TextRasterizer();
45
+ textImages = new Map();
46
+ fontCache = new Map();
47
+ blend;
48
+ /** drawVertices calls in the last render. */
49
+ drawCalls = 0;
50
+ constructor(ck, images, opts = {}) {
51
+ this.ck = ck;
52
+ this.images = images;
53
+ this.opts = opts;
54
+ this.paint = new ck.Paint();
55
+ this.paint.setAntiAlias(true);
56
+ // Untextured geometry without vertex colours (two-colour tint runs) draws in the paint colour.
57
+ this.paint.setColor(ck.WHITE);
58
+ this.blend = { normal: ck.BlendMode.SrcOver, additive: ck.BlendMode.Plus, multiply: ck.BlendMode.Multiply, screen: ck.BlendMode.Screen };
59
+ }
60
+ image(id) {
61
+ if (id === PARTICLE_DOT_TEXTURE) {
62
+ const ck = this.ck;
63
+ this.dot ??= ck.MakeImage({ width: PARTICLE_DOT_SIZE, height: PARTICLE_DOT_SIZE, alphaType: ck.AlphaType.Premul, colorType: ck.ColorType.RGBA_8888, colorSpace: ck.ColorSpace.SRGB }, particleDotPixels(true), PARTICLE_DOT_SIZE * 4);
64
+ return this.dot;
65
+ }
66
+ return this.images(id) ?? null;
67
+ }
68
+ /** Atlas page sampling (filter / wrap) of the current document, and of the batch being drawn. */
69
+ sampling = new Map();
70
+ samplingDoc = null;
71
+ curSampling;
72
+ sampledShaders = new Map();
73
+ shader(img) {
74
+ const ck = this.ck;
75
+ const sm = this.curSampling;
76
+ if (sm) {
77
+ // Skia has one filter per shader: nearest when the atlas asks for nearest magnification, else the min filter's texel filter.
78
+ const key = `${sm.min},${sm.mag},${sm.wrapX},${sm.wrapY}`;
79
+ const hit = this.sampledShaders.get(img);
80
+ if (hit?.key === key)
81
+ return hit.shader;
82
+ hit?.shader.delete();
83
+ const { texel, mip } = filterParts(sm.min);
84
+ const tile = (w) => (w === "repeat" ? ck.TileMode.Repeat : w === "mirroredRepeat" ? ck.TileMode.Mirror : ck.TileMode.Clamp);
85
+ const filter = sm.mag === "nearest" || texel === "nearest" ? ck.FilterMode.Nearest : ck.FilterMode.Linear;
86
+ const mipmap = mip === "linear" ? ck.MipmapMode.Linear : mip === "nearest" ? ck.MipmapMode.Nearest : ck.MipmapMode.None;
87
+ const shader = img.makeShaderOptions(tile(sm.wrapX), tile(sm.wrapY), filter, mipmap);
88
+ this.sampledShaders.set(img, { key, shader });
89
+ return shader;
90
+ }
91
+ let s = this.shaders.get(img);
92
+ if (!s) {
93
+ s = img.makeShaderOptions(ck.TileMode.Clamp, ck.TileMode.Clamp, ck.FilterMode.Linear, ck.MipmapMode.None);
94
+ this.shaders.set(img, s);
95
+ }
96
+ return s;
97
+ }
98
+ /** Skeleton (y up) → canvas pixels for a view (artboard pan/zoom, like render-webgl's `view`). */
99
+ static matrix(doc, view = { x: 0, y: 0, zoom: 1 }) {
100
+ const z = view.zoom;
101
+ return [z, 0, view.x + doc.originX * z, 0, -z, view.y + doc.originY * z, 0, 0, 1];
102
+ }
103
+ /**
104
+ * Draw a skeleton (or an instance's skeleton). `view` maps the artboard onto the canvas; the canvas's current
105
+ * matrix applies on top, so you can also position it yourself with `view` left at its default.
106
+ */
107
+ render(canvas, target, view = { x: 0, y: 0, zoom: 1 }) {
108
+ const sk = "skeleton" in target ? target.skeleton : target;
109
+ const ck = this.ck;
110
+ canvas.save();
111
+ canvas.concat(CanvasKitRenderer.matrix(sk.doc, view));
112
+ // Device pixels per skeleton unit (view and the canvas's own matrix), for text rasters.
113
+ const zoom = Math.sqrt(Math.abs(determinant(canvas.getTotalMatrix())));
114
+ if (this.samplingDoc !== sk.doc) {
115
+ this.samplingDoc = sk.doc;
116
+ this.sampling = textureSamplings(sk.doc);
117
+ }
118
+ const batches = buildBatches(sk.drawList(), { hasTexture: (id) => !!this.image(id) });
119
+ for (const id of this.text.nextFrame()) {
120
+ this.textImages.get(id)?.img.delete();
121
+ this.textImages.delete(id);
122
+ }
123
+ let clip;
124
+ this.drawCalls = 0;
125
+ for (const b of batches) {
126
+ if (b.clip !== clip) {
127
+ if (clip)
128
+ canvas.restore();
129
+ clip = b.clip;
130
+ if (clip) {
131
+ canvas.save();
132
+ const path = new ck.Path();
133
+ path.addPoly(clip.polygon, true);
134
+ canvas.clipPath(path, ck.ClipOp.Intersect, true);
135
+ path.delete();
136
+ }
137
+ }
138
+ this.paint.setBlendMode(this.blend[b.blend] ?? ck.BlendMode.SrcOver);
139
+ if (b.text) {
140
+ if (this.drawNativeText(canvas, b.text.draw, b.text.item.color))
141
+ continue;
142
+ const r = this.text.get(b.text.id, b.text.draw, zoom);
143
+ if (!r || typeof ck.MakeImageFromCanvasImageSource !== "function")
144
+ continue;
145
+ let e = this.textImages.get(b.text.id);
146
+ if (!e || e.version !== r.version) {
147
+ e?.img.delete();
148
+ e = { img: ck.MakeImageFromCanvasImageSource(r.canvas), version: r.version };
149
+ this.textImages.set(b.text.id, e);
150
+ }
151
+ this.curSampling = undefined;
152
+ this.drawBatch(canvas, b, e.img);
153
+ continue;
154
+ }
155
+ this.curSampling = b.texture ? this.sampling.get(b.texture) : undefined;
156
+ this.drawBatch(canvas, b, b.texture ? this.image(b.texture) : null);
157
+ }
158
+ if (clip)
159
+ canvas.restore();
160
+ canvas.restore();
161
+ }
162
+ /**
163
+ * One batch. With a two-colour tint, runs of items that share a light and dark colour each draw as their own
164
+ * call through a colour-matrix filter (Skia has no second vertex colour); plain items in it keep their vertex
165
+ * colours. Batches without a dark colour are a single drawVertices, as before.
166
+ */
167
+ drawBatch(canvas, b, img) {
168
+ if (!b.dark)
169
+ return this.drawGeometry(canvas, b.vertices, b.uvs, b.colors, b.indices, img, null);
170
+ for (const r of tintRuns(b))
171
+ this.drawGeometry(canvas, r.vertices, r.uvs, r.colors, r.indices, img, r.tint);
172
+ }
173
+ drawGeometry(canvas, vertices, uvs, colors, indices, img, tint) {
174
+ const ck = this.ck;
175
+ let texs = null;
176
+ if (img) {
177
+ const w = img.width();
178
+ const h = img.height();
179
+ texs = new Float32Array(uvs.length);
180
+ for (let i = 0; i < texs.length; i += 2) {
181
+ texs[i] = uvs[i] * w;
182
+ texs[i + 1] = uvs[i + 1] * h;
183
+ }
184
+ }
185
+ // A tinted run has no vertex colours: the filter maps the image's (straight) colour, rgb = dark + (light -
186
+ // dark) × rgb, alpha × light alpha, which is render-webgl's two-colour shader.
187
+ const verts = ck.MakeVertices(ck.VertexMode.Triangles, vertices, texs, tint ? null : colors, Array.from(indices), true);
188
+ const filter = tint ? ck.ColorFilter.MakeMatrix(tintMatrix(tint.light, tint.dark)) : null;
189
+ this.paint.setShader(img ? this.shader(img) : null);
190
+ this.paint.setColorFilter(filter);
191
+ // Modulate: image × vertex colour (straight colours, Skia premultiplies them), like render-webgl's shader.
192
+ canvas.drawVertices(verts, ck.BlendMode.Modulate, this.paint);
193
+ if (filter) {
194
+ this.paint.setColorFilter(null);
195
+ filter.delete();
196
+ }
197
+ verts.delete();
198
+ this.drawCalls++;
199
+ }
200
+ font(t) {
201
+ if (!this.opts.fonts)
202
+ return null;
203
+ const key = `${t.font}|${t.weight}|${t.size}`;
204
+ if (!this.fontCache.has(key)) {
205
+ const tf = this.opts.fonts(t.font, t.weight);
206
+ this.fontCache.set(key, tf ? new this.ck.Font(tf, t.size) : null);
207
+ }
208
+ return this.fontCache.get(key) ?? null;
209
+ }
210
+ /** Text with Skia's own font rendering (when `fonts` gives a typeface). */
211
+ drawNativeText(canvas, t, tint) {
212
+ const font = this.font(t);
213
+ if (!font)
214
+ return false;
215
+ const ck = this.ck;
216
+ const m = t.matrix;
217
+ canvas.save();
218
+ // Box frame (y up) → y down, as drawTextBox expects.
219
+ canvas.concat([m.a, m.b, m.x, m.c, m.d, m.y, 0, 0, 1]);
220
+ canvas.scale(1, -1);
221
+ const paint = this.paint.copy();
222
+ paint.setShader(null);
223
+ const metrics = font.getMetrics();
224
+ const ctx = {
225
+ font: "",
226
+ textAlign: "center",
227
+ textBaseline: "middle",
228
+ fillStyle: "",
229
+ strokeStyle: "",
230
+ lineWidth: 1,
231
+ lineJoin: "round",
232
+ fillText: (s, x, y) => draw(s, x, y, false),
233
+ strokeText: (s, x, y) => draw(s, x, y, true),
234
+ };
235
+ const draw = (s, x, y, stroke) => {
236
+ const widths = font.getGlyphWidths(font.getGlyphIDs(s));
237
+ const w = widths.reduce((a, b) => a + b, 0);
238
+ const dx = ctx.textAlign === "center" ? -w / 2 : ctx.textAlign === "right" || ctx.textAlign === "end" ? -w : 0;
239
+ paint.setColor(ck.parseColorString(String(stroke ? ctx.strokeStyle : ctx.fillStyle)));
240
+ paint.setStyle(stroke ? ck.PaintStyle.Stroke : ck.PaintStyle.Fill);
241
+ paint.setStrokeWidth(ctx.lineWidth);
242
+ paint.setStrokeJoin(ck.StrokeJoin.Round);
243
+ // "middle" baseline: centre the ascent..descent box on y.
244
+ canvas.drawText(s, x + dx, y - (metrics.ascent + metrics.descent) / 2, paint, font);
245
+ };
246
+ drawTextBox(ctx, t, tint);
247
+ paint.delete();
248
+ canvas.restore();
249
+ return true;
250
+ }
251
+ dispose() {
252
+ for (const s of this.shaders.values())
253
+ s.delete();
254
+ this.shaders.clear();
255
+ for (const s of this.sampledShaders.values())
256
+ s.shader.delete();
257
+ this.sampledShaders.clear();
258
+ for (const e of this.textImages.values())
259
+ e.img.delete();
260
+ for (const f of this.fontCache.values())
261
+ f?.delete();
262
+ this.dot?.delete();
263
+ this.paint.delete();
264
+ }
265
+ }
266
+ /** Determinant of the 2×2 part of a row-major 3×3 matrix. */
267
+ const determinant = (m) => m[0] * m[4] - m[1] * m[3];
268
+ /** Plays a document on an HTML canvas with CanvasKit: render loop, fit, pointer input to the state machine. */
269
+ export class CanvasKitPlayer {
270
+ ck;
271
+ canvas;
272
+ asset;
273
+ driver;
274
+ opts;
275
+ renderer;
276
+ surface;
277
+ raf = 0;
278
+ last = 0;
279
+ view = { x: 0, y: 0, zoom: 1 };
280
+ unbind;
281
+ playing = false;
282
+ constructor(ck, canvas, asset, driver, opts) {
283
+ this.ck = ck;
284
+ this.canvas = canvas;
285
+ this.asset = asset;
286
+ this.driver = driver;
287
+ this.opts = opts;
288
+ this.renderer = new CanvasKitRenderer(ck, (id) => asset.images.get(id), opts);
289
+ this.surface = this.makeSurface();
290
+ this.unbind = this.bindPointer();
291
+ if (opts.autoplay !== false)
292
+ this.play();
293
+ else
294
+ this.draw();
295
+ }
296
+ static async create(ck, canvas, src, opts = {}) {
297
+ const asset = isAsset(src) ? src : await loadOpenBone(ck, src, opts);
298
+ const driver = await OpenBoneDriver.create(asset.doc, asset.baseUrl, { unlockTarget: canvas.ownerDocument?.defaultView ?? undefined, ...opts });
299
+ return new CanvasKitPlayer(ck, canvas, asset, driver, opts);
300
+ }
301
+ makeSurface() {
302
+ const dpr = devicePixelRatio || 1;
303
+ const c = this.canvas;
304
+ c.width = Math.round((c.clientWidth || this.asset.doc.width) * dpr);
305
+ c.height = Math.round((c.clientHeight || this.asset.doc.height) * dpr);
306
+ const s = (this.opts.surface !== "software" && this.ck.MakeWebGLCanvasSurface(c)) || this.ck.MakeSWCanvasSurface(c);
307
+ if (!s)
308
+ throw new Error("CanvasKit: could not create a surface");
309
+ const d = this.asset.doc;
310
+ const w = c.width / dpr;
311
+ const h = c.height / dpr;
312
+ const fit = this.opts.fit ?? "contain";
313
+ const z = fit === "none" ? 1 : (fit === "cover" ? Math.max : Math.min)(w / d.width, h / d.height);
314
+ this.view = { zoom: z, x: (w - d.width * z) / 2, y: (h - d.height * z) / 2 };
315
+ return s;
316
+ }
317
+ /** Call after the canvas changed size. */
318
+ resize() {
319
+ this.surface.delete();
320
+ this.surface = this.makeSurface();
321
+ if (!this.playing)
322
+ this.draw();
323
+ }
324
+ /** Page (client) coordinates, e.g. a pointer event's clientX/clientY, to skeleton space (y up), through the current fit. */
325
+ clientToSkeleton(clientX, clientY) {
326
+ const r = this.canvas.getBoundingClientRect();
327
+ const ax = (clientX - r.left - this.view.x) / this.view.zoom;
328
+ const ay = (clientY - r.top - this.view.y) / this.view.zoom;
329
+ return this.driver.instance.artboardToSkeleton(ax, ay);
330
+ }
331
+ /** The active bounding boxes (skeleton space): `player.boundingBoxes().containsPoint(...player.clientToSkeleton(e.clientX, e.clientY))`. */
332
+ boundingBoxes() {
333
+ return this.driver.boundingBoxes();
334
+ }
335
+ bindPointer() {
336
+ const send = (type) => (e) => this.driver.pointer(type, ...this.clientToSkeleton(e.clientX, e.clientY));
337
+ const c = this.canvas;
338
+ const down = send("down");
339
+ const up = send("up");
340
+ const move = send("move");
341
+ const leave = () => this.driver.pointerLeave();
342
+ c.addEventListener("pointerdown", down);
343
+ c.addEventListener("pointerup", up);
344
+ c.addEventListener("pointermove", move);
345
+ c.addEventListener("pointerleave", leave);
346
+ return () => {
347
+ c.removeEventListener("pointerdown", down);
348
+ c.removeEventListener("pointerup", up);
349
+ c.removeEventListener("pointermove", move);
350
+ c.removeEventListener("pointerleave", leave);
351
+ };
352
+ }
353
+ draw() {
354
+ const canvas = this.surface.getCanvas();
355
+ const dpr = devicePixelRatio || 1;
356
+ const bg = this.opts.background === undefined ? this.asset.doc.background : this.opts.background;
357
+ canvas.clear(bg ? this.ck.parseColorString(bg) : this.ck.TRANSPARENT);
358
+ this.renderer.render(canvas, this.driver.skeleton, { x: this.view.x * dpr, y: this.view.y * dpr, zoom: this.view.zoom * dpr });
359
+ this.surface.flush();
360
+ }
361
+ play() {
362
+ if (this.playing)
363
+ return;
364
+ this.playing = true;
365
+ this.driver.resume();
366
+ this.last = performance.now();
367
+ const tick = (now) => {
368
+ if (!this.playing)
369
+ return;
370
+ this.driver.advance(Math.min(0.1, (now - this.last) / 1000));
371
+ this.last = now;
372
+ this.draw();
373
+ this.raf = requestAnimationFrame(tick);
374
+ };
375
+ this.raf = requestAnimationFrame(tick);
376
+ }
377
+ pause() {
378
+ this.playing = false;
379
+ cancelAnimationFrame(this.raf);
380
+ this.driver.pause();
381
+ }
382
+ get instance() {
383
+ return this.driver.instance;
384
+ }
385
+ get stateMachine() {
386
+ return this.driver.stateMachine;
387
+ }
388
+ setInput(name, value) {
389
+ this.driver.setInput(name, value);
390
+ }
391
+ getInput(name) {
392
+ return this.driver.getInput(name);
393
+ }
394
+ fire(name) {
395
+ this.driver.fire(name);
396
+ }
397
+ setText(slot, text) {
398
+ this.driver.setText(slot, text);
399
+ }
400
+ setSkin(name) {
401
+ this.driver.setSkin(name);
402
+ if (!this.playing)
403
+ this.draw();
404
+ }
405
+ playAnimation(name, loop = true) {
406
+ this.driver.play(name, loop);
407
+ }
408
+ /** Listen to "event", "stateChange" or "audio"; returns an unsubscribe function. */
409
+ on = (name, fn) => this.driver.on(name, fn);
410
+ dispose() {
411
+ this.pause();
412
+ this.unbind();
413
+ this.driver.dispose();
414
+ this.renderer.dispose();
415
+ this.surface.delete();
416
+ }
417
+ }
418
+ function isAsset(x) {
419
+ return !!x && typeof x === "object" && "images" in x && "doc" in x;
420
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@openbone/canvaskit",
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 CanvasKit (Skia WebAssembly): renderer and player",
5
+ "keywords": [
6
+ "openbone",
7
+ "skeletal-animation",
8
+ "2d-animation",
9
+ "animation",
10
+ "canvaskit",
11
+ "skia"
12
+ ],
13
+ "homepage": "https://github.com/UXCentury/open-bone/tree/main/packages/canvaskit#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/canvaskit"
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
+ "canvaskit-wasm": ">=0.39.0"
44
+ },
45
+ "devDependencies": {
46
+ "esbuild": "^0.28.2",
47
+ "canvaskit-wasm": "^0.40.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
  }