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.

perf(spine): dedup shared skeletons in the side-module backend (S4-A)

esenginead4ec5652cc7
diff --git a/sdk/src/spine/ModuleBackend.ts b/sdk/src/spine/ModuleBackend.ts
index adb3d4a6e..3b2cb7732 100644
--- a/sdk/src/spine/ModuleBackend.ts
+++ b/sdk/src/spine/ModuleBackend.ts
@@ -12,12 +12,19 @@ interface EntityInfo {
flipX: boolean;
flipY: boolean;
layer: number;
+ /** Dedup key (asset ref). Entities sharing a key share one loaded skeleton. */
+ assetKey?: 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
+ // per-entity skeleton (the pre-dedup behaviour).
+ private skeletons_: Map<string, { skelHandle: number; refcount: number }> = new Map();
constructor(controller: SpineModuleController) {
this.controller_ = controller;
@@ -37,25 +44,34 @@ export class ModuleBackend {
atlasText: string,
textures: Map<string, { glId: number; w: number; h: number }>,
isBinary: boolean,
+ assetKey?: string,
): boolean {
- const 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);
+ let skelHandle: number;
+ const shared = assetKey !== undefined ? this.skeletons_.get(assetKey) : 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 (assetKey !== undefined) this.skeletons_.set(assetKey, { skelHandle, refcount: 1 });
}
const instanceId = this.controller_.createInstance(skelHandle);
this.entities_.set(entity, {
- skelHandle, instanceId,
+ skelHandle, instanceId, assetKey,
skeletonScale: 1, flipX: false, flipY: false, layer: 0,
});
return true;
@@ -222,17 +238,41 @@ export class ModuleBackend {
const info = this.entities_.get(entity);
if (!info) return;
this.controller_.destroyInstance(info.instanceId);
- this.controller_.unloadSkeleton(info.skelHandle);
+ this.releaseSkeleton_(info);
this.entities_.delete(entity);
this.disabledEntities_.delete(entity);
}
+ /** 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 (shared) {
+ if (--shared.refcount <= 0) {
+ this.controller_.unloadSkeleton(shared.skelHandle);
+ this.skeletons_.delete(info.assetKey);
+ }
+ return;
+ }
+ }
+ this.controller_.unloadSkeleton(info.skelHandle);
+ }
+
shutdown(): void {
for (const info of this.entities_.values()) {
this.controller_.destroyInstance(info.instanceId);
- this.controller_.unloadSkeleton(info.skelHandle);
}
+ // Unload each unique skeleton once: shared ones via skeletons_, plus any
+ // un-keyed per-entity skeletons.
+ 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);
+ }
+ for (const h of handles) this.controller_.unloadSkeleton(h);
this.entities_.clear();
this.disabledEntities_.clear();
+ this.skeletons_.clear();
}
}
diff --git a/sdk/src/spine/SpineManager.ts b/sdk/src/spine/SpineManager.ts
index dc5010dcc..b519df51c 100644
--- a/sdk/src/spine/SpineManager.ts
+++ b/sdk/src/spine/SpineManager.ts
@@ -45,6 +45,7 @@ export class SpineManager {
atlasText: string,
textures: Map<string, { glId: number; w: number; h: number }>,
_registry: CppRegistry,
+ assetKey?: string,
): Promise<SpineVersion | null> {
const version = typeof skelData === 'string'
? SpineManager.detectVersionJson(skelData)
@@ -62,7 +63,7 @@ export class SpineManager {
}
const isBinary = skelData instanceof Uint8Array;
- const ok = backend.loadEntity(entity, skelData, atlasText, textures, isBinary);
+ const ok = backend.loadEntity(entity, skelData, atlasText, textures, isBinary, assetKey);
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 8a7e88dcd..49e0b03d7 100644
--- a/sdk/src/spine/loadSpineScene.ts
+++ b/sdk/src/spine/loadSpineScene.ts
@@ -139,7 +139,9 @@ export async function applySpineEntities(opts: {
const entity = entityMap.get(sceneEntity.id);
if (entity === undefined) continue;
- await spineManager.loadEntity(entity, info.skelData, info.atlasText, info.textures, registry);
+ await spineManager.loadEntity(
+ entity, info.skelData, info.atlasText, info.textures, registry,
+ `${skelRef}:${atlasRef}`);
spineManager.setEntityProps(entity, {
skeletonScale: (comp.data.skeletonScale as number) ?? 1,
diff --git a/sdk/tests/spine-apply-routing.test.ts b/sdk/tests/spine-apply-routing.test.ts
index 085d6901b..af54b1753 100644
--- a/sdk/tests/spine-apply-routing.test.ts
+++ b/sdk/tests/spine-apply-routing.test.ts
@@ -54,7 +54,7 @@ describe('applySpineEntities routes every version to the SpineManager (S3)', ()
});
expect(manager.loadEntity).toHaveBeenCalledTimes(1);
expect(manager.loadEntity).toHaveBeenCalledWith(
- entity, expect.anything(), '', expect.anything(), expect.anything());
+ entity, expect.anything(), '', expect.anything(), expect.anything(), 'hero.skel:hero.atlas');
expect(manager.setAnimation).toHaveBeenCalledWith(entity, 'walk', true);
});
diff --git a/sdk/tests/spine-dedup.test.ts b/sdk/tests/spine-dedup.test.ts
new file mode 100644
index 000000000..47caa1d5b
--- /dev/null
+++ b/sdk/tests/spine-dedup.test.ts
@@ -0,0 +1,73 @@
+/**
+ * @file spine-dedup.test.ts
+ * @brief S4-A: ModuleBackend shares one loaded skeleton across every entity of
+ * 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 { ModuleBackend } from '../src/spine/ModuleBackend';
+import type { SpineModuleController } from '../src/spine/SpineController';
+import type { Entity } from '../src/types';
+
+function makeController() {
+ let nextSkel = 1, nextInst = 100;
+ return {
+ loadSkeleton: vi.fn(() => nextSkel++),
+ getLastError: vi.fn(() => ''),
+ getAtlasPageCount: vi.fn(() => 0),
+ getAtlasPageTextureName: vi.fn(() => ''),
+ setAtlasPageTexture: vi.fn(),
+ createInstance: vi.fn(() => nextInst++),
+ destroyInstance: vi.fn(),
+ unloadSkeleton: vi.fn(),
+ } as unknown as SpineModuleController & Record<string, ReturnType<typeof vi.fn>>;
+}
+
+const NO_TEX = new Map<string, { glId: number; w: number; h: number }>();
+
+function load(b: ModuleBackend, id: number, key?: string) {
+ b.loadEntity(id as Entity, new Uint8Array(), '', NO_TEX, true, key);
+}
+
+describe('ModuleBackend skeleton dedup (S4-A)', () => {
+ it('shares one skeleton across entities with the same asset key', () => {
+ const c = makeController();
+ const b = new ModuleBackend(c as never);
+ load(b, 1, 'hero');
+ load(b, 2, 'hero');
+ expect(c.loadSkeleton).toHaveBeenCalledTimes(1); // one skeletonData
+ expect(c.createInstance).toHaveBeenCalledTimes(2); // two instances
+ });
+
+ it('unloads the shared skeleton only when the last instance is removed', () => {
+ const c = makeController();
+ const b = new ModuleBackend(c as never);
+ load(b, 1, 'hero');
+ load(b, 2, 'hero');
+
+ b.removeEntity(1 as Entity);
+ expect(c.unloadSkeleton).not.toHaveBeenCalled(); // entity 2 still holds it
+
+ b.removeEntity(2 as Entity);
+ expect(c.unloadSkeleton).toHaveBeenCalledTimes(1); // now released
+ });
+
+ it('loads a fresh skeleton per entity when no asset key is given (legacy)', () => {
+ const c = makeController();
+ const b = new ModuleBackend(c as never);
+ load(b, 1);
+ load(b, 2);
+ expect(c.loadSkeleton).toHaveBeenCalledTimes(2);
+ });
+
+ it('shutdown unloads each unique skeleton once and destroys every instance', () => {
+ const c = makeController();
+ const b = new ModuleBackend(c as never);
+ load(b, 1, 'hero');
+ load(b, 2, 'hero');
+ load(b, 3, 'villain');
+ b.shutdown();
+ expect(c.unloadSkeleton).toHaveBeenCalledTimes(2); // hero + villain, once each
+ expect(c.destroyInstance).toHaveBeenCalledTimes(3); // three instances
+ });
+});