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): three rectangles, and only a promise may authorise a skipped pose

esengineffdc4965e1ec
diff --git a/sdk/etc/spine.api.md b/sdk/etc/spine.api.md
index dd8f67de1..e291d7574 100644
--- a/sdk/etc/spine.api.md
+++ b/sdk/etc/spine.api.md
@@ -105,6 +105,7 @@ static prototype: SpineManager
## SpineModuleController — class @experimental
```
addAnimation: (instanceId: number, animation: string, loop?: boolean, delay?: number, track?: number) => boolean
+animationDuration: (skeletonHandle: number, animation: string) => number
clipBudget: (instanceId: number) => SpineClipBudget | null
collectEvents: (instanceId: number) => RawSpineEvent[]
createInstance: (skeletonHandle: number) => number
@@ -125,6 +126,7 @@ listConstraints: (instanceId: number) => ConstraintList
loadSkeleton: (skelData: Uint8Array | string, atlasText: string, isBinary: boolean) => number
play: (instanceId: number, animation: string, loop?: boolean, track?: number) => boolean
raw: SpineWasmModule
+requiresContinuousWorldPose: (skeletonHandle: number) => boolean
setAtlasPageTexture: (handle: number, pageIndex: number, textureId: number, width: number, height: number) => void
setAttachment: (instanceId: number, slotName: string, attachmentName: string) => boolean
setDefaultMix: (skeletonHandle: number, duration: number) => void
@@ -136,6 +138,7 @@ setSkin: (instanceId: number, skinName: string) => void
setSlotColor: (instanceId: number, slotName: string, r: number, g: number, b: number, a: number) => boolean
setTrackAlpha: (instanceId: number, track: number, alpha: number) => void
setTransformConstraintMix: (instanceId: number, name: string, mix: TransformMixData) => boolean
+skeletonBounds: (skeletonHandle: number) => SpineAABB | null
unloadSkeleton: (handle: number) => void
update: (instanceId: number, dt: number) => void
static new (raw: SpineWasmModule, api: SpineWrappedAPI): SpineModuleController
diff --git a/sdk/src/spine/SpineController.ts b/sdk/src/spine/SpineController.ts
index 7edb6a601..b168ba218 100644
--- a/sdk/src/spine/SpineController.ts
+++ b/sdk/src/spine/SpineController.ts
@@ -12,6 +12,7 @@ import { log } from '../util/logger';
import { withMalloc, withScratch } from '../wasm/wasmScratch';
import { forEachMeshBatch, type MeshBatchVisitor } from '../skeletal/meshBatches';
import type { SpineClipBudget, SkeletalProbe } from './spineMetrics';
+import type { SpineAABB } from './spineBounds';
export interface RawSpineEvent {
type: number;
@@ -226,6 +227,28 @@ export class SpineModuleController {
});
}
+ /** Seconds; negative where this skeleton has no such animation. */
+ animationDuration(skeletonHandle: number, animation: string): number {
+ return this.api_.getAnimationDuration(skeletonHandle, animation);
+ }
+
+ /** Whether this skeleton's world pose carries state and may not be deferred. */
+ requiresContinuousWorldPose(skeletonHandle: number): boolean {
+ return !!this.api_.requiresContinuousWorldPose(skeletonHandle);
+ }
+
+ /** What the skeleton was AUTHORED at, in its own space — no instance, no
+ * pose, and never an authority over culling. See spineBounds. */
+ skeletonBounds(skeletonHandle: number): SpineAABB | null {
+ return withMalloc(this.raw_, 16, (ptr) => {
+ if (!this.api_.getSkeletonBounds(skeletonHandle, ptr, ptr + 4, ptr + 8, ptr + 12)) return null;
+ const f32 = this.raw_.HEAPF32;
+ const at = ptr >> 2;
+ return { minX: f32[at], minY: f32[at + 1],
+ maxX: f32[at] + f32[at + 2], maxY: f32[at + 1] + f32[at + 3] };
+ });
+ }
+
getBounds(instanceId: number): { x: number; y: number; width: number; height: number } {
return withMalloc(this.raw_, 16, ptr => {
this.api_.getBounds(instanceId, ptr, ptr + 4, ptr + 8, ptr + 12);
diff --git a/sdk/src/spine/SpineModuleLoader.ts b/sdk/src/spine/SpineModuleLoader.ts
index e37386e80..0b9b4d11c 100644
--- a/sdk/src/spine/SpineModuleLoader.ts
+++ b/sdk/src/spine/SpineModuleLoader.ts
@@ -24,6 +24,7 @@ export interface SpineWasmModule {
_spine_advanceAndApply(instanceId: number, dt: number): void;
_spine_materializeWorldPose(instanceId: number, dt: number): void;
_spine_requiresContinuousWorldPose(skeletonHandle: number): number;
+ _spine_getAnimationDuration(skeletonHandle: number, animation: number): number;
_spine_getAnimations(instanceId: number): number;
_spine_getSkins(instanceId: number): number;
@@ -106,6 +107,8 @@ export interface SpineWrappedAPI {
advanceAndApply(instanceId: number, dt: number): void;
materializeWorldPose(instanceId: number, dt: number): void;
requiresContinuousWorldPose(skeletonHandle: number): number;
+ /** Seconds; negative where the skeleton has no such animation. */
+ getAnimationDuration(skeletonHandle: number, animation: string): number;
getAnimations(instanceId: number): string;
getSkins(instanceId: number): string;
getBonePosition(instanceId: number, bone: string, outXPtr: number, outYPtr: number): boolean;
@@ -181,6 +184,7 @@ export function wrapSpineModule(raw: SpineWasmModule): SpineWrappedAPI {
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'],
+ getAnimationDuration: cw('spine_getAnimationDuration', 'number', ['number', 'string']) as SpineWrappedAPI['getAnimationDuration'],
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/src/spine/spineBounds.ts b/sdk/src/spine/spineBounds.ts
new file mode 100644
index 000000000..b7e19393c
--- /dev/null
+++ b/sdk/src/spine/spineBounds.ts
@@ -0,0 +1,200 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spineBounds.ts
+ * @brief Three different things that all look like a rectangle.
+ *
+ * @details Skipping a world pose for something off camera is only safe if the
+ * "off camera" was decided without one, and the extent that decides it
+ * has to be one nothing can leave. Three kinds, and only one of them is
+ * allowed to answer that:
+ *
+ * SETUP is what the skeleton was authored at. A fact about the data,
+ * and animations reach outside it.
+ *
+ * OBSERVED is what a scan saw: every animation, every skin, sampled.
+ * Useful to look at and to propose, and it is not a proof — a mix of
+ * two animations is not the union of their extents, runtime code can
+ * move a bone the export never did, and an extreme between two samples
+ * is simply not seen. It may never authorise a skip.
+ *
+ * CERTIFIED is somebody promising that nothing leaves this rectangle.
+ * A contract, not a measurement, which is why its only source is
+ * explicit. A scan can suggest one; accepting it is the promise.
+ *
+ * Everything here is in the skeleton's own space. A certificate
+ * belongs to an era, which entities share; where one of them stands is
+ * not part of it.
+ */
+
+/** A rectangle in the skeleton's own space. */
+export interface SpineAABB {
+ minX: number;
+ minY: number;
+ maxX: number;
+ maxY: number;
+}
+
+/** What a scan actually visited, so "it scanned everything" is checkable. */
+export interface SpineScanCoverage {
+ animations: number;
+ skins: number;
+ samples: number;
+}
+
+/**
+ * The extent culling is allowed to trust, and how much that is worth.
+ *
+ * `observed` carries the era it was scanned from and retires with it: what one
+ * generation's bytes did is no promise about the next. A certificate is about
+ * the asset, so it carries no era at all.
+ */
+export type SpineCullingEnvelope =
+ | { kind: 'certified'; bounds: SpineAABB; source: 'explicit' }
+ | {
+ kind: 'observed'; bounds: SpineAABB; source: 'animation-scan';
+ sampleStep: number; era: string; coverage: SpineScanCoverage;
+ }
+ | { kind: 'unknown' };
+
+/** The narrow slice of a controller a scan needs. */
+export interface SpineBoundsSource {
+ createInstance(skeletonHandle: number): number;
+ destroyInstance(instanceId: number): void;
+ getAnimations(instanceId: number): string[];
+ getSkins(instanceId: number): string[];
+ setSkin(instanceId: number, skin: string): void;
+ play(instanceId: number, animation: string, loop?: boolean, track?: number): boolean;
+ update(instanceId: number, dt: number): void;
+ getBounds(instanceId: number): { x: number; y: number; width: number; height: number };
+ animationDuration(skeletonHandle: number, animation: string): number;
+ skeletonBounds(skeletonHandle: number): SpineAABB | null;
+}
+
+const EMPTY: SpineAABB = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
+
+function union(into: SpineAABB, box: { x: number; y: number; width: number; height: number }): SpineAABB {
+ if (box.width <= 0 && box.height <= 0) return into;
+ return {
+ minX: Math.min(into.minX, box.x),
+ minY: Math.min(into.minY, box.y),
+ maxX: Math.max(into.maxX, box.x + box.width),
+ maxY: Math.max(into.maxY, box.y + box.height),
+ };
+}
+
+/** What the skeleton was authored at. A fact, never an authority. */
+export function setupBounds(source: SpineBoundsSource, skeletonHandle: number): SpineAABB | null {
+ return source.skeletonBounds(skeletonHandle);
+}
+
+/**
+ * Every animation, at `sampleStep` through its whole duration, in every skin.
+ *
+ * On its own scratch instance, so the entities using this skeleton keep the
+ * pose they were in. The result is `observed`, and stays that whatever it finds.
+ */
+export function scanObservedBounds(
+ source: SpineBoundsSource, skeletonHandle: number, era: string,
+ sampleStep = 1 / 30,
+): SpineCullingEnvelope {
+ const instanceId = source.createInstance(skeletonHandle);
+ try {
+ const skins = source.getSkins(instanceId);
+ const animations = source.getAnimations(instanceId);
+ let bounds = EMPTY;
+ let samples = 0;
+
+ for (const skin of skins) {
+ source.setSkin(instanceId, skin);
+ source.update(instanceId, 0);
+ bounds = union(bounds, source.getBounds(instanceId));
+ samples++;
+
+ for (const animation of animations) {
+ const duration = source.animationDuration(skeletonHandle, animation);
+ if (duration < 0) continue;
+ source.play(instanceId, animation, false, 0);
+ source.update(instanceId, 0);
+ bounds = union(bounds, source.getBounds(instanceId));
+ samples++;
+ for (let t = 0; t < duration; t += sampleStep) {
+ source.update(instanceId, Math.min(sampleStep, duration - t));
+ bounds = union(bounds, source.getBounds(instanceId));
+ samples++;
+ }
+ }
+ }
+
+ return {
+ kind: 'observed', source: 'animation-scan', sampleStep, era, bounds,
+ coverage: { animations: animations.length, skins: skins.length, samples },
+ };
+ } finally {
+ source.destroyInstance(instanceId);
+ }
+}
+
+/**
+ * Somebody promising that no pose of this skeleton leaves `bounds`.
+ *
+ * The only way to make a certificate, and it takes a rectangle rather than
+ * another envelope: an observation cannot be upgraded into a promise by passing
+ * it through a function, only by somebody deciding to make one.
+ */
+export function certifyBounds(bounds: SpineAABB): SpineCullingEnvelope {
+ return { kind: 'certified', bounds: { ...bounds }, source: 'explicit' };
+}
+
+/**
+ * The envelope as it stands for `era`. An observation of another generation is
+ * not one of this one, and comes back unknown rather than being trusted.
+ */
+export function envelopeFor(envelope: SpineCullingEnvelope, era: string): SpineCullingEnvelope {
+ if (envelope.kind !== 'observed') return envelope;
+ return envelope.era === era ? envelope : { kind: 'unknown' };
+}
+
+/**
+ * Whether this entity's world pose may be left unresolved when nothing can see
+ * it. Two independent proofs, and the absence of either is a no: the runtime
+ * saying its constraints carry no state across a pose, and an envelope somebody
+ * certified. Anything else materialises, which costs time and cannot be wrong.
+ */
+export function mayDeferWorldPose(
+ envelope: SpineCullingEnvelope, requiresContinuousWorldPose: boolean,
+): boolean {
+ return !requiresContinuousWorldPose && envelope.kind === 'certified';
+}
+
+/** A 2D affine transform, row-major `[a, b, c, d, tx, ty]`. */
+export type SpineAffine = readonly [number, number, number, number, number, number];
+
+/**
+ * The local rectangle in world space, still conservative: all four corners are
+ * transformed and re-bounded, because under rotation the corners of the result
+ * are not the transformed corners of the input.
+ */
+export function worldBounds(local: SpineAABB, transform: SpineAffine): SpineAABB {
+ const [a, b, c, d, tx, ty] = transform;
+ const corners: Array<[number, number]> = [
+ [local.minX, local.minY], [local.maxX, local.minY],
+ [local.maxX, local.maxY], [local.minX, local.maxY],
+ ];
+ let out = EMPTY;
+ for (const [x, y] of corners) {
+ const wx = a * x + c * y + tx;
+ const wy = b * x + d * y + ty;
+ out = {
+ minX: Math.min(out.minX, wx), minY: Math.min(out.minY, wy),
+ maxX: Math.max(out.maxX, wx), maxY: Math.max(out.maxY, wy),
+ };
+ }
+ return out;
+}
+
+/** Whether `outer` contains `inner`, which is what "did not leave it" means. */
+export function contains(outer: SpineAABB, inner: SpineAABB): boolean {
+ return inner.minX >= outer.minX && inner.minY >= outer.minY
+ && inner.maxX <= outer.maxX && inner.maxY <= outer.maxY;
+}
diff --git a/sdk/tests/helpers/syntheticSpine.ts b/sdk/tests/helpers/syntheticSpine.ts
index 2a9c6941d..fdb58b927 100644
--- a/sdk/tests/helpers/syntheticSpine.ts
+++ b/sdk/tests/helpers/syntheticSpine.ts
@@ -46,6 +46,10 @@ export interface SyntheticOptions {
* turns calls it convex. It is not: the edges cross.
*/
selfIntersecting?: boolean;
+ /** A second skin whose mesh is four times the size of the default's. */
+ hugeSkin?: boolean;
+ /** A second animation that carries the strip far from where the first does. */
+ farAnimation?: boolean;
/** An animation that deforms the polygon from convex to concave at 0.5s. */
deformToConcave?: boolean;
}
@@ -181,26 +185,40 @@ export function syntheticSkeleton(options: SyntheticOptions): SyntheticSkeleton
{ name: 'clip', bone: 'root', attachment: 'clip' },
{ name: 'mesh', bone: 'root', attachment: 'mesh' },
],
- skins: [{
- name: 'default',
- attachments: {
- clip: {
- clip: { type: 'clipping', end: 'mesh', vertexCount: clip.length / 2, vertices: clip },
- },
- mesh: {
- mesh: {
- type: 'mesh', path: 'white',
- uvs: mesh.uvs, triangles: mesh.triangles, vertices: mesh.vertices,
- hull: mesh.hull, width: STRIP_WIDTH, height: STRIP_HEIGHT,
- },
- },
- },
- }],
- animations: { idle: options.deformToConcave ? concaveDeform(clip) : {} },
+ skins: skinsOf(options, mesh, clip),
+ animations: options.deformToConcave ? { idle: concaveDeform(clip) }
+ : options.farAnimation ? { near: {}, far: farTravel() } : { idle: {} },
};
return { json: JSON.stringify(json), atlas: ATLAS };
}
+/** The default skin, and optionally a second one carrying a far bigger mesh. */
+function skinsOf(options: SyntheticOptions, mesh: ReturnType<typeof strip>,
+ clip: number[]): unknown[] {
+ const meshAttachment = (scale: number) => ({
+ type: 'mesh', path: 'white',
+ uvs: mesh.uvs, triangles: mesh.triangles,
+ vertices: mesh.vertices.map((v) => v * scale),
+ hull: mesh.hull, width: STRIP_WIDTH * scale, height: STRIP_HEIGHT * scale,
+ });
+ const skins: unknown[] = [{
+ name: 'default',
+ attachments: { clip: { clip: { type: 'clipping', end: 'mesh', vertexCount: clip.length / 2, vertices: clip } },
+ mesh: { mesh: meshAttachment(1) } },
+ }];
+ if (options.hugeSkin) {
+ skins.push({ name: 'huge', attachments: { mesh: { mesh: meshAttachment(4) } } });
+ }
+ return skins;
+}
+
+/** A bone translation that takes the whole strip well outside the setup pose. */
+function farTravel(): Record<string, unknown> {
+ return {
+ bones: { root: { translate: [{ time: 0, x: 0, y: 0 }, { time: 0.5, x: STRIP_WIDTH, y: STRIP_HEIGHT * 4 }] } },
+ };
+}
+
/**
* A deform timeline that pulls one vertex of the clip polygon inward, so the
* same attachment is convex at rest and concave half a second later. Nothing a
diff --git a/sdk/tests/spine-bounds-certification.test.ts b/sdk/tests/spine-bounds-certification.test.ts
new file mode 100644
index 000000000..3237c1360
--- /dev/null
+++ b/sdk/tests/spine-bounds-certification.test.ts
@@ -0,0 +1,182 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spine-bounds-certification.test.ts
+ * @brief Three rectangles, and only one of them may decide anything.
+ *
+ * @details A skipped world pose is only correct if "nothing can see it" was
+ * decided by an extent nothing can leave. A scan is not that: mixing
+ * two animations is not the union of their extents, runtime code moves
+ * bones the export never did, and an extreme between two samples is
+ * simply not seen. So the scan produces an OBSERVATION, a promise is
+ * something somebody makes, and the gate takes only the promise.
+ *
+ * A false positive here wastes time. A false negative makes something
+ * disappear. These hold the default on the first side.
+ */
+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 { SpineModuleController } from '../src/spine/SpineController';
+import type { SpineWasmModule } from '../src/spine/SpineModuleLoader';
+import {
+ setupBounds, scanObservedBounds, certifyBounds, envelopeFor,
+ mayDeferWorldPose, worldBounds, contains,
+} from '../src/spine/spineBounds';
+import type { SpineAABB, SpineBoundsSource } from '../src/spine/spineBounds';
+import { syntheticSkeleton } from './helpers/syntheticSpine';
+import type { SyntheticOptions } from './helpers/syntheticSpine';
+
+const SPINE38_JS = resolve(WASM_DIR, 'spine38.js');
+const SPINE38_WASM = resolve(WASM_DIR, 'spine38.wasm');
+const FIXTURES = resolve(__dirname, '../benchmarks/fixtures/spine');
+const HAS_WASM = existsSync(SPINE38_WASM)
+ && existsSync(resolve(FIXTURES, 'spineboy-38/spineboy-pro.skel'));
+
+let raw: SpineWasmModule;
+let controller: SpineModuleController;
+let source: SpineBoundsSource;
+
+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 {};
+ },
+ });
+ controller = new SpineModuleController(raw, wrapSpineModule(raw));
+ source = controller as unknown as SpineBoundsSource;
+});
+
+function spineboy(): number {
+ const skelData = new Uint8Array(readFileSync(resolve(FIXTURES, 'spineboy-38/spineboy-pro.skel')));
+ const atlasText = readFileSync(resolve(FIXTURES, 'spineboy-38/spineboy.atlas'), 'utf-8');
+ const handle = controller.loadSkeleton(skelData, atlasText, true);
+ if (handle < 0) throw new Error(controller.getLastError());
+ controller.setAtlasPageTexture(handle, 0, 1, 2048, 2048);
+ return handle;
+}
+
+function synthetic(options: SyntheticOptions): number {
+ const { json, atlas } = syntheticSkeleton(options);
+ const handle = controller.loadSkeleton(new TextEncoder().encode(json), atlas, false);
+ if (handle < 0) throw new Error(controller.getLastError());
+ controller.setAtlasPageTexture(handle, 0, 1, 64, 64);
+ return handle;
+}
+
+const STRIP: SyntheticOptions = { quads: 4, relation: 'inside' };
+
+describe.skipIf(!HAS_WASM)('only a promise may authorise a skipped pose', () => {
+ it('a setup extent is a fact about the data and authorises nothing', () => {
+ const handle = spineboy();
+ const setup = setupBounds(source, handle);
+ expect(setup, 'the runtime reports no authored extent').not.toBeNull();
+ // There is no way to reach `certified` from it: the only maker takes a
+ // rectangle and somebody's decision, never another envelope.
+ expect(mayDeferWorldPose({ kind: 'unknown' }, false)).toBe(false);
+ });
+
+ it('an observation is not a promise however much it scanned', () => {
+ const handle = spineboy();
+ const observed = scanObservedBounds(source, handle, 'era#1');
+ expect(observed.kind).toBe('observed');
+ expect(mayDeferWorldPose(observed, false), 'a scan authorised a skipped pose').toBe(false);
+ });
+
+ it('what a scan sees is outside what the skeleton was authored at', () => {
+ // The witness that scanning is worth doing at all, and the reason the
+ // setup extent cannot stand in for it.
+ const handle = spineboy();
+ const setup = setupBounds(source, handle)!;
+ const observed = scanObservedBounds(source, handle, 'era#1');
+ if (observed.kind !== 'observed') throw new Error('not a scan');
+ expect(contains(setup, observed.bounds), 'a walk stayed inside the setup extent').toBe(false);
+ });
+
+ it('every animation is visited, and the count says so', () => {
+ // Not "the box came out big enough" — a scan that quietly ran one
+ // animation would still produce a plausible box.
+ const handle = synthetic({ ...STRIP, farAnimation: true });
+ const instanceId = controller.createInstance(handle);
+ const animations = controller.getAnimations(instanceId);
+ controller.destroyInstance(instanceId);
+
+ const observed = scanObservedBounds(source, handle, 'era#1');
+ if (observed.kind !== 'observed') throw new Error('not a scan');
+ expect(animations.length).toBe(2);
+ expect(observed.coverage.animations, 'the scan skipped an animation').toBe(animations.length);
+ expect(observed.coverage.samples).toBeGreaterThan(animations.length);
+ });
+
+ it('an animation that travels widens what the scan saw', () => {
+ const near = scanObservedBounds(source, synthetic(STRIP), 'era#1');
+ const far = scanObservedBounds(source, synthetic({ ...STRIP, farAnimation: true }), 'era#1');
+ if (near.kind !== 'observed' || far.kind !== 'observed') throw new Error('not a scan');
+ expect(contains(far.bounds, near.bounds), 'the travelling animation was not seen').toBe(true);
+ expect(far.bounds.maxY).toBeGreaterThan(near.bounds.maxY);
+ });
+
+ it('every skin is visited, and the biggest one is inside what was seen', () => {
+ // A certificate hangs off an era, and an era is (skeleton, atlas) — not
+ // a skin. So a scan that only saw the default one would let an entity
+ // wearing another be culled against a box its geometry leaves.
+ const handle = synthetic({ ...STRIP, hugeSkin: true });
+ const observed = scanObservedBounds(source, handle, 'era#1');
+ if (observed.kind !== 'observed') throw new Error('not a scan');
+ expect(observed.coverage.skins, 'the scan saw one skin').toBe(2);
+
+ const instanceId = controller.createInstance(handle);
+ controller.setSkin(instanceId, 'huge');
+ controller.update(instanceId, 0);
+ const posed = controller.getBounds(instanceId);
+ controller.destroyInstance(instanceId);
+ const wearing: SpineAABB = {
+ minX: posed.x, minY: posed.y,
+ maxX: posed.x + posed.width, maxY: posed.y + posed.height,
+ };
+ expect(contains(observed.bounds, wearing), 'the huge skin leaves what the scan saw').toBe(true);
+ });
+
+ it('an observation retires with the generation it was taken from', () => {
+ const observed = scanObservedBounds(source, spineboy(), 'era#1');
+ expect(envelopeFor(observed, 'era#1').kind).toBe('observed');
+ expect(envelopeFor(observed, 'era#2').kind, 'a scan of the last generation was kept')
+ .toBe('unknown');
+
+ // A promise is about the asset, so it does not retire with the bytes.
+ const promised = certifyBounds({ minX: -1, minY: -1, maxX: 1, maxY: 1 });
+ expect(envelopeFor(promised, 'era#2').kind).toBe('certified');
+ });
+
+ it('a promise authorises a skip, and only alongside the runtime\'s own', () => {
+ const promised = certifyBounds({ minX: -1, minY: -1, maxX: 1, maxY: 1 });
+ expect(mayDeferWorldPose(promised, false)).toBe(true);
+ expect(mayDeferWorldPose(promised, true), 'a stateful skeleton was allowed to defer').toBe(false);
+ expect(mayDeferWorldPose({ kind: 'unknown' }, false), 'no envelope authorised a skip').toBe(false);
+ });
+
+ it('the world extent of a rotated local one contains it', () => {
+ // Under rotation the result's corners are not the transformed corners,
+ // so all four are taken and re-bounded.
+ const local: SpineAABB = { minX: -10, minY: -20, maxX: 30, maxY: 40 };
+ const angle = Math.PI / 4;
+ const [cos, sin] = [Math.cos(angle), Math.sin(angle)];
+ const world = worldBounds(local, [cos, sin, -sin, cos, 100, 200]);
+ for (const [x, y] of [[local.minX, local.minY], [local.maxX, local.minY],
+ [local.maxX, local.maxY], [local.minX, local.maxY]] as const) {
+ const wx = cos * x - sin * y + 100;
+ const wy = sin * x + cos * y + 200;
+ expect(wx).toBeGreaterThanOrEqual(world.minX);
+ expect(wx).toBeLessThanOrEqual(world.maxX);
+ expect(wy).toBeGreaterThanOrEqual(world.minY);
+ expect(wy).toBeLessThanOrEqual(world.maxY);
+ }
+ expect(world.maxX - world.minX).toBeGreaterThan(local.maxX - local.minX);
+ });
+});
diff --git a/src/esengine/bindings/modules/spine/SpineBindings.hpp b/src/esengine/bindings/modules/spine/SpineBindings.hpp
index 132718295..c538aaafd 100644
--- a/src/esengine/bindings/modules/spine/SpineBindings.hpp
+++ b/src/esengine/bindings/modules/spine/SpineBindings.hpp
@@ -95,6 +95,9 @@ void spine_advanceAndApply(int instanceId, float dt);
// Resolve the world transforms the local pose implies.
void spine_materializeWorldPose(int instanceId, float dt);
+// How long one animation runs; negative where there is no such animation.
+float spine_getAnimationDuration(int skeletonHandle, const char* animation);
+
// 1 where this skeleton's world pose carries state and may not be deferred.
int spine_requiresContinuousWorldPose(int skeletonHandle);
diff --git a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp b/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp
index a861bd0e4..daca54e2d 100644
--- a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp
+++ b/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp
@@ -241,6 +241,12 @@ void spine_materializeWorldPose(int instanceId, float dt) {
es::spine::materializeWorldPose(g_ctx.instanceOf(instanceId), dt);
}
+/** How long one animation runs; negative where there is no such animation. */
+EMSCRIPTEN_KEEPALIVE
+float spine_getAnimationDuration(int skeletonHandle, const char* animation) {
+ return es::spine::animationDuration(g_ctx.skeletonOf(skeletonHandle), animation);
+}
+
/** 1 where this skeleton's world pose carries state and may not be deferred. */
EMSCRIPTEN_KEEPALIVE
int spine_requiresContinuousWorldPose(int skeletonHandle) {
diff --git a/src/esengine/bindings/modules/spine/SpineRuntime.hpp b/src/esengine/bindings/modules/spine/SpineRuntime.hpp
index 2908b9367..3caedbc8a 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntime.hpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntime.hpp
@@ -201,6 +201,11 @@ void update(Instance* instance, float dt);
*/
bool requiresContinuousWorldPose(const Skeleton* skeleton);
+/** How long one animation runs, so a scan over it can know when it is done
+ * rather than sampling for a while and hoping. Negative if there is no such
+ * animation. */
+float animationDuration(const Skeleton* skeleton, const char* animation);
+
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.cpp
index ed566b2c0..fcdf7ed9f 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntime21.cpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntime21.cpp
@@ -353,6 +353,12 @@ void update(Instance* instance, float dt) {
materializeWorldPose(instance, dt);
}
+float animationDuration(const Skeleton* skeleton, const char* animation) {
+ if (!skeleton || !skeleton->data) return -1.0f;
+ spAnimation* found = spSkeletonData_findAnimation(skeleton->data, animation);
+ return found ? found->duration : -1.0f;
+}
+
bool requiresContinuousWorldPose(const Skeleton*) {
// 2.1 has no constraint that carries state across a pose.
return false;
diff --git a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp b/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp
index 11367a8b6..2a5d8a292 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp
@@ -308,6 +308,12 @@ void update(Instance* instance, float dt) {
materializeWorldPose(instance, dt);
}
+float animationDuration(const Skeleton* skeleton, const char* animation) {
+ if (!skeleton || !skeleton->data) return -1.0f;
+ spAnimation* found = spSkeletonData_findAnimation(skeleton->data, animation);
+ return found ? found->duration : -1.0f;
+}
+
bool requiresContinuousWorldPose(const Skeleton* skeleton) {
if (!skeleton || !skeleton->data) return false;
#if ES_SPINE_VERSION >= 42
diff --git a/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp b/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp
index 19fbd3e92..936db56e9 100644
--- a/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp
+++ b/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp
@@ -243,6 +243,12 @@ void update(Instance* instance, float dt) {
materializeWorldPose(instance, dt);
}
+float animationDuration(const Skeleton* skeleton, const char* animation) {
+ if (!skeleton || !skeleton->data) return -1.0f;
+ sp::Animation* found = skeleton->data->findAnimation(animation);
+ return found ? found->getDuration() : -1.0f;
+}
+
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,