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.

fix(spine): binding an entity to a runtime is a transaction with one authority

esenginec548887b95ef
diff --git a/sdk/etc/spine.api.md b/sdk/etc/spine.api.md
index 06a8059db..8f11e5e32 100644
--- a/sdk/etc/spine.api.md
+++ b/sdk/etc/spine.api.md
@@ -101,6 +101,7 @@ events: readonly SpineEvent[]
## SpineManager — class @experimental
```
+@internal moduleBackendForDiagnostics: (version: SpineVersion) => ModuleBackend | undefined
boundEntities: () => Iterable<Entity>
collectAllEvents: () => { entity: Entity; raw: RawSpineEvent; }[]
dispose: () => void
@@ -108,7 +109,6 @@ enableEvents: (entity: Entity) => void
getAnimations: (entity: Entity) => string[]
getBounds: (entity: Entity) => { x: number; y: number; width: number; height: number; } | null
getEntityVersion: (entity: Entity) => SpineVersion | undefined
-getModuleBackend: (version: SpineVersion) => ModuleBackend | undefined
getPathConstraintMix: (entity: Entity, name: string) => PathMixData | null
getSkins: (entity: Entity) => string[]
getTransformConstraintMix: (entity: Entity, name: string) => TransformMixData | null
@@ -129,7 +129,6 @@ setSkin: (entity: Entity, skin: string) => void
setSlotColor: (entity: Entity, slotName: string, r: number, g: number, b: number, a: number) => boolean
setTrackAlpha: (entity: Entity, track: number, alpha: number) => void
setTransformConstraintMix: (entity: Entity, name: string, mix: TransformMixData) => boolean
-shutdown: () => void
submitMeshes: (registry: CppRegistry, materialOf?: SkeletalMaterialOf) => void
updateAnimations: (dt: number) => void
static detectVersion: (data: Uint8Array) => SpineVersion | null
diff --git a/sdk/src/spine/ModuleBackend.ts b/sdk/src/spine/ModuleBackend.ts
index 2ad30de05..ead0a1be7 100644
--- a/sdk/src/spine/ModuleBackend.ts
+++ b/sdk/src/spine/ModuleBackend.ts
@@ -57,42 +57,60 @@ export class ModuleBackend {
*/
era?: string,
): boolean {
- // Re-loading a live entity (rapid editor ref edits, runtime asset swap)
- // must free the old instance + skeleton refcount first, or replacing its
- // EntityInfo below leaks the native instance and pins the shared skeleton.
- if (this.entities_.has(entity)) this.removeEntity(entity);
-
- let skelHandle: number;
- const shared = era !== undefined ? this.skeletons_.get(era) : undefined;
- if (shared) {
- // Reuse the already-loaded skeleton — just spin up a fresh instance.
- skelHandle = shared.skelHandle;
- shared.refcount++;
- } else {
- skelHandle = this.controller_.loadSkeleton(skelData, atlasText, isBinary);
- if (skelHandle < 0) {
- log.error('spine', `Failed to load skeleton: ${this.controller_.getLastError()}`);
- return false;
- }
- const pageCount = this.controller_.getAtlasPageCount(skelHandle);
- for (let i = 0; i < pageCount; i++) {
- const pageName = this.controller_.getAtlasPageTextureName(skelHandle, i);
- const tex = textures.get(pageName);
- if (tex) {
- this.controller_.setAtlasPageTexture(skelHandle, i, tex.glId, tex.w, tex.h);
- }
- }
- if (era !== undefined) this.skeletons_.set(era, { skelHandle, refcount: 1 });
+ // Commit after success, like the preparation that produced the asset:
+ // what this replaces keeps posing until the new binding exists, so a
+ // skeleton that will not parse costs the entity nothing.
+ const claimed = this.claimSkeleton_(skelData, atlasText, textures, isBinary, era);
+ if (claimed < 0) return false;
+ const instanceId = this.controller_.createInstance(claimed);
+ if (instanceId < 0) {
+ log.error('spine', `Failed to create instance: ${this.controller_.getLastError()}`);
+ this.releaseSkeleton_({ skelHandle: claimed, era } as EntityInfo);
+ return false;
}
- const instanceId = this.controller_.createInstance(skelHandle);
+ // Only now: the old instance and its claim on the era it was posing.
+ // Re-binding to the SAME era claimed it again above, so the skeleton is
+ // never unloaded and re-parsed underneath an entity that stays on it.
+ this.removeEntity(entity);
this.entities_.set(entity, {
- skelHandle, instanceId, era,
+ skelHandle: claimed, instanceId, era,
skeletonScale: 1, flipX: false, flipY: false, layer: 0, timeScale: 1, playing: true,
});
return true;
}
+ /** One claim on the era's native skeleton — the loaded one if this runtime
+ * already has it, else a fresh parse. -1 when it will not parse. */
+ private claimSkeleton_(
+ skelData: Uint8Array | string,
+ atlasText: string,
+ textures: Map<string, { glId: number; w: number; h: number }>,
+ isBinary: boolean,
+ era?: string,
+ ): number {
+ const shared = era !== undefined ? this.skeletons_.get(era) : undefined;
+ if (shared) {
+ shared.refcount++;
+ return shared.skelHandle;
+ }
+ const skelHandle = this.controller_.loadSkeleton(skelData, atlasText, isBinary);
+ if (skelHandle < 0) {
+ log.error('spine', `Failed to load skeleton: ${this.controller_.getLastError()}`);
+ return -1;
+ }
+ const pageCount = this.controller_.getAtlasPageCount(skelHandle);
+ for (let i = 0; i < pageCount; i++) {
+ const pageName = this.controller_.getAtlasPageTextureName(skelHandle, i);
+ const tex = textures.get(pageName);
+ if (tex) {
+ this.controller_.setAtlasPageTexture(skelHandle, i, tex.glId, tex.w, tex.h);
+ }
+ }
+ if (era !== undefined) this.skeletons_.set(era, { skelHandle, refcount: 1 });
+ return skelHandle;
+ }
+
setEntityProps(entity: Entity, props: {
skeletonScale?: number; flipX?: boolean; flipY?: boolean; layer?: number;
timeScale?: number; playing?: boolean; color?: { r: number; g: number; b: number; a: number };
diff --git a/sdk/src/spine/SpineManager.ts b/sdk/src/spine/SpineManager.ts
index 2569b90a0..452dffb0b 100644
--- a/sdk/src/spine/SpineManager.ts
+++ b/sdk/src/spine/SpineManager.ts
@@ -41,7 +41,10 @@ export class SpineManager {
private factories_: Map<SpineVersion, SpineModuleFactory>;
private backends_: Map<SpineVersion, ModuleBackend> = new Map();
private loadingBackends_: Map<SpineVersion, Promise<ModuleBackend | null>> = new Map();
- private entityVersions_: Map<Entity, SpineVersion> = new Map();
+ /** Which runtime poses each entity. The authority for that is HERE: a
+ * version backend can only see its own entities, so one that is handed an
+ * entity another is posing cannot retire the binding it replaces. */
+ private bindings_: Map<Entity, { version: SpineVersion; backend: ModuleBackend }> = new Map();
constructor(
/** Whichever engine core is present (see ecs/engineApi.ts). */
@@ -88,12 +91,19 @@ export class SpineManager {
}
const isBinary = skelData instanceof Uint8Array;
+ const previous = this.bindings_.get(entity);
const ok = backend.loadEntity(entity, skelData, atlasText, textures, isBinary, era);
if (!ok) {
+ // Commit after success all the way up: the entity keeps the binding
+ // it had, in whichever runtime that was.
log.error('spine', `Failed to load entity ${entity} into backend ${version}`);
return null;
}
- this.entityVersions_.set(entity, version);
+ // A move BETWEEN runtimes: the one it went to removed nothing, because
+ // it never had this entity. Left behind, the old instance is posed and
+ // submitted every frame and no despawn ever reaches it.
+ if (previous && previous.backend !== backend) previous.backend.removeEntity(entity);
+ this.bindings_.set(entity, { version, backend });
return version;
}
@@ -112,27 +122,18 @@ export class SpineManager {
/** The entities that currently have a skeleton bound — what a per-frame pass
* over "everything spine draws" iterates, without asking the World. */
boundEntities(): Iterable<Entity> {
- return this.entityVersions_.keys();
+ return this.bindings_.keys();
}
removeEntity(entity: Entity): void {
- const version = this.entityVersions_.get(entity);
- if (!version) {
- this.entityVersions_.delete(entity);
- return;
- }
- const backend = this.backends_.get(version);
- if (backend) {
- backend.removeEntity(entity);
- }
- this.entityVersions_.delete(entity);
+ this.bindings_.get(entity)?.backend.removeEntity(entity);
+ this.bindings_.delete(entity);
}
/**
- * Tear down every loaded runtime backend, freeing the native skeletons /
- * atlases each holds. Idempotent — clearing the maps makes a second call a
- * no-op. Called from SpinePlugin.cleanup() on app teardown so spine wasm
- * resources don't leak across an engine re-init.
+ * Tear down every loaded runtime, freeing the native skeletons / atlases
+ * each holds. Idempotent — clearing the maps makes a second call a no-op.
+ * The ONE teardown door: `shutdown()` was a second name for this.
*/
dispose(): void {
for (const backend of this.backends_.values()) {
@@ -140,67 +141,49 @@ export class SpineManager {
}
this.backends_.clear();
this.loadingBackends_.clear();
- this.entityVersions_.clear();
+ this.bindings_.clear();
}
getEntityVersion(entity: Entity): SpineVersion | undefined {
- return this.entityVersions_.get(entity);
+ return this.bindings_.get(entity)?.version;
}
hasModuleBackend(version: SpineVersion): boolean {
return this.backends_.has(version);
}
- getModuleBackend(version: SpineVersion): ModuleBackend | undefined {
+ /** @internal One version's runtime, for a diagnostic that has to look at
+ * what it holds. Not a door into it: an entity's binding is this manager's,
+ * and reaching a runtime directly is how one gets posed by two of them. */
+ moduleBackendForDiagnostics(version: SpineVersion): ModuleBackend | undefined {
return this.backends_.get(version);
}
setAnimation(entity: Entity, animation: string, loop: boolean): void {
- const version = this.entityVersions_.get(entity);
- if (!version) return;
- const backend = this.backends_.get(version);
- if (backend) backend.setAnimation(entity, animation, loop);
+ this.getEntityBackend_(entity)?.setAnimation(entity, animation, loop);
}
setSkin(entity: Entity, skin: string): void {
- const version = this.entityVersions_.get(entity);
- if (!version) return;
- const backend = this.backends_.get(version);
- if (backend) backend.setSkin(entity, skin);
+ this.getEntityBackend_(entity)?.setSkin(entity, skin);
}
setEntityProps(entity: Entity, props: {
skeletonScale?: number; flipX?: boolean; flipY?: boolean; layer?: number;
timeScale?: number; playing?: boolean; color?: { r: number; g: number; b: number; a: number };
}): void {
- const version = this.entityVersions_.get(entity);
- if (!version) return;
- const backend = this.backends_.get(version);
- if (backend) backend.setEntityProps(entity, props);
+ this.getEntityBackend_(entity)?.setEntityProps(entity, props);
}
getBounds(entity: Entity): { x: number; y: number; width: number; height: number } | null {
- const version = this.entityVersions_.get(entity);
- if (!version) return null;
- const backend = this.backends_.get(version);
- if (backend) return backend.getBounds(entity);
- return null;
+ return this.getEntityBackend_(entity)?.getBounds(entity) ?? null;
}
getAnimations(entity: Entity): string[] {
- const version = this.entityVersions_.get(entity);
- if (!version) return [];
- const backend = this.backends_.get(version);
- if (!backend) return [];
- return backend.getAnimations(entity);
+ return this.getEntityBackend_(entity)?.getAnimations(entity) ?? [];
}
getSkins(entity: Entity): string[] {
- const version = this.entityVersions_.get(entity);
- if (!version) return [];
- const backend = this.backends_.get(version);
- if (!backend) return [];
- return backend.getSkins(entity);
+ return this.getEntityBackend_(entity)?.getSkins(entity) ?? [];
}
setDefaultMix(entity: Entity, duration: number): void {
@@ -297,22 +280,11 @@ export class SpineManager {
}
hasInstance(entity: Entity): boolean {
- return this.entityVersions_.has(entity);
- }
-
- shutdown(): void {
- for (const backend of this.backends_.values()) {
- backend.shutdown();
- }
- this.backends_.clear();
- this.loadingBackends_.clear();
- this.entityVersions_.clear();
+ return this.bindings_.has(entity);
}
private getEntityBackend_(entity: Entity): ModuleBackend | undefined {
- const version = this.entityVersions_.get(entity);
- if (!version) return undefined;
- return this.backends_.get(version);
+ return this.bindings_.get(entity)?.backend;
}
private async ensureBackend(version: SpineVersion): Promise<ModuleBackend | null> {
diff --git a/sdk/tests/plugin-cleanup.test.ts b/sdk/tests/plugin-cleanup.test.ts
index 61be633dd..2ffe51232 100644
--- a/sdk/tests/plugin-cleanup.test.ts
+++ b/sdk/tests/plugin-cleanup.test.ts
@@ -22,7 +22,7 @@ describe('SpineManager.dispose', () => {
const m = mgr as any;
m.backends_.set('3.8', backendA);
m.backends_.set('4.1', backendB);
- m.entityVersions_.set(1, '3.8');
+ m.bindings_.set(1, { version: '3.8', backend: backendA });
m.loadingBackends_.set('4.2', Promise.resolve(null));
mgr.dispose();
@@ -30,7 +30,7 @@ describe('SpineManager.dispose', () => {
expect(backendA.shutdown).toHaveBeenCalledTimes(1);
expect(backendB.shutdown).toHaveBeenCalledTimes(1);
expect(m.backends_.size).toBe(0);
- expect(m.entityVersions_.size).toBe(0);
+ expect(m.bindings_.size).toBe(0);
expect(m.loadingBackends_.size).toBe(0);
// Idempotent: a second dispose is a no-op, not a re-shutdown / throw.
diff --git a/sdk/tests/spine-multi-version-build.test.ts b/sdk/tests/spine-multi-version-build.test.ts
index 8516e796a..22957d0d3 100644
--- a/sdk/tests/spine-multi-version-build.test.ts
+++ b/sdk/tests/spine-multi-version-build.test.ts
@@ -45,7 +45,7 @@ describe('Spine multi-version build pipeline', () => {
const manager = new SpineManager({} as any, factories as any);
expect(manager).toBeDefined();
- manager.shutdown();
+ manager.dispose();
});
test('SpineManager fails the load (no native fallback) when a version has no factory', async () => {
@@ -63,7 +63,7 @@ describe('Spine multi-version build pipeline', () => {
expect(v43).toBeNull();
expect(v42).toBeNull();
expect(manager.getEntityVersion(1 as any)).toBeUndefined();
- manager.shutdown();
+ manager.dispose();
});
test('SpineManager never touches a native spine_* binding', async () => {
@@ -81,7 +81,7 @@ describe('Spine multi-version build pipeline', () => {
1 as any, '{"spine":"4.2.10","skeleton":{}}', '', new Map(), {} as any,
);
expect(touched).toBeNull();
- manager.shutdown();
+ manager.dispose();
});
test('detectVersionJson routes every supported version, and only those', () => {
diff --git a/sdk/tests/spine-runtime-binding.test.ts b/sdk/tests/spine-runtime-binding.test.ts
new file mode 100644
index 000000000..708241350
--- /dev/null
+++ b/sdk/tests/spine-runtime-binding.test.ts
@@ -0,0 +1,162 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spine-runtime-binding.test.ts
+ * @brief Binding an entity to a spine runtime is a transaction with one
+ * authority, exactly as preparing the asset it plays is.
+ *
+ * @details Two rules, and both are about what happens when a binding is
+ * REPLACED: at any observable point one entity is posed by at most one
+ * runtime, and a replacement that fails leaves the entity playing what
+ * it was playing. A destroy-first reload with no owner above the
+ * version backends can honour neither.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { SpineManager, type SpineVersion } from '../src/spine/SpineManager';
+import type { SpineModuleFactory } from '../src/spine/SpineModuleLoader';
+import type { Entity } from '../src/types';
+
+/** A skeleton document that reports `version`, in the shape detection reads. */
+function skeletonOf(version: string): string {
+ return JSON.stringify({ skeleton: { spine: version } });
+}
+
+/** One version's wasm module, faked at the ABI: every export the controller
+ * reaches for, and a switch for making the next parse fail. */
+function fakeModule(state: { parses: boolean; skeletons: number[]; instances: number[] }) {
+ let nextSkeleton = 1;
+ let nextInstance = 1000;
+ const exports: Record<string, (...args: never[]) => unknown> = {
+ spine_loadSkeleton: () => {
+ if (!state.parses) return -1;
+ const handle = nextSkeleton++;
+ state.skeletons.push(handle);
+ return handle;
+ },
+ spine_unloadSkeleton: ((handle: number) => {
+ state.skeletons.splice(state.skeletons.indexOf(handle), 1);
+ }) as never,
+ spine_getLastError: () => 'the fake refused to parse',
+ spine_getAtlasPageCount: () => 0,
+ spine_createInstance: () => {
+ const id = nextInstance++;
+ state.instances.push(id);
+ return id;
+ },
+ spine_destroyInstance: ((id: number) => {
+ state.instances.splice(state.instances.indexOf(id), 1);
+ }) as never,
+ spine_getMeshBatchCount: () => 0,
+ };
+ return {
+ cwrap: (name: string) => exports[name] ?? (() => 0),
+ _malloc: () => 0,
+ _free: () => {},
+ HEAPU8: new Uint8Array(4096),
+ HEAPF32: new Float32Array(1024),
+ HEAP32: new Int32Array(1024),
+ HEAPU32: new Uint32Array(1024),
+ HEAPU16: new Uint16Array(1024),
+ } as never;
+}
+
+/** A manager over two faked runtimes, and the state each of them holds. */
+function managerWithVersions() {
+ const runtimes = {
+ '4.1': { parses: true, skeletons: [] as number[], instances: [] as number[] },
+ '4.2': { parses: true, skeletons: [] as number[], instances: [] as number[] },
+ };
+ const factories = new Map<SpineVersion, SpineModuleFactory>([
+ ['4.1', (async () => fakeModule(runtimes['4.1'])) as never],
+ ['4.2', (async () => fakeModule(runtimes['4.2'])) as never],
+ ]);
+ const core = {} as never;
+ return { manager: new SpineManager(core, factories), runtimes };
+}
+
+const NO_TEXTURES = new Map<string, { glId: number; w: number; h: number }>();
+const REGISTRY = {} as never;
+
+async function bind(
+ manager: SpineManager, entity: Entity, version: string, era: string,
+): Promise<SpineVersion | null> {
+ return manager.loadEntity(entity, skeletonOf(version), '', NO_TEXTURES, REGISTRY, era);
+}
+
+describe('one entity is posed by at most one runtime', () => {
+ it('moving to another spine version leaves nothing behind in the old one', async () => {
+ // The runtime it moves TO can only remove its own entities, and the one
+ // it came from is never told: what stays there is posed and submitted
+ // every frame, and no despawn ever reaches it.
+ const { manager, runtimes } = managerWithVersions();
+ const entity = 7 as Entity;
+
+ expect(await bind(manager, entity, '4.1', 'hero#1')).toBe('4.1');
+ expect(runtimes['4.1'].instances).toHaveLength(1);
+
+ expect(await bind(manager, entity, '4.2', 'hero#2')).toBe('4.2');
+
+ expect(runtimes['4.1'].instances, 'the instance the old runtime kept posing').toEqual([]);
+ expect(runtimes['4.1'].skeletons, 'the skeleton nobody could unload').toEqual([]);
+ expect(runtimes['4.2'].instances).toHaveLength(1);
+ });
+
+ it('a despawn after a version change reaches every runtime that had it', async () => {
+ const { manager, runtimes } = managerWithVersions();
+ const entity = 7 as Entity;
+ await bind(manager, entity, '4.1', 'hero#1');
+ await bind(manager, entity, '4.2', 'hero#2');
+
+ manager.removeEntity(entity);
+
+ expect(runtimes['4.1'].instances).toEqual([]);
+ expect(runtimes['4.2'].instances).toEqual([]);
+ expect([...manager.boundEntities()]).toEqual([]);
+ });
+});
+
+describe('replacing a binding is commit-after-success', () => {
+ it('a reload whose skeleton will not parse leaves the entity playing', async () => {
+ // Preparing an asset already works this way: a failed preparation leaves
+ // the era that is published alone. A runtime binding that destroys first
+ // has already thrown away what it was going to fall back to.
+ const { manager, runtimes } = managerWithVersions();
+ const entity = 7 as Entity;
+ await bind(manager, entity, '4.2', 'hero#1');
+ const posing = [...runtimes['4.2'].instances];
+
+ runtimes['4.2'].parses = false;
+ expect(await bind(manager, entity, '4.2', 'hero#2')).toBeNull();
+
+ expect(runtimes['4.2'].instances, 'the entity stopped playing').toEqual(posing);
+ expect(runtimes['4.2'].skeletons, 'the era it was posing was retired').toHaveLength(1);
+ expect(manager.getEntityVersion(entity)).toBe('4.2');
+ });
+
+ it('a failed move to another version stays on the one that works', async () => {
+ const { manager, runtimes } = managerWithVersions();
+ const entity = 7 as Entity;
+ await bind(manager, entity, '4.1', 'hero#1');
+ const posing = [...runtimes['4.1'].instances];
+
+ runtimes['4.2'].parses = false;
+ expect(await bind(manager, entity, '4.2', 'hero#2')).toBeNull();
+
+ expect(runtimes['4.1'].instances, 'the entity was left with no runtime at all').toEqual(posing);
+ expect(runtimes['4.2'].instances, 'half a binding in the runtime that failed').toEqual([]);
+ expect(runtimes['4.2'].skeletons).toEqual([]);
+ expect(manager.getEntityVersion(entity)).toBe('4.1');
+ });
+
+ it('the frame pass poses it once, from one runtime', async () => {
+ const { manager, runtimes } = managerWithVersions();
+ const entity = 7 as Entity;
+ await bind(manager, entity, '4.1', 'hero#1');
+ await bind(manager, entity, '4.2', 'hero#2');
+
+ manager.updateAnimations(1 / 60);
+
+ expect(runtimes['4.1'].instances.length + runtimes['4.2'].instances.length,
+ 'two runtimes each posing their own copy of one entity').toBe(1);
+ });
+});