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): a shared skeleton is shared by era, not by ref

esengine7fcb63bbbfeb
diff --git a/sdk/etc/spine.api.md b/sdk/etc/spine.api.md
index 66468adcc..06a8059db 100644
--- a/sdk/etc/spine.api.md
+++ b/sdk/etc/spine.api.md
@@ -23,7 +23,7 @@ getPathConstraintMix: (entity: Entity, name: string) => PathMixData | null
getSkins: (entity: Entity) => string[]
getTransformConstraintMix: (entity: Entity, name: string) => TransformMixData | null
listConstraints: (entity: Entity) => ConstraintList | null
-loadEntity: (entity: Entity, skelData: Uint8Array | string, atlasText: string, textures: Map<string, { glId: number; w: number; h: number; }>, isBinary: boolean, assetKey?: string) => boolean
+loadEntity: (entity: Entity, skelData: Uint8Array | string, atlasText: string, textures: Map<string, { glId: number; w: number; h: number; }>, isBinary: boolean, era?: string) => boolean
removeEntity: (entity: Entity) => void
setAnimation: (entity: Entity, animation: string, loop: boolean) => void
setAttachment: (entity: Entity, slotName: string, attachmentName: string) => boolean
@@ -115,7 +115,7 @@ getTransformConstraintMix: (entity: Entity, name: string) => TransformMixData |
hasInstance: (entity: Entity) => boolean
hasModuleBackend: (version: SpineVersion) => boolean
listConstraints: (entity: Entity) => ConstraintList | null
-loadEntity: (entity: Entity, skelData: Uint8Array | string, atlasText: string, textures: Map<string, { glId: number; w: number; h: number; }>, _registry: CppRegistry, assetKey?: string) => Promise<SpineVersion | null>
+loadEntity: (entity: Entity, skelData: Uint8Array | string, atlasText: string, textures: Map<string, { glId: number; w: number; h: number; }>, _registry: CppRegistry, era?: string) => Promise<SpineVersion | null>
removeEntity: (entity: Entity) => void
setAnimation: (entity: Entity, animation: string, loop: boolean) => void
setAttachment: (entity: Entity, slotName: string, attachmentName: string) => boolean
@@ -219,7 +219,7 @@ mixY: number
## loadSpineAssets — function @experimental
```
-(module: ESEngineModule | null, source: RuntimeAssetSource, spineManager: SpineManager | null | undefined, spinePairs: ReadonlyArray<{ skeleton: string; atlas: string; }>, transcoderProvider?: TranscoderProvider): Promise<Map<string, SpineAssetInfo>>
+(module: ESEngineModule | null, source: RuntimeAssetSource, spineManager: SpineManager | null | undefined, spinePairs: ReadonlyArray<{ skeleton: string; atlas: string; }>, transcoderProvider?: TranscoderProvider, owner?: SpineAssetOwner): Promise<Map<string, SpineAssetInfo>>
```
## loadSpineSceneEntities — function @experimental
diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.ts
index 6d54417d3..94f0a3b03 100644
--- a/sdk/src/runtime/runtimeLoader.ts
+++ b/sdk/src/runtime/runtimeLoader.ts
@@ -339,8 +339,12 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promis
const mod = await host.acquire('basis');
return mod ? transcoderFromModule(mod as unknown as BasisWasmModule) : null;
};
+ // Prepared by the realm, owned by the scene: the receipts join the scope
+ // this scene gives back, and a second scene of one spine asset joins its era
+ // instead of uploading its pages again.
const spineAssetInfo = app.sideModules
- ? await loadSpineAssets(module, source, spineManager, discovered.spines, transcoderProvider)
+ ? await loadSpineAssets(module, source, spineManager, discovered.spines, transcoderProvider,
+ { assets: sceneAssets, scope: assetResult.scope })
: new Map<string, SpineAssetInfo>();
// DragonBones, the same two phases. The manager is acquired only when the
diff --git a/sdk/src/spine/ModuleBackend.ts b/sdk/src/spine/ModuleBackend.ts
index 55b298850..2ad30de05 100644
--- a/sdk/src/spine/ModuleBackend.ts
+++ b/sdk/src/spine/ModuleBackend.ts
@@ -17,17 +17,17 @@ interface EntityInfo {
layer: number;
timeScale: number;
playing: boolean;
- /** Dedup key (asset ref). Entities sharing a key share one loaded skeleton. */
- assetKey?: string;
+ /** Which era of which asset. Entities sharing it share one loaded skeleton. */
+ era?: string;
}
export class ModuleBackend {
private controller_: SpineModuleController;
private entities_: Map<Entity, EntityInfo> = new Map();
private disabledEntities_: Set<Entity> = new Set();
- // assetKey -> the one loaded skeleton (skeletonData + atlas + page textures)
- // shared by every entity of that asset; refcounted so it unloads when the
- // last instance is removed. Without a key, an entity falls back to its own
+ // era -> the one loaded skeleton (skeletonData + atlas + page textures)
+ // shared by every entity of that era; refcounted so it unloads when the last
+ // instance is removed. Without one, an entity falls back to its own
// per-entity skeleton (the pre-dedup behaviour).
private skeletons_: Map<string, { skelHandle: number; refcount: number }> = new Map();
@@ -49,7 +49,13 @@ export class ModuleBackend {
atlasText: string,
textures: Map<string, { glId: number; w: number; h: number }>,
isBinary: boolean,
- assetKey?: string,
+ /**
+ * The identity of the prepared asset — its ERA, never merely its ref. A
+ * ref would find the skeleton parsed from the bytes BEFORE an update
+ * still referenced by another entity, and hand it back: every entity
+ * reloads, none of them onto the new content, and nothing reports it.
+ */
+ 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
@@ -57,7 +63,7 @@ export class ModuleBackend {
if (this.entities_.has(entity)) this.removeEntity(entity);
let skelHandle: number;
- const shared = assetKey !== undefined ? this.skeletons_.get(assetKey) : undefined;
+ 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;
@@ -76,12 +82,12 @@ export class ModuleBackend {
this.controller_.setAtlasPageTexture(skelHandle, i, tex.glId, tex.w, tex.h);
}
}
- if (assetKey !== undefined) this.skeletons_.set(assetKey, { skelHandle, refcount: 1 });
+ if (era !== undefined) this.skeletons_.set(era, { skelHandle, refcount: 1 });
}
const instanceId = this.controller_.createInstance(skelHandle);
this.entities_.set(entity, {
- skelHandle, instanceId, assetKey,
+ skelHandle, instanceId, era,
skeletonScale: 1, flipX: false, flipY: false, layer: 0, timeScale: 1, playing: true,
});
return true;
@@ -264,12 +270,12 @@ export class ModuleBackend {
/** Drop one reference to an entity's skeleton; unload it only when shared
* refcount hits zero (or immediately for an un-keyed per-entity skeleton). */
private releaseSkeleton_(info: EntityInfo): void {
- if (info.assetKey !== undefined) {
- const shared = this.skeletons_.get(info.assetKey);
+ if (info.era !== undefined) {
+ const shared = this.skeletons_.get(info.era);
if (shared) {
if (--shared.refcount <= 0) {
this.controller_.unloadSkeleton(shared.skelHandle);
- this.skeletons_.delete(info.assetKey);
+ this.skeletons_.delete(info.era);
}
return;
}
@@ -286,7 +292,7 @@ export class ModuleBackend {
const handles = new Set<number>();
for (const entry of this.skeletons_.values()) handles.add(entry.skelHandle);
for (const info of this.entities_.values()) {
- if (info.assetKey === undefined) handles.add(info.skelHandle);
+ if (info.era === undefined) handles.add(info.skelHandle);
}
for (const h of handles) this.controller_.unloadSkeleton(h);
this.entities_.clear();
diff --git a/sdk/src/spine/SpineManager.ts b/sdk/src/spine/SpineManager.ts
index beab9896d..2569b90a0 100644
--- a/sdk/src/spine/SpineManager.ts
+++ b/sdk/src/spine/SpineManager.ts
@@ -69,7 +69,8 @@ export class SpineManager {
atlasText: string,
textures: Map<string, { glId: number; w: number; h: number }>,
_registry: CppRegistry,
- assetKey?: string,
+ /** The prepared asset's ERA — see ModuleBackend.loadEntity. */
+ era?: string,
): Promise<SpineVersion | null> {
const version = typeof skelData === 'string'
? SpineManager.detectVersionJson(skelData)
@@ -87,7 +88,7 @@ export class SpineManager {
}
const isBinary = skelData instanceof Uint8Array;
- const ok = backend.loadEntity(entity, skelData, atlasText, textures, isBinary, assetKey);
+ const ok = backend.loadEntity(entity, skelData, atlasText, textures, isBinary, era);
if (!ok) {
log.error('spine', `Failed to load entity ${entity} into backend ${version}`);
return null;
diff --git a/sdk/src/spine/loadSpineScene.ts b/sdk/src/spine/loadSpineScene.ts
index c77064e08..b4c37b3e0 100644
--- a/sdk/src/spine/loadSpineScene.ts
+++ b/sdk/src/spine/loadSpineScene.ts
@@ -26,6 +26,8 @@ import { SpineManager, type SpineVersion } from './SpineManager';
import { prepareSpine, spinePairKey, type SpineAssetValue, type SpineIO } from './prepareSpine';
import { createAtlasPageTexture, type RuntimeAssetSource } from '../runtime/runtimeAssets';
import type { BasisTranscoder } from '../asset/compressed';
+import type { AssetsData } from '../asset/AssetPlugin';
+import type { AssetScope } from '../asset/AssetLease';
/**
* The in-place editable spine props from a SpineAnimation component's data — the
@@ -61,13 +63,34 @@ export type TranscoderProvider = () => Promise<BasisTranscoder | null>;
/** The opaque C++ registry handle SpineManager.loadEntity expects (app.world.getCppRegistry()). */
type CppRegistry = Parameters<SpineManager['loadEntity']>[4];
-/** One prepared pair, plus the runtime version its skeleton document names. */
-export type SpineAssetInfo = SpineAssetValue & { version: SpineVersion | null };
+/** One prepared pair: what it is, the runtime version its skeleton names, and
+ * the identity of THIS preparation of it — see {@link SpineAssetInfo.era}. */
+export type SpineAssetInfo = SpineAssetValue & {
+ version: SpineVersion | null;
+ /**
+ * Which generation of the pair this is. Entities sharing it share one native
+ * skeleton; entities on different ones do not, which is what makes an update
+ * actually load the new bytes instead of finding the old skeleton still
+ * referenced and handing it back.
+ */
+ era: string;
+};
/**
* Phase 1 — fetch + decode each spine pair's skeleton/atlas/textures and detect
* its runtime version. Keyed by `skeletonRef:atlasRef` for {@link applySpineEntities}.
*/
+/**
+ * Who prepares the pairs, and who owns what the preparation takes. With one,
+ * two scenes of a spine asset share its era — one page upload, one native
+ * skeleton — and the receipts are the scene's. Without one the same algorithm
+ * runs over a host's own file access, and what it uploads is the host's.
+ */
+export interface SpineAssetOwner {
+ assets: AssetsData;
+ scope: AssetScope;
+}
+
export async function loadSpineAssets(
/** The wasm engine module, or null on a core with no heap — the atlas page upload
* goes through the ResourceManager's byte path there. */
@@ -76,21 +99,36 @@ export async function loadSpineAssets(
spineManager: SpineManager | null | undefined,
spinePairs: ReadonlyArray<{ skeleton: string; atlas: string }>,
transcoderProvider?: TranscoderProvider,
+ owner?: SpineAssetOwner,
): Promise<Map<string, SpineAssetInfo>> {
const assetInfoMap = new Map<string, SpineAssetInfo>();
for (const pair of spinePairs) {
try {
- const value = await prepareSpine(
- hostSpineIo(module, source, pair.atlas, transcoderProvider),
- pair.skeleton, pair.atlas,
- );
+ const key = spinePairKey(pair.skeleton, pair.atlas);
+ let value: SpineAssetValue;
+ let era: string;
+ if (owner) {
+ // The realm's era: a second scene of this pair joins it rather
+ // than uploading its pages again, and the receipt is the
+ // scene's, so the pages go back when the scene does.
+ const lease = await owner.assets.acquireSpine(pair.skeleton, pair.atlas);
+ owner.scope.add(lease);
+ value = lease.value;
+ era = `${key}#${lease.generation}`;
+ } else {
+ value = await prepareSpine(
+ hostSpineIo(module, source, pair.atlas, transcoderProvider),
+ pair.skeleton, pair.atlas,
+ );
+ era = `${key}#${++preparations}`;
+ }
const version = spineManager
? (typeof value.skelData === 'string'
? SpineManager.detectVersionJson(value.skelData)
: SpineManager.detectVersion(value.skelData))
: null;
- assetInfoMap.set(spinePairKey(pair.skeleton, pair.atlas), { ...value, version });
+ assetInfoMap.set(key, { ...value, version, era });
} catch (err) {
log.warn('runtime', `Failed to load spine asset: skel=${pair.skeleton} atlas=${pair.atlas}`, err);
}
@@ -98,6 +136,13 @@ export async function loadSpineAssets(
return assetInfoMap;
}
+/**
+ * How many preparations this process has run. An id, not state: what it has to
+ * be is distinct, so that entities of one preparation share a skeleton and
+ * entities of two never do.
+ */
+let preparations = 0;
+
/**
* A host's own file access as a spine transport — the editor, and any target
* driving this loader without an asset layer. Same algorithm as the asset
@@ -169,8 +214,7 @@ export async function applySpineEntities(opts: {
if (entity === undefined) continue;
await spineManager.loadEntity(
- entity, info.skelData, info.atlasText, info.textures, registry,
- `${skelRef}:${atlasRef}`);
+ entity, info.skelData, info.atlasText, info.textures, registry, info.era);
spineManager.setEntityProps(entity, spineEntityProps(comp.data as Record<string, unknown>));
const skin = comp.data.skin as string;
diff --git a/sdk/tests/spine-apply-routing.test.ts b/sdk/tests/spine-apply-routing.test.ts
index 922a193c7..6bac46acf 100644
--- a/sdk/tests/spine-apply-routing.test.ts
+++ b/sdk/tests/spine-apply-routing.test.ts
@@ -51,12 +51,16 @@ describe('applySpineEntities routes every version to the SpineManager (S3)', ()
entityMap: new Map([[1, entity]]),
registry: {} as never,
assetInfo: new Map([['hero.skel:hero.atlas', {
- version: '4.2' as const, skelData: new Uint8Array(), atlasText: '', textures: new Map(),
+ version: '4.2' as const, era: 'hero.skel:hero.atlas#7', isBinary: true,
+ skelData: new Uint8Array(), atlasText: '', textures: new Map(),
}]]),
});
expect(manager.loadEntity).toHaveBeenCalledTimes(1);
+ // The ERA, not the ref: two entities share a native skeleton only while
+ // they are on the same generation of the asset.
expect(manager.loadEntity).toHaveBeenCalledWith(
- entity, expect.anything(), '', expect.anything(), expect.anything(), 'hero.skel:hero.atlas');
+ entity, expect.anything(), '', expect.anything(), expect.anything(),
+ 'hero.skel:hero.atlas#7');
expect(manager.setAnimation).toHaveBeenCalledWith(entity, 'walk', true);
});
diff --git a/sdk/tests/spine-dedup.test.ts b/sdk/tests/spine-dedup.test.ts
index 06bbb54cd..af557b062 100644
--- a/sdk/tests/spine-dedup.test.ts
+++ b/sdk/tests/spine-dedup.test.ts
@@ -6,10 +6,13 @@
* the same asset (keyed) and refcounts it, instead of loading a fresh
* skeletonData per entity. Without a key it falls back to per-entity.
*/
-import { describe, it, expect, vi } from 'vitest';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ModuleBackend } from '../src/spine/ModuleBackend';
import type { SpineModuleController } from '../src/spine/SpineController';
import type { Entity } from '../src/types';
+import { defineComponent, clearUserComponents } from '../src/ecs/component';
+import { applySpineEntities } from '../src/spine/loadSpineScene';
+import type { SceneData } from '../src/scene/scene';
function makeController() {
let nextSkel = 1, nextInst = 100;
@@ -99,3 +102,98 @@ describe('ModuleBackend skeleton dedup (S4-A)', () => {
expect(c.destroyInstance).toHaveBeenCalledTimes(3); // three instances
});
});
+
+
+describe('a hot swap loads the new bytes, once', () => {
+ const COMP = 'SpineHotSwap_Spine';
+ beforeEach(() => {
+ clearUserComponents();
+ defineComponent(COMP, { skeleton: '', atlas: '' }, {
+ skeletalFields: { skeletonField: 'skeleton', atlasField: 'atlas' },
+ });
+ });
+
+ /** Two entities of ONE pair — what makes the shared skeleton shared. */
+ const SCENE = {
+ version: 1,
+ entities: [1, 2].map((id) => ({
+ id,
+ components: [{ type: COMP, data: { skeleton: 'hero.skel', atlas: 'hero.atlas' } }],
+ })),
+ } as unknown as SceneData;
+
+ /** A manager that is the real backend, so what is asserted is what the
+ * native side was actually told. */
+ function managerOver(backend: ModuleBackend) {
+ return {
+ loadEntity: vi.fn(async (
+ entity: Entity, skelData: Uint8Array | string, atlasText: string,
+ textures: Map<string, { glId: number; w: number; h: number }>,
+ _registry: unknown, era?: string,
+ ) => {
+ backend.loadEntity(entity, skelData, atlasText, textures, true, era);
+ return '4.2';
+ }),
+ setEntityProps: vi.fn(), setSkin: vi.fn(), setAnimation: vi.fn(),
+ };
+ }
+
+ function generation(era: string) {
+ return new Map([['hero.skel:hero.atlas', {
+ version: '4.2' as const, era, isBinary: true,
+ skelData: new Uint8Array([era.length]), atlasText: era, textures: new Map(),
+ }]]);
+ }
+
+ it('does not reuse the skeleton built from the era before it', async () => {
+ // Two entities share one skeleton, so the update removes one reference,
+ // finds the other still holding it, and hands back the skeleton the OLD
+ // bytes were parsed into — with nothing reporting a failure.
+ const controller = makeController();
+ const backend = new ModuleBackend(controller as never);
+ const spineManager = managerOver(backend);
+ const entityMap = new Map([[1, 11 as Entity], [2, 12 as Entity]]);
+ const apply = (era: string) => applySpineEntities({
+ spineManager: spineManager as never,
+ sceneData: SCENE, entityMap, registry: {} as never, assetInfo: generation(era) as never,
+ });
+
+ await apply('hero.skel:hero.atlas#1');
+ expect(controller.loadSkeleton).toHaveBeenCalledTimes(1);
+
+ await apply('hero.skel:hero.atlas#2');
+
+ expect(controller.loadSkeleton, 'the new era was never parsed').toHaveBeenCalledTimes(2);
+ expect(controller.unloadSkeleton, 'the era nobody is left in must go')
+ .toHaveBeenCalledTimes(1);
+ expect(controller.createInstance, 'one instance per entity per era').toHaveBeenCalledTimes(4);
+ });
+
+ it('the era its last entity leaves is the one that goes', async () => {
+ // Old and new coexist while a holder of each is alive: the first entity
+ // moves to the new era, the second is still posing the old one.
+ const controller = makeController();
+ const backend = new ModuleBackend(controller as never);
+ const spineManager = managerOver(backend);
+ const both = new Map([[1, 11 as Entity], [2, 12 as Entity]]);
+ await applySpineEntities({
+ spineManager: spineManager as never,
+ sceneData: SCENE, entityMap: both, registry: {} as never,
+ assetInfo: generation('era#1') as never,
+ });
+
+ // Only entity 1 moves on.
+ await applySpineEntities({
+ spineManager: spineManager as never,
+ sceneData: SCENE, entityMap: new Map([[1, 11 as Entity]]), registry: {} as never,
+ assetInfo: generation('era#2') as never,
+ });
+
+ expect(controller.unloadSkeleton, 'the old era was pulled from under entity 2')
+ .not.toHaveBeenCalled();
+
+ backend.removeEntity(12 as Entity);
+ expect(controller.unloadSkeleton, 'the old era outlived its last entity')
+ .toHaveBeenCalledTimes(1);
+ });
+});