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.

feat(spine): who is allowed to owe a world pose, before anything may skip one

esenginee17608fdb602
diff --git a/sdk/etc/spine.api.md b/sdk/etc/spine.api.md
index 756d8593b..5b1052e15 100644
--- a/sdk/etc/spine.api.md
+++ b/sdk/etc/spine.api.md
@@ -180,8 +180,10 @@ getSkins: (entity: Entity) => string[]
getTransformConstraintMix: (entity: Entity, name: string) => TransformMixData | null
listConstraints: (entity: Entity) => ConstraintList | null
loadEntity: (entity: Entity, era: SpineEraBinding) => boolean
+mayDefer: (entity: Entity) => boolean
metrics: () => SpineFrameMetrics | null
observe: (on: boolean) => void
+poseEligibility: (entity: Entity) => { culling: SpineCullingEnvelope; requiresContinuousWorldPose: boolean; } | null
removeEntity: (entity: Entity) => void
setAnimation: (entity: Entity, animation: string, loop: boolean) => void
setAttachment: (entity: Entity, slotName: string, attachmentName: string) => boolean
@@ -224,7 +226,7 @@ mixY: number
## loadSpineAssets — function @experimental
```
-(module: ESEngineModule | null, source: RuntimeAssetSource, spineManager: SpineManager | null | undefined, spinePairs: ReadonlyArray<{ skeleton: string; atlas: string; }>, transcoderProvider?: TranscoderProvider, owner?: SpineAssetOwner): Promise<Map<string, SpineAssetInfo>>
+(module: ESEngineModule | null, source: RuntimeAssetSource, spineManager: SpineManager | null | undefined, spinePairs: ReadonlyArray<{ skeleton: string; atlas: string; }>, transcoderProvider?: TranscoderProvider, owner?: SpineAssetOwner, certificates?: SpineCertificateSource): Promise<Map<string, SpineAssetInfo>>
```
## loadSpineSceneEntities — function @experimental
diff --git a/sdk/src/spine/SpineRuntime.ts b/sdk/src/spine/SpineRuntime.ts
index 577d8f14e..216f7fd8c 100644
--- a/sdk/src/spine/SpineRuntime.ts
+++ b/sdk/src/spine/SpineRuntime.ts
@@ -27,6 +27,8 @@ import type { SpineVersion } from '../sideModules/registry';
import { log } from '../util/logger';
import { submitEntityMeshes, type SkeletalMaterialOf } from '../skeletal/submitMeshes';
import type { SpineClipBudget } from './spineMetrics';
+import { mayDeferWorldPose } from './spineBounds';
+import type { SpineCullingEnvelope } from './spineBounds';
interface EntityInfo {
skelHandle: number;
@@ -59,6 +61,26 @@ interface SkeletonResidency {
skelHandle: number;
refcount: number;
claim: SpineEraClaim;
+
+ /**
+ * The two proofs a deferred world pose needs, both settled once when the
+ * residency is made: what the asset promised, and what this runtime says
+ * about its own constraints. Kept as the two FACTS rather than one verdict,
+ * so a diagnostic can say which of them is missing.
+ */
+ culling: SpineCullingEnvelope;
+ requiresContinuousWorldPose: boolean;
+}
+
+/**
+ * Whether entities of this residency may be left owing a world pose. Both
+ * proofs, and the absence of either is a no — see spineBounds for why an
+ * observation is not one of them.
+ */
+export function residencyMayDefer(residency: {
+ culling: SpineCullingEnvelope; requiresContinuousWorldPose: boolean;
+}): boolean {
+ return mayDeferWorldPose(residency.culling, residency.requiresContinuousWorldPose);
}
export class SpineRuntime {
@@ -142,7 +164,14 @@ export class SpineRuntime {
this.controller_.setAtlasPageTexture(skelHandle, i, tex.glId, tex.w, tex.h);
}
}
- this.skeletons_.set(era.id, { skelHandle, refcount: 1, claim });
+ // Asked once, here. A hundred entities of this era share the answer, and
+ // a new generation makes a new residency that asks again — the capability
+ // belongs to the skeleton this handle is, not to the name it came under.
+ this.skeletons_.set(era.id, {
+ skelHandle, refcount: 1, claim,
+ culling: era.culling,
+ requiresContinuousWorldPose: this.controller_.requiresContinuousWorldPose(skelHandle),
+ });
return skelHandle;
}
@@ -294,6 +323,31 @@ export class SpineRuntime {
return result;
}
+ /**
+ * Whether this entity's world pose may be left owed when nothing wants it —
+ * both proofs, settled when its residency was made. The scheduler that will
+ * use it does not exist yet; a diagnostic asking why can already read the
+ * two facts off the residency.
+ */
+ mayDefer(entity: Entity): boolean {
+ const info = this.entities_.get(entity);
+ const residency = info ? this.skeletons_.get(info.era) : undefined;
+ return residency ? residencyMayDefer(residency) : false;
+ }
+
+ /** Why, for a diagnostic: the promise, and what the runtime says of itself. */
+ poseEligibility(entity: Entity): {
+ culling: SpineCullingEnvelope; requiresContinuousWorldPose: boolean;
+ } | null {
+ const info = this.entities_.get(entity);
+ const residency = info ? this.skeletons_.get(info.era) : undefined;
+ if (!residency) return null;
+ return {
+ culling: residency.culling,
+ requiresContinuousWorldPose: residency.requiresContinuousWorldPose,
+ };
+ }
+
/**
* Resolve this entity's world transforms if they do not already reflect its
* local pose; returns whether it had to. The REVISION is the authority, not
diff --git a/sdk/src/spine/loadSpineScene.ts b/sdk/src/spine/loadSpineScene.ts
index db1ceb7ac..5f56a73a7 100644
--- a/sdk/src/spine/loadSpineScene.ts
+++ b/sdk/src/spine/loadSpineScene.ts
@@ -30,6 +30,8 @@ import { createAtlasPageTexture, type RuntimeAssetSource } from '../runtime/runt
import type { BasisTranscoder } from '../asset/compressed';
import type { AssetsData } from '../asset/AssetPlugin';
import type { AssetScope } from '../asset/AssetLease';
+import { NO_CERTIFICATES } from './spineCertificates';
+import type { SpineCertificateSource } from './spineCertificates';
/**
* The in-place editable spine props from a SpineAnimation component's data — the
@@ -99,6 +101,10 @@ export async function loadSpineAssets(
spinePairs: ReadonlyArray<{ skeleton: string; atlas: string }>,
transcoderProvider?: TranscoderProvider,
owner?: SpineAssetOwner,
+ /** The promises this realm has recorded about spine assets' extents. Absent
+ * means none, which is what makes an unconfigured project behave exactly as
+ * it did: nothing is certified, so nothing may defer a world pose. */
+ certificates: SpineCertificateSource = NO_CERTIFICATES,
): Promise<Map<string, SpineAssetInfo>> {
const assetInfoMap = new Map<string, SpineAssetInfo>();
@@ -113,7 +119,7 @@ export async function loadSpineAssets(
// 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);
- era = spineEraOf(key, lease as never);
+ era = spineEraOf(key, lease as never, certificates.envelopeFor(key));
} else {
const pages: number[] = [];
const value = await prepareSpine(
@@ -162,7 +168,9 @@ function hostEra(
pages.length = 0;
};
return {
- era: { id, value, retain: () => { claims++; return { release: drop }; } },
+ // A host preparation has no project metadata to read a promise from.
+ era: { id, value, culling: { kind: 'unknown' },
+ retain: () => { claims++; return { release: drop }; } },
preparation: { release: drop },
};
}
diff --git a/sdk/src/spine/prepareSpine.ts b/sdk/src/spine/prepareSpine.ts
index a98a12356..c58005f14 100644
--- a/sdk/src/spine/prepareSpine.ts
+++ b/sdk/src/spine/prepareSpine.ts
@@ -24,6 +24,7 @@ import { requireResourceManager } from '../wasm/resourceManager';
import type { AssetLease } from '../asset/AssetLease';
import { parseSpineAtlasPages } from './atlasPages';
import { log } from '../util/logger';
+import type { SpineCullingEnvelope } from './spineBounds';
/** One atlas page, as the runtime needs it: a GL id and its size. */
export interface SpinePage {
@@ -82,15 +83,26 @@ export interface SpineEraBinding {
* skeleton was parsed from. Null when the era can no longer be joined.
*/
retain(): SpineEraClaim | null;
+
+ /**
+ * What culling may assume about this asset's extent. Carried with the era
+ * because a residency is made from one, but it belongs to the PAIR: a
+ * promise about the asset survives the generation it was read beside.
+ */
+ readonly culling: SpineCullingEnvelope;
}
/** The era binding for an acquired spine asset: identity is the pair plus the
* generation, and the claim is a retain of exactly that generation. */
-export function spineEraOf(key: string, lease: AssetLease<SpineAssetValue>): SpineEraBinding {
+export function spineEraOf(
+ key: string, lease: AssetLease<SpineAssetValue>,
+ culling: SpineCullingEnvelope = { kind: 'unknown' },
+): SpineEraBinding {
return {
id: `${key}#${lease.generation}`,
value: lease.value,
retain: () => lease.retain(),
+ culling,
};
}
diff --git a/sdk/src/spine/spineCertificates.ts b/sdk/src/spine/spineCertificates.ts
new file mode 100644
index 000000000..26751e1f8
--- /dev/null
+++ b/sdk/src/spine/spineCertificates.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spineCertificates.ts
+ * @brief Where a promise about a spine asset's extent comes from.
+ *
+ * @details A certified envelope is a statement somebody made about an asset, so
+ * it belongs to the asset and not to a generation of its bytes: a hot
+ * reload replaces what the skeleton does, not what was promised about
+ * it. That makes the key the PAIR — skeleton and atlas, the identity
+ * spine assets already have — and never a path on its own, because an
+ * atlas decides how its regions were trimmed and so what geometry the
+ * attachments end up with.
+ *
+ * This is the read seam and nothing more. Where the promises are
+ * persisted is the project's business — import metadata today, an
+ * inspector writing that metadata later — and neither of them may
+ * reach past this to hand a runtime an envelope it did not certify.
+ */
+import type { SpineAABB, SpineCullingEnvelope } from './spineBounds';
+import { certifyBounds } from './spineBounds';
+
+/** What a runtime asks when it is about to make a residency. */
+export interface SpineCertificateSource {
+ /** The promise recorded for this pair, or unknown where there is none. */
+ envelopeFor(pairKey: string): SpineCullingEnvelope;
+}
+
+/**
+ * The promises a realm knows about, by pair.
+ *
+ * Only `certify` puts one in, and it takes a rectangle: an observation cannot
+ * become a promise by being stored somewhere that returns promises.
+ */
+export class SpineCertificates implements SpineCertificateSource {
+ private byPair_ = new Map<string, SpineAABB>();
+
+ /** Record that nothing this pair can pose leaves `bounds`. */
+ certify(pairKey: string, bounds: SpineAABB): void {
+ this.byPair_.set(pairKey, { ...bounds });
+ }
+
+ /** Withdraw a promise: a pair with no contract has no envelope. */
+ revoke(pairKey: string): void {
+ this.byPair_.delete(pairKey);
+ }
+
+ envelopeFor(pairKey: string): SpineCullingEnvelope {
+ const bounds = this.byPair_.get(pairKey);
+ return bounds ? certifyBounds(bounds) : { kind: 'unknown' };
+ }
+}
+
+/** A realm with no recorded promises: everything materialises. */
+export const NO_CERTIFICATES: SpineCertificateSource = {
+ envelopeFor: () => ({ kind: 'unknown' }),
+};
diff --git a/sdk/tests/helpers/fakeSpineModule.ts b/sdk/tests/helpers/fakeSpineModule.ts
index 105004e74..f3c1e0e86 100644
--- a/sdk/tests/helpers/fakeSpineModule.ts
+++ b/sdk/tests/helpers/fakeSpineModule.ts
@@ -12,6 +12,7 @@
import { vi } from 'vitest';
import type { SpineWasmModule } from '../../src/spine/SpineModuleLoader';
import type { SpineEraBinding } from '../../src/spine/prepareSpine';
+import type { SpineCullingEnvelope } from '../../src/spine/spineBounds';
export interface FakeSpineModule {
module: SpineWasmModule;
@@ -24,6 +25,10 @@ export interface FakeSpineModule {
unloadSkeleton: ReturnType<typeof vi.fn>;
createInstance: ReturnType<typeof vi.fn>;
destroyInstance: ReturnType<typeof vi.fn>;
+ /** What this fake runtime claims about its own constraints. */
+ continuousWorldPose: boolean;
+ /** How many times a residency asked — the answer is settled once. */
+ continuousQueries: number;
}
export function fakeSpineModule(): FakeSpineModule {
@@ -33,6 +38,9 @@ export function fakeSpineModule(): FakeSpineModule {
skeletons: [] as number[],
instances: [] as number[],
parses: true,
+ /** What the fake runtime says about its own constraints. */
+ continuousWorldPose: false,
+ continuousQueries: 0,
} as FakeSpineModule;
fake.loadSkeleton = vi.fn(() => {
@@ -63,6 +71,10 @@ export function fakeSpineModule(): FakeSpineModule {
spine_getLastError: () => 'the fake refused to parse',
spine_getAtlasPageCount: () => 0,
spine_getMeshBatchCount: () => 0,
+ spine_requiresContinuousWorldPose: () => {
+ fake.continuousQueries++;
+ return fake.continuousWorldPose ? 1 : 0;
+ },
};
fake.module = {
cwrap: (name: string) => exports[name] ?? (() => 0),
@@ -80,11 +92,13 @@ export function fakeSpineModule(): FakeSpineModule {
/** A prepared era with nothing behind it: what a runtime binds an entity to. */
export function fakeSpineEra(
id: string, skelData: Uint8Array | string = new Uint8Array([1]),
+ culling: SpineCullingEnvelope = { kind: 'unknown' },
): SpineEraBinding & { claims: { retained: number; released: number } } {
const claims = { retained: 0, released: 0 };
return {
id,
claims,
+ culling,
value: {
skelData, atlasText: '', isBinary: typeof skelData !== 'string',
textures: new Map(),
diff --git a/sdk/tests/spine-pose-eligibility.test.ts b/sdk/tests/spine-pose-eligibility.test.ts
new file mode 100644
index 000000000..5699ae965
--- /dev/null
+++ b/sdk/tests/spine-pose-eligibility.test.ts
@@ -0,0 +1,152 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spine-pose-eligibility.test.ts
+ * @brief Who is allowed to owe a world pose, and why they are not.
+ *
+ * @details One chain, and every link has to be the thing it says: a promise
+ * recorded against a PAIR, carried on the era a residency is made from,
+ * settled once beside what the runtime says about its own constraints.
+ * Two proofs, kept as two facts — collapsing them into one verdict
+ * would make "this asset is not deferring" unanswerable.
+ *
+ * Nothing skips anything yet. This is the authority arriving before the
+ * effect that will use it.
+ */
+import { describe, it, expect } from 'vitest';
+import { SpineRuntime } from '../src/spine/SpineRuntime';
+import { fakeSpineModule, fakeSpineEra } from './helpers/fakeSpineModule';
+import { SpineCertificates, NO_CERTIFICATES } from '../src/spine/spineCertificates';
+import { certifyBounds, scanObservedBounds, mayDeferWorldPose } from '../src/spine/spineBounds';
+import type { SpineAABB, SpineCullingEnvelope } from '../src/spine/spineBounds';
+import { spinePairKey } from '../src/spine/prepareSpine';
+import type { Entity } from '../src/types';
+
+const PROMISE: SpineAABB = { minX: -200, minY: -100, maxX: 200, maxY: 400 };
+
+function certified(): SpineCullingEnvelope {
+ return certifyBounds(PROMISE);
+}
+
+describe('a promise about a pair, carried to the residency that needs it', () => {
+ it('is recorded against the pair, and another atlas is another asset', () => {
+ const certificates = new SpineCertificates();
+ const withA = spinePairKey('hero.skel', 'hero.atlas');
+ const withB = spinePairKey('hero.skel', 'winter.atlas');
+ certificates.certify(withA, PROMISE);
+
+ expect(certificates.envelopeFor(withA).kind).toBe('certified');
+ expect(certificates.envelopeFor(withB).kind,
+ 'a promise about one atlas was read for another').toBe('unknown');
+ });
+
+ it('a realm with nothing recorded promises nothing', () => {
+ expect(NO_CERTIFICATES.envelopeFor(spinePairKey('hero.skel', 'hero.atlas')).kind)
+ .toBe('unknown');
+ expect(new SpineCertificates().envelopeFor('anything').kind).toBe('unknown');
+ });
+
+ it('a withdrawn promise is not a promise', () => {
+ const certificates = new SpineCertificates();
+ const key = spinePairKey('hero.skel', 'hero.atlas');
+ certificates.certify(key, PROMISE);
+ certificates.revoke(key);
+ expect(certificates.envelopeFor(key).kind).toBe('unknown');
+ });
+
+ it('the residency settles both facts, and asks the runtime exactly once', () => {
+ const fake = fakeSpineModule();
+ const runtime = new SpineRuntime('3.8', fake.module);
+ const era = fakeSpineEra('era#1', new Uint8Array([1]), certified());
+
+ for (let i = 0; i < 100; i++) runtime.loadEntity(i as Entity, era);
+ expect(fake.continuousQueries, 'the capability was asked per entity').toBe(1);
+
+ const eligibility = runtime.poseEligibility(0 as Entity)!;
+ expect(eligibility.culling.kind).toBe('certified');
+ expect(eligibility.requiresContinuousWorldPose).toBe(false);
+ expect(runtime.mayDefer(0 as Entity)).toBe(true);
+ runtime.dispose();
+ });
+
+ it('a runtime whose constraints carry state refuses, promise or not', () => {
+ const fake = fakeSpineModule();
+ fake.continuousWorldPose = true;
+ const runtime = new SpineRuntime('4.2', fake.module);
+ runtime.loadEntity(1 as Entity, fakeSpineEra('era#1', new Uint8Array([1]), certified()));
+
+ const eligibility = runtime.poseEligibility(1 as Entity)!;
+ expect(eligibility.culling.kind, 'the promise was lost on the way in').toBe('certified');
+ expect(eligibility.requiresContinuousWorldPose).toBe(true);
+ expect(runtime.mayDefer(1 as Entity), 'a stateful skeleton was allowed to owe').toBe(false);
+ runtime.dispose();
+ });
+
+ it('an asset nobody promised anything about refuses, whatever the runtime says', () => {
+ const fake = fakeSpineModule();
+ const runtime = new SpineRuntime('3.8', fake.module);
+ runtime.loadEntity(1 as Entity, fakeSpineEra('era#1'));
+
+ const eligibility = runtime.poseEligibility(1 as Entity)!;
+ expect(eligibility.culling.kind).toBe('unknown');
+ expect(eligibility.requiresContinuousWorldPose).toBe(false);
+ expect(runtime.mayDefer(1 as Entity), 'an uncertified asset was allowed to owe').toBe(false);
+ runtime.dispose();
+ });
+
+ it('an observation cannot arrive as a promise', () => {
+ // Not a policy in the scheduler — the gate itself refuses it, so a
+ // future caller cannot hand one in through a different door.
+ const observed: SpineCullingEnvelope = {
+ kind: 'observed', source: 'animation-scan', sampleStep: 1 / 30,
+ era: 'era#1', bounds: PROMISE,
+ coverage: { animations: 11, skins: 1, samples: 400 },
+ };
+ expect(mayDeferWorldPose(observed, false)).toBe(false);
+
+ const fake = fakeSpineModule();
+ const runtime = new SpineRuntime('3.8', fake.module);
+ runtime.loadEntity(1 as Entity, fakeSpineEra('era#1', new Uint8Array([1]), observed));
+ expect(runtime.poseEligibility(1 as Entity)!.culling.kind).toBe('observed');
+ expect(runtime.mayDefer(1 as Entity), 'a scan authorised a deferral').toBe(false);
+ runtime.dispose();
+ });
+
+ it('a new generation is asked again rather than inheriting the last answer', () => {
+ // A residency belongs to an era. Hot-reloading gives a different one,
+ // whose native skeleton is a different parse — and whose capability is
+ // therefore a different question, not a remembered answer.
+ const fake = fakeSpineModule();
+ const runtime = new SpineRuntime('4.2', fake.module);
+ runtime.loadEntity(1 as Entity, fakeSpineEra('pair#1', new Uint8Array([1]), certified()));
+ expect(fake.continuousQueries).toBe(1);
+ expect(runtime.mayDefer(1 as Entity)).toBe(true);
+
+ fake.continuousWorldPose = true;
+ runtime.loadEntity(1 as Entity, fakeSpineEra('pair#2', new Uint8Array([1]), certified()));
+ expect(fake.continuousQueries, 'the new residency reused the old answer').toBe(2);
+ expect(runtime.mayDefer(1 as Entity), 'a reloaded skeleton kept the old capability')
+ .toBe(false);
+ runtime.dispose();
+ });
+
+ it('the promise survives the generation the asset was read at', () => {
+ // What the certificate is ABOUT is the asset, so reloading its bytes
+ // does not withdraw it — the pair key is the same one.
+ const certificates = new SpineCertificates();
+ const key = spinePairKey('hero.skel', 'hero.atlas');
+ certificates.certify(key, PROMISE);
+ for (const generation of [17, 18, 19]) {
+ const envelope = certificates.envelopeFor(key);
+ expect(envelope.kind, `generation ${generation} lost the promise`).toBe('certified');
+ }
+ });
+
+ it('nothing may defer without both, and the two facts say which is missing', () => {
+ expect(mayDeferWorldPose(certified(), false)).toBe(true);
+ expect(mayDeferWorldPose(certified(), true)).toBe(false);
+ expect(mayDeferWorldPose({ kind: 'unknown' }, false)).toBe(false);
+ expect(mayDeferWorldPose({ kind: 'unknown' }, true)).toBe(false);
+ void scanObservedBounds;
+ });
+});