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
refactor(spine): a pose is two things, and only one of them is worth skipping
esengine4ce853b8a0e8
diff --git a/sdk/src/spine/SpineModuleLoader.ts b/sdk/src/spine/SpineModuleLoader.tsindex 3c5848ea8..e37386e80 100644--- a/sdk/src/spine/SpineModuleLoader.ts+++ b/sdk/src/spine/SpineModuleLoader.ts@@ -21,6 +21,9 @@ export interface SpineWasmModule {_spine_addAnimation(instanceId: number, name: number, loop: number, delay: number, track: number): number;_spine_setSkin(instanceId: number, name: number): void;_spine_update(instanceId: number, dt: number): void;+ _spine_advanceAndApply(instanceId: number, dt: number): void;+ _spine_materializeWorldPose(instanceId: number, dt: number): void;+ _spine_requiresContinuousWorldPose(skeletonHandle: number): number;_spine_getAnimations(instanceId: number): number;_spine_getSkins(instanceId: number): number;@@ -93,6 +96,16 @@ export interface SpineWrappedAPI {addAnimation(instanceId: number, name: string, loop: boolean, delay: number, track: number): boolean;setSkin(instanceId: number, name: string): void;update(instanceId: number, dt: number): void;++ /**+ * The two halves {@link update} is made of. Advancing is what an animation+ * MEANS — track time, mixing, events, attachments — and materializing is+ * where those local transforms become world ones. Only the second is worth+ * skipping, and only where {@link requiresContinuousWorldPose} says it may be.+ */+ advanceAndApply(instanceId: number, dt: number): void;+ materializeWorldPose(instanceId: number, dt: number): void;+ requiresContinuousWorldPose(skeletonHandle: number): number;getAnimations(instanceId: number): string;getSkins(instanceId: number): string;getBonePosition(instanceId: number, bone: string, outXPtr: number, outYPtr: number): boolean;@@ -165,6 +178,9 @@ export function wrapSpineModule(raw: SpineWasmModule): SpineWrappedAPI {addAnimation: cw('spine_addAnimation', 'number', ['number', 'string', 'number', 'number', 'number']) as SpineWrappedAPI['addAnimation'],setSkin: cw('spine_setSkin', null, ['number', 'string']) as SpineWrappedAPI['setSkin'],update: cw('spine_update', null, ['number', 'number']) as SpineWrappedAPI['update'],+ advanceAndApply: cw('spine_advanceAndApply', null, ['number', 'number']) as SpineWrappedAPI['advanceAndApply'],+ materializeWorldPose: cw('spine_materializeWorldPose', null, ['number', 'number']) as SpineWrappedAPI['materializeWorldPose'],+ requiresContinuousWorldPose: cw('spine_requiresContinuousWorldPose', 'number', ['number']) as SpineWrappedAPI['requiresContinuousWorldPose'],getAnimations: cw('spine_getAnimations', 'string', ['number']) as SpineWrappedAPI['getAnimations'],getSkins: cw('spine_getSkins', 'string', ['number']) as SpineWrappedAPI['getSkins'],getBonePosition: cw('spine_getBonePosition', 'number', ['number', 'string', 'number', 'number']) as SpineWrappedAPI['getBonePosition'],diff --git a/sdk/tests/spine-phase-split.test.ts b/sdk/tests/spine-phase-split.test.tsnew file mode 100644index 000000000..a3bd25bbc--- /dev/null+++ b/sdk/tests/spine-phase-split.test.ts@@ -0,0 +1,210 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file spine-phase-split.test.ts+ * @brief A pose is two things, and the composition is the one it was.+ *+ * @details Advancing the animation and resolving world transforms were one call+ * because nothing needed them apart. Splitting them is only allowed to+ * be a split: the pair must be the whole, for geometry, for events, for+ * mixing, for every constraint kind the fixtures carry.+ *+ * And the claim the rest of this design rests on: for a skeleton whose+ * world pose carries no state, resolving it ONCE after many advances is+ * the pose that resolving it after each of them would have produced.+ * That is what makes a deferred pose a deferral rather than a+ * different animation, and the runtime says which skeletons it holds+ * for rather than a caller guessing from a version number.+ */+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 { wrapSpineModule } from '../src/spine/SpineModuleLoader';+import type { SpineWasmModule, SpineWrappedAPI } from '../src/spine/SpineModuleLoader';+import { withScratch } from '../src/wasm/wasmScratch';+import { drawnGeometry } from './helpers/clipGeometry';++const SPINE38_JS = resolve(WASM_DIR, 'spine38.js');+const SPINE38_WASM = resolve(WASM_DIR, 'spine38.wasm');+const FIXTURES = resolve(__dirname, '../benchmarks/fixtures/spine');++/** Every constraint kind the corpus has, and a clipped one. */+const ASSETS = [+ { name: 'spineboy (7 ik, 7 transform)', skel: 'spineboy-38/spineboy-pro.skel', atlas: 'spineboy-38/spineboy.atlas', animation: 'walk' },+ { name: 'raptor (9 ik)', skel: 'raptor-38/raptor-pro.skel', atlas: 'raptor-38/raptor.atlas', animation: 'walk' },+ { name: 'stretchyman (4 ik, 2 transform, 4 path)', skel: 'stretchyman-38/stretchyman-pro.skel', atlas: 'stretchyman-38/stretchyman.atlas', animation: 'sneak' },+ { name: 'coin (clipped)', skel: 'coin-38/coin-pro.skel', atlas: 'coin-38/coin.atlas', animation: 'animation' },+ { name: 'tank (concave clip)', skel: 'tank-38/tank-pro.skel', atlas: 'tank-38/tank.atlas', animation: 'shoot' },+];+const HAS_WASM = existsSync(SPINE38_WASM)+ && ASSETS.every((a) => existsSync(resolve(FIXTURES, a.skel)));+const DT = 1 / 60;++let raw: SpineWasmModule;+let api: SpineWrappedAPI;++beforeAll(async () => {+ if (!HAS_WASM) return;+ const factory = (await import(SPINE38_JS)).default as (opts: unknown) => Promise<SpineWasmModule>;+ const bytes = readFileSync(SPINE38_WASM);+ raw = await factory({+ instantiateWasm(imports: WebAssembly.Imports, cb: (i: WebAssembly.Instance, m: WebAssembly.Module) => void) {+ void WebAssembly.instantiate(bytes, imports).then((r) => cb(r.instance, r.module));+ return {};+ },+ });+ api = wrapSpineModule(raw);+});++const handles = new Map<string, number>();++function skeletonOf(asset: (typeof ASSETS)[number]): number {+ const cached = handles.get(asset.skel);+ if (cached !== undefined) return cached;+ const skelData = new Uint8Array(readFileSync(resolve(FIXTURES, asset.skel)));+ const atlasText = readFileSync(resolve(FIXTURES, asset.atlas), 'utf-8');+ const handle = withScratch(raw, (alloc) => {+ const ptr = alloc(skelData.length);+ raw.HEAPU8.set(skelData, ptr);+ return api.loadSkeleton(ptr, skelData.length, atlasText, atlasText.length, true);+ });+ if (handle < 0) throw new Error(api.getLastError());+ for (let i = 0, pages = api.getAtlasPageCount(handle); i < pages; i++) {+ api.setAtlasPageTexture(handle, i, 1, 2048, 2048);+ }+ handles.set(asset.skel, handle);+ return handle;+}++function playing(asset: (typeof ASSETS)[number]): number {+ const instanceId = api.createInstance(skeletonOf(asset));+ if (!api.playAnimation(instanceId, asset.animation, true, 0)) {+ throw new Error(`${asset.name}: no "${asset.animation}"`);+ }+ return instanceId;+}++function drawn(instanceId: number): string {+ const batches = api.getMeshBatchCount(instanceId);+ return drawnGeometry({+ batches,+ vertexCount: (b) => api.getMeshBatchVertexCount(instanceId, b),+ indexCount: (b) => api.getMeshBatchIndexCount(instanceId, b),+ read(b) {+ const vertices = api.getMeshBatchVertexCount(instanceId, b);+ const indices = api.getMeshBatchIndexCount(instanceId, b);+ return withScratch(raw, (alloc) => {+ const vp = alloc(vertices * 8 * 4 + 4);+ const ip = alloc(indices * 2 + 2);+ const tp = alloc(4);+ const bp = alloc(4);+ api.getMeshBatchData(instanceId, b, vp, ip, tp, bp);+ return {+ vertices: new Float32Array(raw.HEAPU8.buffer.slice(vp, vp + vertices * 8 * 4)),+ indices: new Uint16Array(raw.HEAPU8.buffer.slice(ip, ip + indices * 2)),+ };+ });+ },+ }).digest;+}++/** Everything the module queued this advance, in order. */+function drainEvents(instanceId: number): string[] {+ const out: string[] = [];+ for (let i = 0, n = api.getEventCount(instanceId); i < n; i++) {+ out.push(`${api.getEventAnimationName(i)}:${api.getEventName(i)}`);+ }+ return out;+}++describe.skipIf(!HAS_WASM)('a pose is two things and the pair is the whole', () => {+ it.each(ASSETS)('$name: the two phases draw what the one call drew', (asset) => {+ const fused = playing(asset);+ const split = playing(asset);+ for (let frame = 0; frame < 40; frame++) {+ api.update(fused, DT);+ api.advanceAndApply(split, DT);+ api.materializeWorldPose(split, DT);+ expect(drawn(split), `frame ${frame} drifted`).toBe(drawn(fused));+ }+ });++ it.each(ASSETS)('$name: the world pose is owed after an advance, not paid by it', (asset) => {+ // The tests above compare split against fused, and a break hitting both+ // leaves them agreeing — so this reads at ONE animation time. Advancing+ // does change what is drawn; where the bones ARE is the debt it leaves.+ const instanceId = playing(asset);+ api.materializeWorldPose(instanceId, DT);+ for (let frame = 0; frame < 30; frame++) api.advanceAndApply(instanceId, DT);++ const owed = drawn(instanceId);+ api.materializeWorldPose(instanceId, DT);+ expect(drawn(instanceId), 'either advancing already resolved the world or materializing did not')+ .not.toBe(owed);+ });++ it('the events an advance queues are the events the whole call queued', () => {+ const fused = playing(ASSETS[0]);+ const split = playing(ASSETS[0]);+ api.enableEvents(fused);+ api.enableEvents(split);++ const fusedEvents: string[][] = [];+ const splitEvents: string[][] = [];+ for (let frame = 0; frame < 120; frame++) {+ api.update(fused, DT);+ fusedEvents.push(drainEvents(fused));+ // Materialized AFTER draining, which is the order a deferred pose+ // would use: the events belong to the advance, not to the world.+ api.advanceAndApply(split, DT);+ splitEvents.push(drainEvents(split));+ api.materializeWorldPose(split, DT);+ }+ expect(fusedEvents.flat().length, 'the walk queued no events at all').toBeGreaterThan(0);+ expect(splitEvents).toEqual(fusedEvents);+ });++ it('a mix in flight survives the split', () => {+ const fused = playing(ASSETS[0]);+ const split = playing(ASSETS[0]);+ api.setDefaultMix(skeletonOf(ASSETS[0]), 0.4);+ api.update(fused, DT);+ api.advanceAndApply(split, DT);+ api.materializeWorldPose(split, DT);+ expect(api.playAnimation(fused, 'run', true, 0)).toBeTruthy();+ expect(api.playAnimation(split, 'run', true, 0)).toBeTruthy();++ for (let frame = 0; frame < 30; frame++) {+ api.update(fused, DT);+ api.advanceAndApply(split, DT);+ api.materializeWorldPose(split, DT);+ expect(drawn(split), `mixing frame ${frame} drifted`).toBe(drawn(fused));+ }+ api.setDefaultMix(skeletonOf(ASSETS[0]), 0);+ });++ it.each(ASSETS)('$name: one materialization after many advances is the pose', (asset) => {+ // What a deferred pose has to be. Sixty advances with the world never+ // resolved, then resolved once, is the pose sixty resolutions leave —+ // none of these skeletons carry world state between frames.+ const eager = playing(asset);+ const deferred = playing(asset);+ for (let frame = 0; frame < 60; frame++) {+ api.update(eager, DT);+ api.advanceAndApply(deferred, DT);+ }+ api.materializeWorldPose(deferred, DT);+ expect(drawn(deferred), 'a deferred pose is a different animation').toBe(drawn(eager));+ });++ it('the runtime says which skeletons may not defer, not the caller', () => {+ // 3.8 has no constraint that carries state across a pose, and says so+ // itself — a manager that reasoned from a version number would have to+ // know which release introduced physics.+ for (const asset of ASSETS) {+ expect(api.requiresContinuousWorldPose(skeletonOf(asset)),+ `${asset.name} claims its world pose carries state`).toBe(0);+ }+ });+});diff --git a/src/esengine/bindings/modules/spine/SpineBindings.hpp b/src/esengine/bindings/modules/spine/SpineBindings.hppindex 99ef8dc1c..132718295 100644--- a/src/esengine/bindings/modules/spine/SpineBindings.hpp+++ b/src/esengine/bindings/modules/spine/SpineBindings.hpp@@ -89,6 +89,15 @@ int spine_probe_extract(int instanceId, int stage, int useCollector);// The twenty-four counters of the last probe run, into as many u32 slots.void spine_probe_counts(uint32_t* out);+// Advance the animation clock and apply it to the bones' LOCAL transforms.+void spine_advanceAndApply(int instanceId, float dt);++// Resolve the world transforms the local pose implies.+void spine_materializeWorldPose(int instanceId, float dt);++// 1 where this skeleton's world pose carries state and may not be deferred.+int spine_requiresContinuousWorldPose(int skeletonHandle);+// The skeleton's authored extent, into four floats. No instance, no pose.int spine_getSkeletonBounds(int skeletonHandle, uintptr_t outXPtr, uintptr_t outYPtr,uintptr_t outWPtr, uintptr_t outHPtr);diff --git a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp b/src/esengine/bindings/modules/spine/SpineModuleEntry.cppindex 00146318e..a861bd0e4 100644--- a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp+++ b/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp@@ -211,10 +211,40 @@ EMSCRIPTEN_KEEPALIVEvoid spine_update(int instanceId, float dt) {auto* instance = g_ctx.instanceOf(instanceId);if (!instance) return;+ // The composition lives in the runtime beside the two halves, so there is+ // one definition of what a whole frame is rather than one here as well.+ g_ctx.events.clear();+ es::spine::update(instance, dt);+}+/**+ * Advance the animation clock and apply it to the bones' LOCAL transforms —+ * everything an animation means, and nothing about where it is in the world.+ * The events this produced are queued here, so a caller drains them whether or+ * not it goes on to materialize a world pose.+ */+EMSCRIPTEN_KEEPALIVE+void spine_advanceAndApply(int instanceId, float dt) {+ auto* instance = g_ctx.instanceOf(instanceId);+ if (!instance) return;g_ctx.events.clear();+ es::spine::advanceAndApply(instance, dt);+}- es::spine::update(instance, dt);+/**+ * Resolve the world transforms the local pose implies. Deferring it past an+ * advance is only equivalent where the skeleton says so — see+ * {@link spine_requiresContinuousWorldPose}.+ */+EMSCRIPTEN_KEEPALIVE+void spine_materializeWorldPose(int instanceId, float dt) {+ es::spine::materializeWorldPose(g_ctx.instanceOf(instanceId), dt);+}++/** 1 where this skeleton's world pose carries state and may not be deferred. */+EMSCRIPTEN_KEEPALIVE+int spine_requiresContinuousWorldPose(int skeletonHandle) {+ return es::spine::requiresContinuousWorldPose(g_ctx.skeletonOf(skeletonHandle)) ? 1 : 0;}// =============================================================================diff --git a/src/esengine/bindings/modules/spine/SpineRuntime.hpp b/src/esengine/bindings/modules/spine/SpineRuntime.hppindex da914c16f..2908b9367 100644--- a/src/esengine/bindings/modules/spine/SpineRuntime.hpp+++ b/src/esengine/bindings/modules/spine/SpineRuntime.hpp@@ -175,8 +175,32 @@ void setMixDuration(Skeleton* skeleton, const char* from, const char* to, float// --- instances -------------------------------------------------------------Instance* createInstance(Skeleton* skeleton);+/**+ * Advance the animation clock onto the bones' LOCAL transforms — track time,+ * mixing, events, attachment and draw-order timelines, none of it world space.+ * A fifth of a pose, so nothing that skips frames should skip this.+ */+void advanceAndApply(Instance* instance, float dt);++/**+ * Resolve the bones' WORLD transforms from the local ones, constraints and all:+ * four fifths of a pose, and the only part a frame nobody sees has no use for.+ * `dt` is read only where the skeleton carries stateful physics — see+ * {@link requiresContinuousWorldPose} for when deferring this is the same thing.+ */+void materializeWorldPose(Instance* instance, float dt);++/** {@link advanceAndApply} then {@link materializeWorldPose} — a whole frame. */void update(Instance* instance, float dt);+/**+ * Whether this skeleton's world pose carries state from the last one, so it may+ * never be deferred. The runtime answers for its own version rather than a+ * caller reasoning about which constraints a Spine release has: IK, transform+ * and path solve the current local pose; physics integrates, and cannot.+ */+bool requiresContinuousWorldPose(const Skeleton* skeleton);+bool playAnimation(Instance* instance, const char* animation, bool loop, int track);bool addAnimation(Instance* instance, const char* animation, bool loop, float delay, int track);/** Null or empty restores the default skin. */diff --git a/src/esengine/bindings/modules/spine/SpineRuntime21.cpp b/src/esengine/bindings/modules/spine/SpineRuntime21.cppindex 6eae5ed99..ed566b2c0 100644--- a/src/esengine/bindings/modules/spine/SpineRuntime21.cpp+++ b/src/esengine/bindings/modules/spine/SpineRuntime21.cpp@@ -336,13 +336,28 @@ Instance* createInstance(Skeleton* skeleton) {return instance.release();}-void update(Instance* instance, float dt) {+void advanceAndApply(Instance* instance, float dt) {if (!instance) return;spAnimationState_update(instance->state, dt);spAnimationState_apply(instance->state, instance->skeleton);+}++void materializeWorldPose(Instance* instance, float dt) {+ if (!instance) return;+ (void)dt;spSkeleton_updateWorldTransform(instance->skeleton);}+void update(Instance* instance, float dt) {+ advanceAndApply(instance, dt);+ materializeWorldPose(instance, dt);+}++bool requiresContinuousWorldPose(const Skeleton*) {+ // 2.1 has no constraint that carries state across a pose.+ return false;+}+bool playAnimation(Instance* instance, const char* animation, bool loop, int track) {if (!instance) return false;if (!spSkeletonData_findAnimation(instance->skeleton->data, animation)) return false;diff --git a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp b/src/esengine/bindings/modules/spine/SpineRuntimeC.cppindex eb66b8fb5..11367a8b6 100644--- a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp+++ b/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp@@ -284,19 +284,39 @@ Instance* createInstance(Skeleton* skeleton) {return instance.release();}-void update(Instance* instance, float dt) {+void advanceAndApply(Instance* instance, float dt) {if (!instance) return;spAnimationState_update(instance->state, dt);spAnimationState_apply(instance->state, instance->skeleton);+}++void materializeWorldPose(Instance* instance, float dt) {+ if (!instance) return;#if ES_SPINE_VERSION >= 42- // 4.2 skeletons carry physics constraints, which advance with the clock.+ // 4.2 skeletons carry physics constraints, which advance with the clock —+ // which is exactly why a skeleton that has any may not defer this.spSkeleton_update(instance->skeleton, dt);spSkeleton_updateWorldTransform(instance->skeleton, SP_PHYSICS_UPDATE);#else+ (void)dt;spSkeleton_updateWorldTransform(instance->skeleton);#endif}+void update(Instance* instance, float dt) {+ advanceAndApply(instance, dt);+ materializeWorldPose(instance, dt);+}++bool requiresContinuousWorldPose(const Skeleton* skeleton) {+ if (!skeleton || !skeleton->data) return false;+#if ES_SPINE_VERSION >= 42+ return skeleton->data->physicsConstraintsCount > 0;+#else+ return false;+#endif+}+namespace {/// The entries one track applies this frame: the current one and everything itdiff --git a/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp b/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cppindex 2b21d8c9a..19fbd3e92 100644--- a/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp+++ b/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp@@ -28,6 +28,7 @@#include "./SpineRuntime.hpp"#include <spine/spine.h>+#include <spine/PhysicsConstraintData.h>#include <spine/SkeletonRenderer.h>#include <vector>@@ -225,14 +226,34 @@ Instance* createInstance(Skeleton* skeleton) {return instance.release();}-void update(Instance* instance, float dt) {+void advanceAndApply(Instance* instance, float dt) {if (!instance) return;instance->state->update(dt);instance->state->apply(*instance->skeleton);+}++void materializeWorldPose(Instance* instance, float dt) {+ if (!instance) return;instance->skeleton->update(dt);instance->skeleton->updateWorldTransform(sp::Physics_Update);}+void update(Instance* instance, float dt) {+ advanceAndApply(instance, dt);+ materializeWorldPose(instance, dt);+}++bool requiresContinuousWorldPose(const Skeleton* skeleton) {+ if (!skeleton || !skeleton->data) return false;+ // 4.3 keeps one constraint list and tells them apart by spine's own RTTI,+ // which is what this build has instead of the compiler's.+ sp::Array<sp::ConstraintData*>& constraints = skeleton->data->getConstraints();+ for (size_t i = 0; i < constraints.size(); ++i) {+ if (constraints[i]->getRTTI().instanceOf(sp::PhysicsConstraintData::rtti)) return true;+ }+ return false;+}+bool playAnimation(Instance* instance, const char* animation, bool loop, int track) {if (!instance) return false;// setAnimation takes a reference and asserts on a missing name, so look first.