Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(sdk): a skeletal runtime's shared surface, and DragonBones behind it

esengine3719dcb7fc79
diff --git a/sdk/etc/spine.api.md b/sdk/etc/spine.api.md
index 149a4d0ca..2b3623a8d 100644
--- a/sdk/etc/spine.api.md
+++ b/sdk/etc/spine.api.md
@@ -143,7 +143,7 @@ collectEvents: (instanceId: number) => RawSpineEvent[]
createInstance: (skeletonHandle: number) => number
destroyInstance: (instanceId: number) => void
enableEvents: (instanceId: number) => void
-forEachMeshBatch: (instanceId: number, cb: (vertBytes: Uint8Array, indexBytes: Uint8Array, vertexCount: number, indexCount: number, textureId: number, blendMode: number) => void) => void
+forEachMeshBatch: (instanceId: number, cb: MeshBatchVisitor) => void
getAnimations: (instanceId: number) => string[]
getAtlasPageCount: (handle: number) => number
getAtlasPageTextureName: (handle: number, pageIndex: number) => string
diff --git a/sdk/src/dragonbones/DragonBonesController.ts b/sdk/src/dragonbones/DragonBonesController.ts
new file mode 100644
index 000000000..3b0629fdb
--- /dev/null
+++ b/sdk/src/dragonbones/DragonBonesController.ts
@@ -0,0 +1,155 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file dragonbones/DragonBonesController.ts
+ * @brief One loaded DragonBones module, driven from TypeScript.
+ *
+ * @details Implements SkeletalController — the part that means the same thing as
+ * it does for Spine — and then adds what only DragonBones has, rather
+ * than bending either runtime into the other's vocabulary.
+ *
+ * Two additions are worth naming. `getArmatures` exists because a
+ * DragonBones file is a project holding several armatures, so choosing
+ * one is a real step and not a detail. And `fadeIn` is where Spine would
+ * set a mix duration: DragonBones crossfades at the moment of play, so
+ * the fade is an argument to starting an animation, not state on the
+ * skeleton.
+ */
+import { forEachMeshBatch, type MeshBatchVisitor } from '../skeletal/meshBatches';
+import type { SkeletalBounds, SkeletalController } from '../skeletal/types';
+import type { DragonBonesWasmModule, DragonBonesWrappedAPI } from './DragonBonesModuleLoader';
+import { withMalloc } from '../wasmScratch';
+import { log } from '../logger';
+
+/** Parse a `["a","b"]` the module published; a malformed one is no names, not a throw. */
+function parseNames(json: string): string[] {
+ try {
+ const parsed: unknown = JSON.parse(json);
+ return Array.isArray(parsed) ? (parsed as string[]) : [];
+ } catch {
+ return [];
+ }
+}
+
+export class DragonBonesModuleController implements SkeletalController {
+ private readonly raw_: DragonBonesWasmModule;
+ private readonly api_: DragonBonesWrappedAPI;
+
+ constructor(raw: DragonBonesWasmModule, api: DragonBonesWrappedAPI) {
+ this.raw_ = raw;
+ this.api_ = api;
+ }
+
+ // — Resources ————————————————————————————————————————————————————————————
+
+ /**
+ * Parse a skeleton and its atlas together; -1 on failure, with the reason in
+ * {@link getLastError}. Both are copied into the module's heap because the
+ * parsers want a terminated string and the caller's bytes are not one.
+ */
+ loadSkeleton(skeletonData: Uint8Array | string, atlasJson: string): number {
+ const skeleton = typeof skeletonData === 'string'
+ ? new TextEncoder().encode(skeletonData)
+ : skeletonData;
+ const atlas = new TextEncoder().encode(atlasJson);
+
+ return withMalloc(this.raw_, skeleton.length + atlas.length, basePtr => {
+ const skeletonPtr = basePtr;
+ const atlasPtr = basePtr + skeleton.length;
+ this.raw_.HEAPU8.set(skeleton, skeletonPtr);
+ this.raw_.HEAPU8.set(atlas, atlasPtr);
+ return this.api_.loadSkeleton(skeletonPtr, skeleton.length, atlasPtr, atlas.length);
+ });
+ }
+
+ getLastError(): string {
+ return this.api_.getLastError();
+ }
+
+ unloadSkeleton(handle: number): void {
+ this.api_.unloadSkeleton(handle);
+ }
+
+ /** The armatures this file holds — DragonBones-only; a Spine file has one skeleton. */
+ getArmatures(handle: number): string[] {
+ return parseNames(this.api_.getArmatures(handle));
+ }
+
+ /** The image the atlas expects, so the caller knows what to upload. */
+ getAtlasImageName(handle: number): string {
+ return this.api_.getAtlasImageName(handle);
+ }
+
+ /**
+ * Bind the uploaded page. Safe to call after instances exist — the module
+ * invalidates them, because uploading last is the normal order.
+ */
+ setAtlasTexture(handle: number, textureId: number): void {
+ this.api_.setAtlasTexture(handle, textureId);
+ }
+
+ // — Instances ————————————————————————————————————————————————————————————
+
+ /** -1 when the file holds no armature by that name (see {@link getArmatures}). */
+ createInstance(skeletonHandle: number, armatureName: string): number {
+ const id = this.api_.createInstance(skeletonHandle, armatureName);
+ if (id < 0) log.warn('dragonbones', `createInstance failed: ${this.getLastError()}`);
+ return id;
+ }
+
+ destroyInstance(instanceId: number): void {
+ this.api_.destroyInstance(instanceId);
+ }
+
+ // — Animation ————————————————————————————————————————————————————————————
+
+ /** `loop` false plays once; DragonBones counts plays, where 0 means forever. */
+ play(instanceId: number, animation: string, loop = true): boolean {
+ return this.api_.playAnimation(instanceId, animation, loop ? 0 : 1) !== 0;
+ }
+
+ /** Crossfade into `animation` over `fadeSeconds` — Spine's mix table, per play. */
+ fadeIn(instanceId: number, animation: string, fadeSeconds: number, loop = true): boolean {
+ return this.api_.fadeInAnimation(instanceId, animation, fadeSeconds, loop ? 0 : 1) !== 0;
+ }
+
+ stop(instanceId: number, animation = ''): void {
+ this.api_.stopAnimation(instanceId, animation);
+ }
+
+ setTimeScale(instanceId: number, scale: number): void {
+ this.api_.setTimeScale(instanceId, scale);
+ }
+
+ update(instanceId: number, dt: number): void {
+ this.api_.update(instanceId, dt);
+ }
+
+ getAnimations(instanceId: number): string[] {
+ return parseNames(this.api_.getAnimations(instanceId));
+ }
+
+ // — Geometry ————————————————————————————————————————————————————————————
+
+ getBounds(instanceId: number): SkeletalBounds {
+ return withMalloc(this.raw_, 16, ptr => {
+ this.api_.getBounds(instanceId, ptr, ptr + 4, ptr + 8, ptr + 12);
+ const f = this.raw_.HEAPF32;
+ return {
+ x: f[ptr >> 2],
+ y: f[(ptr + 4) >> 2],
+ width: f[(ptr + 8) >> 2],
+ height: f[(ptr + 12) >> 2],
+ };
+ });
+ }
+
+ forEachMeshBatch(instanceId: number, cb: MeshBatchVisitor): void {
+ forEachMeshBatch(this.raw_, this.api_, instanceId, cb);
+ }
+
+ /** The DragonBones data format this module reads. */
+ runtimeVersion(): number {
+ return this.api_.runtimeVersion();
+ }
+}
diff --git a/sdk/src/dragonbones/DragonBonesModuleLoader.ts b/sdk/src/dragonbones/DragonBonesModuleLoader.ts
new file mode 100644
index 000000000..40f8d3f2e
--- /dev/null
+++ b/sdk/src/dragonbones/DragonBonesModuleLoader.ts
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file dragonbones/DragonBonesModuleLoader.ts
+ * @brief cwrap the DragonBones side module's exports once, so the controller
+ * calls typed functions instead of re-stating signatures per call.
+ */
+import type { SkeletalHeap } from '../skeletal/meshBatches';
+
+export interface DragonBonesWasmModule extends SkeletalHeap {
+ cwrap(name: string, ret: string | null, sig: string[]): (...args: unknown[]) => unknown;
+ HEAPF32: Float32Array;
+ HEAP32: Int32Array;
+}
+
+export type DragonBonesModuleFactory = (options?: { wasmBinary?: Uint8Array }) => Promise<DragonBonesWasmModule>;
+
+export interface DragonBonesWrappedAPI {
+ loadSkeleton(skeletonPtr: number, skeletonLen: number, atlasPtr: number, atlasLen: number): number;
+ getLastError(): string;
+ unloadSkeleton(handle: number): void;
+ getArmatures(handle: number): string;
+ getAtlasImageName(handle: number): string;
+ setAtlasTexture(handle: number, textureId: number): void;
+
+ createInstance(handle: number, armatureName: string): number;
+ destroyInstance(instanceId: number): void;
+
+ playAnimation(instanceId: number, name: string, playTimes: number): number;
+ fadeInAnimation(instanceId: number, name: string, fadeSeconds: number, playTimes: number): number;
+ stopAnimation(instanceId: number, name: string): void;
+ setTimeScale(instanceId: number, scale: number): void;
+ update(instanceId: number, dt: number): void;
+ getAnimations(instanceId: number): string;
+
+ getMeshBatchCount(instanceId: number): number;
+ getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;
+ getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;
+ getMeshBatchData(
+ instanceId: number, batchIndex: number,
+ verticesPtr: number, indicesPtr: number, textureIdPtr: number, blendModePtr: number,
+ ): void;
+ getBounds(instanceId: number, xPtr: number, yPtr: number, wPtr: number, hPtr: number): void;
+ runtimeVersion(): number;
+}
+
+const N = 'number';
+const S = 'string';
+
+/** Bind every export once; a typo becomes a load-time failure, not a call-time one. */
+export function wrapDragonBonesModule(raw: DragonBonesWasmModule): DragonBonesWrappedAPI {
+ const w = <T>(name: string, ret: string | null, sig: string[]): T =>
+ raw.cwrap(`db_${name}`, ret, sig) as unknown as T;
+
+ return {
+ loadSkeleton: w('loadSkeleton', N, [N, N, N, N]),
+ getLastError: w('getLastError', S, []),
+ unloadSkeleton: w('unloadSkeleton', null, [N]),
+ getArmatures: w('getArmatures', S, [N]),
+ getAtlasImageName: w('getAtlasImageName', S, [N]),
+ setAtlasTexture: w('setAtlasTexture', null, [N, N]),
+
+ createInstance: w('createInstance', N, [N, S]),
+ destroyInstance: w('destroyInstance', null, [N]),
+
+ playAnimation: w('playAnimation', N, [N, S, N]),
+ fadeInAnimation: w('fadeInAnimation', N, [N, S, N, N]),
+ stopAnimation: w('stopAnimation', null, [N, S]),
+ setTimeScale: w('setTimeScale', null, [N, N]),
+ update: w('update', null, [N, N]),
+ getAnimations: w('getAnimations', S, [N]),
+
+ getMeshBatchCount: w('getMeshBatchCount', N, [N]),
+ getMeshBatchVertexCount: w('getMeshBatchVertexCount', N, [N, N]),
+ getMeshBatchIndexCount: w('getMeshBatchIndexCount', N, [N, N]),
+ getMeshBatchData: w('getMeshBatchData', null, [N, N, N, N, N, N]),
+ getBounds: w('getBounds', null, [N, N, N, N, N]),
+ runtimeVersion: w('runtimeVersion', N, []),
+ };
+}
diff --git a/sdk/src/dragonbones/index.ts b/sdk/src/dragonbones/index.ts
new file mode 100644
index 000000000..6b583ec5c
--- /dev/null
+++ b/sdk/src/dragonbones/index.ts
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+export { DragonBonesModuleController } from './DragonBonesController';
+export { wrapDragonBonesModule } from './DragonBonesModuleLoader';
+export type {
+ DragonBonesWasmModule,
+ DragonBonesWrappedAPI,
+ DragonBonesModuleFactory,
+} from './DragonBonesModuleLoader';
diff --git a/sdk/src/skeletal/index.ts b/sdk/src/skeletal/index.ts
new file mode 100644
index 000000000..07b0775d1
--- /dev/null
+++ b/sdk/src/skeletal/index.ts
@@ -0,0 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+export { forEachMeshBatch } from './meshBatches';
+export type { MeshBatchSource, MeshBatchVisitor, SkeletalHeap } from './meshBatches';
+export type { SkeletalBounds, SkeletalController } from './types';
diff --git a/sdk/src/skeletal/meshBatches.ts b/sdk/src/skeletal/meshBatches.ts
new file mode 100644
index 000000000..5aab03955
--- /dev/null
+++ b/sdk/src/skeletal/meshBatches.ts
@@ -0,0 +1,83 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file skeletal/meshBatches.ts
+ * @brief Reading posed geometry back out of a skeletal side module.
+ *
+ * @details Every such module answers the same four questions — how many batches,
+ * how many vertices, how many indices, give me the bytes — because
+ * SkeletalModule.hpp packs them the same way on the other side. So this
+ * is written against those four rather than against a runtime, and Spine
+ * and DragonBones both hand it their own.
+ *
+ * The views handed to the callback point INTO the module's scratch heap
+ * and die when the call returns. That is the point: a consumer copies
+ * those bytes straight into its own heap, and nothing allocates a typed
+ * array per batch per frame.
+ */
+import { withMalloc, withScratch } from '../wasmScratch';
+
+/** The heap a module marshals through. */
+export interface SkeletalHeap {
+ _malloc(size: number): number;
+ _free(ptr: number): void;
+ HEAPU8: Uint8Array;
+ HEAPU32: Uint32Array;
+}
+
+/** The four readback entry points, however a module spells them. */
+export interface MeshBatchSource {
+ getMeshBatchCount(instanceId: number): number;
+ getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;
+ getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;
+ getMeshBatchData(
+ instanceId: number, batchIndex: number,
+ verticesPtr: number, indicesPtr: number, textureIdPtr: number, blendModePtr: number,
+ ): void;
+}
+
+export type MeshBatchVisitor = (
+ vertBytes: Uint8Array, indexBytes: Uint8Array,
+ vertexCount: number, indexCount: number,
+ textureId: number, blendMode: number,
+) => void;
+
+/** Interleaved x,y,u,v,r,g,b,a — the layout every skeletal module writes. */
+const VERTEX_FLOATS = 8;
+
+/** Visit each posed batch. Views are valid only for the duration of each call. */
+export function forEachMeshBatch(
+ heap: SkeletalHeap,
+ api: MeshBatchSource,
+ instanceId: number,
+ cb: MeshBatchVisitor,
+): void {
+ const batchCount = api.getMeshBatchCount(instanceId);
+ if (batchCount === 0) return;
+
+ withMalloc(heap, 8, metaPtr => {
+ const texIdPtr = metaPtr;
+ const blendPtr = metaPtr + 4;
+
+ for (let i = 0; i < batchCount; i++) {
+ const vertexCount = api.getMeshBatchVertexCount(instanceId, i);
+ const indexCount = api.getMeshBatchIndexCount(instanceId, i);
+ if (vertexCount <= 0 || indexCount <= 0) continue;
+
+ const vertByteLen = vertexCount * VERTEX_FLOATS * 4;
+ const idxByteLen = indexCount * 2;
+ withScratch(heap, alloc => {
+ const vertPtr = alloc(vertByteLen);
+ const idxPtr = alloc(idxByteLen);
+ api.getMeshBatchData(instanceId, i, vertPtr, idxPtr, texIdPtr, blendPtr);
+ cb(
+ new Uint8Array(heap.HEAPU8.buffer, vertPtr, vertByteLen),
+ new Uint8Array(heap.HEAPU8.buffer, idxPtr, idxByteLen),
+ vertexCount, indexCount,
+ heap.HEAPU32[texIdPtr >> 2],
+ heap.HEAPU32[blendPtr >> 2],
+ );
+ });
+ }
+ });
+}
diff --git a/sdk/src/skeletal/types.ts b/sdk/src/skeletal/types.ts
new file mode 100644
index 000000000..286349c8d
--- /dev/null
+++ b/sdk/src/skeletal/types.ts
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file skeletal/types.ts
+ * @brief What a caller can ask of ANY skeletal runtime the engine hosts.
+ *
+ * @details Deliberately the intersection and not the union. Spine mixes through a
+ * from/to table set on the skeleton; DragonBones fades in at the moment
+ * of play. Spine has skins and path constraints; DragonBones has display
+ * lists and several armatures per file. Folding those together would
+ * invent a vocabulary neither runtime speaks, so each keeps its own on
+ * its own controller, and only what genuinely means the same thing in
+ * both is promised here.
+ *
+ * What that leaves is the lifecycle, the queries the editor and gameplay
+ * actually reach for, and the render path — which is most of what code
+ * outside the two implementations ever touches.
+ */
+import type { MeshBatchVisitor } from './meshBatches';
+
+export interface SkeletalBounds {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+export interface SkeletalController {
+ /** Why the last call that could fail did. Empty when it did not. */
+ getLastError(): string;
+
+ /** Drop a loaded file and every instance built from it. */
+ unloadSkeleton(handle: number): void;
+
+ destroyInstance(instanceId: number): void;
+
+ /** Advance by `dt` seconds and re-pose. Geometry is read back after this. */
+ update(instanceId: number, dt: number): void;
+
+ /** Animation names this instance can play. */
+ getAnimations(instanceId: number): string[];
+
+ /** Where the posed skeleton currently is, in its own units. */
+ getBounds(instanceId: number): SkeletalBounds;
+
+ /** Visit the posed geometry; views live only for the duration of each call. */
+ forEachMeshBatch(instanceId: number, cb: MeshBatchVisitor): void;
+}
+
+export type { MeshBatchVisitor };
diff --git a/sdk/src/spine/SpineController.ts b/sdk/src/spine/SpineController.ts
index 11f82fe18..2ed8cb9af 100644
--- a/sdk/src/spine/SpineController.ts
+++ b/sdk/src/spine/SpineController.ts
@@ -10,6 +10,7 @@ import type { SpineWasmModule, SpineWrappedAPI } from './SpineModuleLoader';
import { SpineModuleBridge } from './SpineBridge';
import { log } from '../logger';
import { withMalloc, withScratch } from '../wasmScratch';
+import { forEachMeshBatch, type MeshBatchVisitor } from '../skeletal/meshBatches';
export type SpineEventType = 'start' | 'interrupt' | 'end' | 'complete' | 'dispose' | 'event';
@@ -227,52 +228,17 @@ export class SpineModuleController {
// =========================================================================
/**
- * Iterate this instance's mesh batches, invoking `cb` for each with Uint8Array
- * views directly into spine wasm scratch — valid only for the duration of the
- * call. No per-batch Float32Array/Uint16Array allocation and no copy out; the
- * consumer copies the bytes straight into its own wasm heap while the view is
- * live. Replaces extractMeshBatches, which allocated and cached two typed
- * arrays per batch per frame (C7).
+ * Iterate this instance's mesh batches. The views point into wasm scratch and
+ * are valid only for the duration of each call, so a consumer copies straight
+ * into its own heap and nothing allocates a typed array per batch per frame.
+ *
+ * The walk itself is shared with every other skeletal module (see
+ * skeletal/meshBatches) — the four readback entry points are packed the same
+ * way on the C++ side, so reading them differently per runtime would be two
+ * copies of one contract.
*/
- forEachMeshBatch(
- instanceId: number,
- cb: (
- vertBytes: Uint8Array, indexBytes: Uint8Array,
- vertexCount: number, indexCount: number,
- textureId: number, blendMode: number,
- ) => void,
- ): void {
- const batchCount = this.api_.getMeshBatchCount(instanceId);
- if (batchCount === 0) return;
-
- withMalloc(this.raw_, 8, metaPtr => {
- const texIdPtr = metaPtr;
- const blendPtr = metaPtr + 4;
-
- for (let i = 0; i < batchCount; i++) {
- const vertexCount = this.api_.getMeshBatchVertexCount(instanceId, i);
- const indexCount = this.api_.getMeshBatchIndexCount(instanceId, i);
- if (vertexCount <= 0 || indexCount <= 0) continue;
-
- const vertByteLen = vertexCount * 8 * 4;
- const idxByteLen = indexCount * 2;
- withScratch(this.raw_, alloc => {
- const vertPtr = alloc(vertByteLen);
- const idxPtr = alloc(idxByteLen);
-
- this.api_.getMeshBatchData(
- instanceId, i, vertPtr, idxPtr, texIdPtr, blendPtr);
-
- cb(
- new Uint8Array(this.raw_.HEAPU8.buffer, vertPtr, vertByteLen),
- new Uint8Array(this.raw_.HEAPU8.buffer, idxPtr, idxByteLen),
- vertexCount, indexCount,
- this.raw_.HEAPU32[texIdPtr >> 2],
- this.raw_.HEAPU32[blendPtr >> 2],
- );
- });
- }
- });
+ forEachMeshBatch(instanceId: number, cb: MeshBatchVisitor): void {
+ forEachMeshBatch(this.raw_, this.api_, instanceId, cb);
}
// =========================================================================
diff --git a/sdk/tests/dragonbones-controller.integration.test.ts b/sdk/tests/dragonbones-controller.integration.test.ts
new file mode 100644
index 000000000..e37805a77
--- /dev/null
+++ b/sdk/tests/dragonbones-controller.integration.test.ts
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The SDK layer, driven the way a caller would. The raw-ABI test beside this one
+// checks the module; this one checks that the TypeScript in front of it marshals
+// correctly — two heaps, a string list crossing as JSON, and geometry read back
+// through the walk that Spine now shares.
+import { describe, it, expect, beforeAll } from 'vitest';
+import { existsSync, readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { WASM_DIR } from './helpers/loadWasm';
+import { DragonBonesModuleController } from '../src/dragonbones/DragonBonesController';
+import { wrapDragonBonesModule, type DragonBonesWasmModule } from '../src/dragonbones/DragonBonesModuleLoader';
+
+const DB_JS = resolve(WASM_DIR, 'dragonbones.js');
+const DB_WASM = resolve(WASM_DIR, 'dragonbones.wasm');
+const ASSET_DIR = resolve(__dirname, 'assets/dragonbones');
+const SKE = resolve(ASSET_DIR, 'DragonBoy_ske.json');
+const TEX = resolve(ASSET_DIR, 'DragonBoy_tex.json');
+const HAS_ASSETS = existsSync(DB_WASM) && existsSync(SKE);
+
+describe.skipIf(!HAS_ASSETS)('DragonBonesModuleController', () => {
+ let controller: DragonBonesModuleController;
+
+ beforeAll(async () => {
+ const factory = (await import(DB_JS)).default as
+ (a: { wasmBinary: Uint8Array }) => Promise<DragonBonesWasmModule>;
+ const raw = await factory({ wasmBinary: new Uint8Array(readFileSync(DB_WASM)) });
+ controller = new DragonBonesModuleController(raw, wrapDragonBonesModule(raw));
+ });
+
+ const load = (): number =>
+ controller.loadSkeleton(new Uint8Array(readFileSync(SKE)), readFileSync(TEX, 'utf8'));
+
+ it('loads from bytes and from a string alike', () => {
+ const fromBytes = load();
+ expect(fromBytes, controller.getLastError()).toBeGreaterThanOrEqual(0);
+ const fromText = controller.loadSkeleton(readFileSync(SKE, 'utf8'), readFileSync(TEX, 'utf8'));
+ expect(fromText).toBeGreaterThanOrEqual(0);
+ expect(controller.getArmatures(fromText)).toEqual(controller.getArmatures(fromBytes));
+ controller.unloadSkeleton(fromBytes);
+ controller.unloadSkeleton(fromText);
+ });
+
+ it('reports a failure instead of a handle', () => {
+ const handle = controller.loadSkeleton(new Uint8Array([1, 2, 3]), 'not json');
+ expect(handle).toBeLessThan(0);
+ expect(controller.getLastError()).not.toBe('');
+ });
+
+ it('names the armatures and the image the atlas wants', () => {
+ const handle = load();
+ expect(controller.getArmatures(handle)).toEqual(['Dragon']);
+ expect(controller.getAtlasImageName(handle)).toBe('DragonBoy_tex.png');
+ controller.unloadSkeleton(handle);
+ });
+
+ it('plays, poses, and hands geometry back through the shared walk', () => {
+ const handle = load();
+ controller.setAtlasTexture(handle, 42);
+ const instance = controller.createInstance(handle, 'Dragon');
+ expect(instance).toBeGreaterThanOrEqual(0);
+ expect(controller.getAnimations(instance).sort()).toEqual(['fall', 'jump', 'stand', 'walk']);
+
+ expect(controller.play(instance, 'walk')).toBe(true);
+ for (let i = 0; i < 10; i++) controller.update(instance, 1 / 60);
+
+ let batches = 0;
+ let vertices = 0;
+ controller.forEachMeshBatch(instance, (vertBytes, indexBytes, vertexCount, indexCount, textureId) => {
+ batches++;
+ vertices += vertexCount;
+ expect(textureId).toBe(42);
+ // The views are windows into wasm scratch, so their length is the
+ // contract: eight floats a vertex, two bytes an index.
+ expect(vertBytes.byteLength).toBe(vertexCount * 8 * 4);
+ expect(indexBytes.byteLength).toBe(indexCount * 2);
+ });
+ expect(batches).toBeGreaterThan(0);
+ expect(vertices).toBeGreaterThan(0);
+
+ controller.destroyInstance(instance);
+ controller.unloadSkeleton(handle);
+ });
+
+ it('crossfades where Spine would consult a mix table', () => {
+ const handle = load();
+ controller.setAtlasTexture(handle, 1);
+ const instance = controller.createInstance(handle, 'Dragon');
+ controller.play(instance, 'stand');
+ controller.update(instance, 1 / 60);
+
+ expect(controller.fadeIn(instance, 'walk', 0.2)).toBe(true);
+ for (let i = 0; i < 6; i++) controller.update(instance, 1 / 60);
+ const bounds = controller.getBounds(instance);
+ // Mid-fade the pose is neither animation, but it is still a posed skeleton.
+ expect(bounds.width).toBeGreaterThan(0);
+ expect(Number.isFinite(bounds.x)).toBe(true);
+
+ controller.destroyInstance(instance);
+ controller.unloadSkeleton(handle);
+ });
+
+ it('refuses an armature the file does not hold', () => {
+ const handle = load();
+ expect(controller.createInstance(handle, 'NotAnArmature')).toBeLessThan(0);
+ expect(controller.getLastError()).not.toBe('');
+ controller.unloadSkeleton(handle);
+ });
+});