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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(sdk): entities, instances and shared skeletons for DragonBones
esengine0edd8eda5a9c
diff --git a/sdk/src/dragonbones/DragonBonesManager.ts b/sdk/src/dragonbones/DragonBonesManager.tsnew file mode 100644index 000000000..ed3bff8f9--- /dev/null+++ b/sdk/src/dragonbones/DragonBonesManager.ts@@ -0,0 +1,229 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file dragonbones/DragonBonesManager.ts+ * @brief Entities, their armature instances, and the skeletons they share.+ *+ * @details ONE class, where Spine has two. Its Manager exists to route an entity+ * to the backend for ITS Spine version, because five vendored runtimes+ * ship side by side. DragonBones' format is frozen and there is one+ * runtime, so that routing layer would have nothing to route — mirroring+ * the split here would be importing someone else's constraint.+ *+ * Skeletons are shared and refcounted. Ten entities of the same armature+ * parse the file once and hold one atlas between them; the last one out+ * unloads it. An entity given no asset key gets its own, which is the+ * honest fallback for a caller that cannot say when two are the same.+ */+import type { Entity } from '../types';+import { submitEntityMeshes, type SkeletalSubmitCore } from '../skeletal/submitMeshes';+import type { SkeletalBounds } from '../skeletal/types';+import { DragonBonesModuleController } from './DragonBonesController';+import { log } from '../logger';++/** How one entity's armature is posed and drawn. */+interface EntityInfo {+ skeletonHandle: number;+ instanceId: number;+ skeletonScale: number;+ flipX: boolean;+ flipY: boolean;+ layer: number;+ timeScale: number;+ /** Set when the skeleton is shared; absent means this entity owns its own. */+ assetKey?: string;+}++export interface DragonBonesEntityOptions {+ armature: string;+ /** Identifies the loaded file, so entities of one asset share a skeleton. */+ assetKey?: string;+ skeletonScale?: number;+ flipX?: boolean;+ flipY?: boolean;+ layer?: number;+ animation?: string;+ loop?: boolean;+}++export class DragonBonesManager {+ private readonly controller_: DragonBonesModuleController;+ private readonly entities_ = new Map<Entity, EntityInfo>();+ private readonly disabled_ = new Set<Entity>();+ private readonly skeletons_ = new Map<string, { handle: number; refcount: number }>();++ constructor(controller: DragonBonesModuleController) {+ this.controller_ = controller;+ }++ get controller(): DragonBonesModuleController {+ return this.controller_;+ }++ // — Skeletons ————————————————————————————————————————————————————————————++ /**+ * Parse a file once per `assetKey`, or every time when none is given.+ * Returns -1 on failure, with the reason on the controller.+ */+ loadSkeleton(skeletonData: Uint8Array | string, atlasJson: string, assetKey?: string): number {+ if (assetKey !== undefined) {+ const shared = this.skeletons_.get(assetKey);+ if (shared) return shared.handle;+ }+ const handle = this.controller_.loadSkeleton(skeletonData, atlasJson);+ if (handle < 0) {+ log.warn('dragonbones', `loadSkeleton failed: ${this.controller_.getLastError()}`);+ return -1;+ }+ if (assetKey !== undefined) this.skeletons_.set(assetKey, { handle, refcount: 0 });+ return handle;+ }++ /** Bind the uploaded atlas page; safe after instances exist. */+ setAtlasTexture(skeletonHandle: number, textureId: number): void {+ this.controller_.setAtlasTexture(skeletonHandle, textureId);+ }++ getArmatures(skeletonHandle: number): string[] {+ return this.controller_.getArmatures(skeletonHandle);+ }++ // — Entities —————————————————————————————————————————————————————————————++ /** Attach an armature to `entity`. Replaces whatever it had. */+ addEntity(entity: Entity, skeletonHandle: number, options: DragonBonesEntityOptions): boolean {+ this.removeEntity(entity);++ const instanceId = this.controller_.createInstance(skeletonHandle, options.armature);+ if (instanceId < 0) return false;++ if (options.assetKey !== undefined) {+ const shared = this.skeletons_.get(options.assetKey);+ if (shared) shared.refcount++;+ }++ const info: EntityInfo = {+ skeletonHandle,+ instanceId,+ skeletonScale: options.skeletonScale ?? 1,+ flipX: options.flipX ?? false,+ flipY: options.flipY ?? false,+ layer: options.layer ?? 0,+ timeScale: 1,+ assetKey: options.assetKey,+ };+ this.entities_.set(entity, info);++ if (options.animation) this.controller_.play(instanceId, options.animation, options.loop ?? true);+ return true;+ }++ removeEntity(entity: Entity): void {+ const info = this.entities_.get(entity);+ if (!info) return;+ this.controller_.destroyInstance(info.instanceId);+ this.releaseSkeleton_(info);+ this.entities_.delete(entity);+ this.disabled_.delete(entity);+ }++ hasInstance(entity: Entity): boolean {+ return this.entities_.has(entity);+ }++ /** A disabled entity keeps its instance but stops advancing and drawing. */+ setEnabled(entity: Entity, enabled: boolean): void {+ if (enabled) this.disabled_.delete(entity);+ else this.disabled_.add(entity);+ }++ setEntityProps(entity: Entity, props: Partial<Pick<EntityInfo, 'skeletonScale' | 'flipX' | 'flipY' | 'layer'>>): void {+ const info = this.entities_.get(entity);+ if (info) Object.assign(info, props);+ }++ // — Animation ————————————————————————————————————————————————————————————++ play(entity: Entity, animation: string, loop = true): boolean {+ const info = this.entities_.get(entity);+ return info ? this.controller_.play(info.instanceId, animation, loop) : false;+ }++ /** Crossfade in, which is where DragonBones puts what Spine keeps in a table. */+ fadeIn(entity: Entity, animation: string, fadeSeconds: number, loop = true): boolean {+ const info = this.entities_.get(entity);+ return info ? this.controller_.fadeIn(info.instanceId, animation, fadeSeconds, loop) : false;+ }++ stop(entity: Entity, animation = ''): void {+ const info = this.entities_.get(entity);+ if (info) this.controller_.stop(info.instanceId, animation);+ }++ setTimeScale(entity: Entity, scale: number): void {+ const info = this.entities_.get(entity);+ if (!info) return;+ info.timeScale = scale;+ this.controller_.setTimeScale(info.instanceId, scale);+ }++ getAnimations(entity: Entity): string[] {+ const info = this.entities_.get(entity);+ return info ? this.controller_.getAnimations(info.instanceId) : [];+ }++ getBounds(entity: Entity): SkeletalBounds | null {+ const info = this.entities_.get(entity);+ return info ? this.controller_.getBounds(info.instanceId) : null;+ }++ // — Frame ————————————————————————————————————————————————————————————————++ updateAnimations(dt: number): void {+ for (const [entity, info] of this.entities_) {+ if (this.disabled_.has(entity)) continue;+ this.controller_.update(info.instanceId, dt);+ }+ }++ submitMeshes(core: SkeletalSubmitCore, registry: unknown): void {+ for (const [entity, info] of this.entities_) {+ if (this.disabled_.has(entity)) continue;+ // False means the core cannot take geometry at all, so asking again for+ // the next entity would only repeat the same check.+ const accepted = submitEntityMeshes(core, registry, entity, info, cb =>+ this.controller_.forEachMeshBatch(info.instanceId, cb));+ if (!accepted) return;+ }+ }++ // — Teardown —————————————————————————————————————————————————————————————++ /** Drop every instance and skeleton. Idempotent, so a second call is a no-op. */+ dispose(): void {+ for (const info of this.entities_.values()) {+ this.controller_.destroyInstance(info.instanceId);+ }+ for (const shared of this.skeletons_.values()) {+ this.controller_.unloadSkeleton(shared.handle);+ }+ this.entities_.clear();+ this.disabled_.clear();+ this.skeletons_.clear();+ }++ /** One reference gone; a shared skeleton unloads when the last one does. */+ private releaseSkeleton_(info: EntityInfo): void {+ if (info.assetKey === undefined) {+ this.controller_.unloadSkeleton(info.skeletonHandle);+ return;+ }+ const shared = this.skeletons_.get(info.assetKey);+ if (!shared) return;+ if (--shared.refcount <= 0) {+ this.controller_.unloadSkeleton(shared.handle);+ this.skeletons_.delete(info.assetKey);+ }+ }+}diff --git a/sdk/src/dragonbones/index.ts b/sdk/src/dragonbones/index.tsindex 6b583ec5c..bc307c1c2 100644--- a/sdk/src/dragonbones/index.ts+++ b/sdk/src/dragonbones/index.ts@@ -7,3 +7,5 @@ export type {DragonBonesWrappedAPI,DragonBonesModuleFactory,} from './DragonBonesModuleLoader';+export { DragonBonesManager } from './DragonBonesManager';+export type { DragonBonesEntityOptions } from './DragonBonesManager';diff --git a/sdk/tests/dragonbones-manager.integration.test.ts b/sdk/tests/dragonbones-manager.integration.test.tsnew file mode 100644index 000000000..51720552f--- /dev/null+++ b/sdk/tests/dragonbones-manager.integration.test.ts@@ -0,0 +1,129 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// The manager against the real module. Its interesting behaviour is bookkeeping —+// who shares a skeleton, when the last reference drops it, what a disabled entity+// stops doing — and every one of those fails quietly: a leak shows up as memory,+// a double free as a crash three frames later, a missed disable as a thing that+// keeps animating. So they are asserted, not eyeballed.+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 { DragonBonesManager } from '../src/dragonbones/DragonBonesManager';+import { DragonBonesModuleController } from '../src/dragonbones/DragonBonesController';+import { wrapDragonBonesModule, type DragonBonesWasmModule } from '../src/dragonbones/DragonBonesModuleLoader';+import type { Entity } from '../src/types';++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);++const e = (n: number): Entity => n as unknown as Entity;++describe.skipIf(!HAS_ASSETS)('DragonBonesManager', () => {+ let raw: DragonBonesWasmModule;+ let manager: DragonBonesManager;++ beforeAll(async () => {+ const factory = (await import(DB_JS)).default as+ (a: { wasmBinary: Uint8Array }) => Promise<DragonBonesWasmModule>;+ raw = await factory({ wasmBinary: new Uint8Array(readFileSync(DB_WASM)) });+ });++ const fresh = (): DragonBonesManager =>+ new DragonBonesManager(new DragonBonesModuleController(raw, wrapDragonBonesModule(raw)));++ const load = (m: DragonBonesManager, key?: string): number =>+ m.loadSkeleton(new Uint8Array(readFileSync(SKE)), readFileSync(TEX, 'utf8'), key);++ it('parses a keyed file once, however many entities want it', () => {+ manager = fresh();+ const first = load(manager, 'dragonboy');+ const second = load(manager, 'dragonboy');+ expect(second).toBe(first);++ // No key means no sharing — the honest fallback when a caller cannot say+ // that two requests are for the same asset.+ const unkeyed = load(manager);+ expect(unkeyed).not.toBe(first);+ manager.dispose();+ });++ it('attaches an armature and refuses one the file does not hold', () => {+ manager = fresh();+ const handle = load(manager, 'dragonboy');+ manager.setAtlasTexture(handle, 3);++ expect(manager.addEntity(e(1), handle, { armature: 'Dragon', assetKey: 'dragonboy' })).toBe(true);+ expect(manager.hasInstance(e(1))).toBe(true);+ expect(manager.addEntity(e(2), handle, { armature: 'Nope', assetKey: 'dragonboy' })).toBe(false);+ expect(manager.hasInstance(e(2))).toBe(false);+ manager.dispose();+ });++ it('keeps a shared skeleton alive until its last entity leaves', () => {+ manager = fresh();+ const handle = load(manager, 'dragonboy');+ manager.setAtlasTexture(handle, 3);+ manager.addEntity(e(1), handle, { armature: 'Dragon', assetKey: 'dragonboy' });+ manager.addEntity(e(2), handle, { armature: 'Dragon', assetKey: 'dragonboy' });++ manager.removeEntity(e(1));+ // Still loaded: entity 2 holds the other reference. Asking the module is the+ // check that matters — an unloaded handle answers with no armatures.+ expect(manager.getArmatures(handle)).toEqual(['Dragon']);+ expect(manager.play(e(2), 'walk')).toBe(true);++ manager.removeEntity(e(2));+ expect(manager.getArmatures(handle)).toEqual([]);+ manager.dispose();+ });++ it('advances what is enabled and leaves the rest where it was', () => {+ manager = fresh();+ const handle = load(manager, 'dragonboy');+ manager.setAtlasTexture(handle, 3);+ manager.addEntity(e(1), handle, { armature: 'Dragon', assetKey: 'dragonboy', animation: 'walk' });+ manager.addEntity(e(2), handle, { armature: 'Dragon', assetKey: 'dragonboy', animation: 'walk' });+ manager.updateAnimations(1 / 60);++ manager.setEnabled(e(2), false);+ const frozen = manager.getBounds(e(2));+ for (let i = 0; i < 20; i++) manager.updateAnimations(1 / 60);++ expect(manager.getBounds(e(1))).not.toEqual(frozen);+ expect(manager.getBounds(e(2))).toEqual(frozen);+ manager.dispose();+ });++ it('re-attaching an entity replaces its armature rather than stacking one', () => {+ manager = fresh();+ const handle = load(manager, 'dragonboy');+ manager.setAtlasTexture(handle, 3);+ manager.addEntity(e(1), handle, { armature: 'Dragon', assetKey: 'dragonboy' });+ manager.addEntity(e(1), handle, { armature: 'Dragon', assetKey: 'dragonboy' });++ // One entity, one instance — and the shared skeleton survives, which it+ // would not if the replace released a reference it never took.+ manager.removeEntity(e(1));+ expect(manager.getArmatures(handle)).toEqual([]);+ manager.dispose();+ });++ it('forgets everything on dispose, twice over', () => {+ manager = fresh();+ const handle = load(manager, 'dragonboy');+ manager.setAtlasTexture(handle, 3);+ manager.addEntity(e(1), handle, { armature: 'Dragon', assetKey: 'dragonboy' });++ manager.dispose();+ expect(manager.hasInstance(e(1))).toBe(false);+ // Idempotent: teardown runs from app shutdown and from an engine re-init,+ // and the second must not free a handle the first already did.+ expect(() => manager.dispose()).not.toThrow();+ });+});diff --git a/src/esengine/bindings/DragonBonesModuleEntry.cpp b/src/esengine/bindings/DragonBonesModuleEntry.cppindex 9a2ceeb50..c0c86a7aa 100644--- a/src/esengine/bindings/DragonBonesModuleEntry.cpp+++ b/src/esengine/bindings/DragonBonesModuleEntry.cpp@@ -261,7 +261,6 @@ void db_update(int instanceId, float dt) {if (!armature) return;g_ctx.events.clear();armature->advanceTime(dt);- extractBatches(instanceId);}EMSCRIPTEN_KEEPALIVE@@ -277,9 +276,13 @@ const char* db_getAnimations(int instanceId) {// Geometry readback// =============================================================================+// Posing happens HERE, not in update: one batch list serves every instance, so it+// has to belong to whichever one is being read right now. Extracting in update+// instead leaves it holding the last instance updated — and every getter below+// would then answer for that one however carefully it was asked about another.EMSCRIPTEN_KEEPALIVEint db_getMeshBatchCount(int instanceId) {- (void)instanceId;+ extractBatches(instanceId);return static_cast<int>(g_ctx.batches.size());}@@ -316,9 +319,9 @@ EMSCRIPTEN_KEEPALIVEvoid db_getBounds(int instanceId, uintptr_t outXPtr, uintptr_t outYPtr, uintptr_t outWPtr, uintptr_t outHPtr) {// Derived from the posed batches rather than asked of the runtime: DragonBones// reports an armature's authored bounds, which is not where it currently is.+ extractBatches(instanceId);float minX = 0.0f, minY = 0.0f, maxX = 0.0f, maxY = 0.0f;bool any = false;- (void)instanceId;for (const auto& batch : g_ctx.batches) {for (std::size_t i = 0; i < batch.vertices.size(); i += es::skeletal::VERTEX_FLOATS) {const float x = batch.vertices[i];