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(animation): apply sprite frames through direct storage accessors

yhheafc8ea2289e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f5532f149..826fd09fe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Fixed
+- **Sprite animation applies frames through direct component accessors.** Running animation resolves the sprite read/write path once per update, avoiding per-frame embind snapshots and full component marshalling for every animated entity. Component write journals still observe frame changes, while editor observers, speculative updates, and rebound worlds retain the full mutation path.
+
- **Native audio completion subscriptions are independent.** Multiple backends sharing one host bridge receive their own voice-end notifications, and preview shutdowns withdraw only their subscription. Dispatch skips listeners withdrawn during the event, defers new listeners to the next event, and notifies remaining listeners before propagating the first callback error.
- **Mini-game and native audio completion retires ownership before callbacks.** Natural completion releases the player or voice record before calling user code, so callback exceptions and repeated end notifications cannot retain resources or deliver completion twice. Stopped, ended, and backend-disposed mini-game handles ignore later playback and parameter operations; retired native handles also stop sending host operations.
diff --git a/sdk/src/animation/SpriteAnimator.ts b/sdk/src/animation/SpriteAnimator.ts
index 7e73181f6..7f1573bd2 100644
--- a/sdk/src/animation/SpriteAnimator.ts
+++ b/sdk/src/animation/SpriteAnimator.ts
@@ -7,6 +7,7 @@
import { defineComponent, type ComponentDef } from '../ecs/component';
import { defineResource } from '../ecs/resource';
+import { getDefaultContext } from '../ecs/context';
import type { Entity, TextureHandle } from '../types';
import type { World } from '../ecs/world';
import { Sprite, type SpriteData } from '../ecs/component';
@@ -53,6 +54,11 @@ export interface SpriteAnimClip {
events?: SpriteAnimEvent[];
}
+function frameDurationOf(clip: SpriteAnimClip, index: number, speed: number, fallback: number): number {
+ const duration = clip.frames[index]?.duration;
+ return Math.max(Number.MIN_VALUE, (duration !== undefined && Number.isFinite(duration) && duration > 0 ? duration : fallback) / speed);
+}
+
export function shouldFireEvent(eventFrame: number, prevFrame: number, newFrame: number, totalFrames: number, loop: boolean): boolean {
// Frame-0 initial apply only. Without the `=== 0`, the completion clamp
// (currentFrame overflows → clamped to last, so prev === new === last) re-fires
@@ -222,6 +228,9 @@ export class SpriteAnimationAPI {
private updateWorld(world: World, deltaTime: number): void {
const entities = world.getEntitiesWithComponents([SpriteAnimator]);
+ if (entities.length === 0) return;
+ const registry = world.getCppRegistry(), module = world.getWasmModule();
+ const readSprite = world.resolveGetter(Sprite), writeSprite = world.resolveSetter(Sprite);
for (const entity of entities) {
// An earlier entity's event can remove a later entity/component
@@ -248,10 +257,6 @@ export class SpriteAnimationAPI {
// timer backward.
const speed = Number.isFinite(animator.speed) ? Math.max(animator.speed, 1e-4) : 1;
const fallback = 1 / (Number.isFinite(clip.fps) && clip.fps > 0 ? clip.fps : 12);
- const durationOf = (i: number): number => {
- const duration = clip.frames[i]?.duration;
- return Math.max(Number.MIN_VALUE, (duration !== undefined && Number.isFinite(duration) && duration > 0 ? duration : fallback) / speed);
- };
let token = this.clipTokens.get(clip);
if (!token) { token = {}; this.clipTokens.set(clip, token); }
const needsInitialApply = this.appliedAnimators.get(animator) !== token;
@@ -272,7 +277,7 @@ export class SpriteAnimationAPI {
let cycleDuration = 0;
while (animator.playing && steps < clip.frames.length * 2) {
if (looping && steps === clip.frames.length) animator.frameTimer %= cycleDuration;
- const frameDuration = durationOf(animator.currentFrame);
+ const frameDuration = frameDurationOf(clip, animator.currentFrame, speed, fallback);
if (animator.frameTimer < frameDuration) break;
animator.frameTimer -= frameDuration;
if (steps < clip.frames.length) cycleDuration += frameDuration;
@@ -300,7 +305,12 @@ export class SpriteAnimationAPI {
if (frameChanged && world.has(entity, Sprite)) {
const frame = clip.frames[animator.currentFrame];
- const sprite = world.get(entity, Sprite) as SpriteData;
+ // Borrow only after event callbacks. Speculation and editor
+ // observers use the full mutation seam; a rebound world cannot
+ // use accessors resolved against its previous registry.
+ const direct = readSprite && writeSprite && !world.speculating && !getDefaultContext().editorBridge
+ && registry === world.getCppRegistry() && module === world.getWasmModule();
+ const sprite = (direct ? readSprite(entity) : world.get(entity, Sprite)) as SpriteData;
sprite.texture = frame.texture;
// Copy (don't alias the clip's frame objects), and RESET to the full
// texture when a frame carries no sub-rect — else a plain frame after
@@ -321,7 +331,10 @@ export class SpriteAnimationAPI {
if (frame.pivot) {
sprite.pivot = { x: frame.pivot.x, y: frame.pivot.y };
}
- world.set(entity, Sprite, sprite);
+ if (direct) {
+ writeSprite(entity, sprite);
+ world.markChanged(entity, Sprite);
+ } else world.set(entity, Sprite, sprite);
}
if (frameChanged) {
diff --git a/sdk/tests/fsm-sprite-anim.test.ts b/sdk/tests/fsm-sprite-anim.test.ts
index d297ea3f9..dd2fa3336 100644
--- a/sdk/tests/fsm-sprite-anim.test.ts
+++ b/sdk/tests/fsm-sprite-anim.test.ts
@@ -117,6 +117,10 @@ describe('finished-latch flag contract (system side)', () => {
* accrual persists between ticks without an insert). */
function makeWorld(comps: Map<string, unknown>): World {
return {
+ getCppRegistry: () => null,
+ getWasmModule: () => null,
+ resolveGetter: () => null,
+ resolveSetter: () => null,
getEntitiesWithComponents: () => [1],
get: (_e: number, c: { _name: string }) => comps.get(c._name),
tryGet: (_e: number, c: { _name: string }) => comps.get(c._name) ?? null,
diff --git a/sdk/tests/sprite-events-wasm.test.ts b/sdk/tests/sprite-events-wasm.test.ts
index 8214dda81..60607b868 100644
--- a/sdk/tests/sprite-events-wasm.test.ts
+++ b/sdk/tests/sprite-events-wasm.test.ts
@@ -6,6 +6,7 @@ import { Sprite } from '../src/ecs/component';
import type { CppRegistry, ESEngineModule } from '../src/wasm';
import { SpriteAnimator, SpriteAnimationAPI } from '../src/animation/SpriteAnimator';
import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';
+import { getDefaultContext } from '../src/ecs/context';
describe.skipIf(!HAS_WASM)('sprite animation callback lifecycle on real WASM', () => {
let engine: ESEngineModule;
@@ -25,6 +26,52 @@ describe.skipIf(!HAS_WASM)('sprite animation callback lifecycle on real WASM', (
});
const spawn = () => { const entity = world.spawn(); world.insert(entity, SpriteAnimator, { clip: 'walk' }); return entity; };
+ it('animates native sprite rows without embind snapshots while preserving authored fields', () => {
+ const entities = Array.from({ length: 32 }, () => {
+ const entity = spawn(); world.insert(entity, Sprite, { texture: 9, layer: 4, flipX: true, color: { r: .2, g: .3, b: .4, a: .8 } }); return entity;
+ });
+ const reads = vi.spyOn(world, 'get'), writes = vi.spyOn(world, 'set');
+ animation.update(world, .1);
+ expect(reads.mock.calls.some(([, component]) => component === Sprite)).toBe(false);
+ expect(writes.mock.calls.some(([, component]) => component === Sprite)).toBe(false);
+ for (const entity of entities) {
+ const sprite = world.get(entity, Sprite);
+ expect(sprite.texture).toBe(0); expect(sprite.layer).toBe(4); expect(sprite.flipX).toBe(true);
+ expect(sprite.color.r).toBeCloseTo(.2); expect(sprite.color.a).toBeCloseTo(.8);
+ }
+ });
+
+ it('preserves editor mutation notifications during frame application', () => {
+ const entity = spawn(); world.insert(entity, Sprite, { texture: 9 });
+ const context = getDefaultContext(), previous = context.editorBridge, changed = vi.fn();
+ context.editorBridge = { registerComponent() {}, onComponentChanged: changed };
+ try {
+ animation.update(world, .1);
+ expect(changed).toHaveBeenCalledWith(entity, 'Sprite');
+ expect(world.get(entity, Sprite).texture).toBe(0);
+ } finally { context.editorBridge = previous; }
+ });
+
+ it('records the pre-image when applying a frame inside speculation', () => {
+ const entity = spawn(); world.insert(entity, Sprite, { texture: 9 });
+ const previous: number[] = [];
+ world.openSpeculation({ record(w, e, component) {
+ if (component === Sprite && previous.length === 0) {
+ previous.push(-1); previous[0] = w.get(e, Sprite).texture;
+ }
+ } });
+ try { animation.update(world, .1); } finally { world.closeSpeculation(); }
+ expect(previous).toContain(9); expect(world.get(entity, Sprite).texture).toBe(0);
+ });
+
+ it('reports direct frame writes to sparse component write readers', () => {
+ const entity = spawn(); world.insert(entity, Sprite, { texture: 9 });
+ const tick = world.getWorldTick(), reader = world.registerWriteReaderFrom(Sprite, tick);
+ world.advanceTick(); animation.update(world, .1);
+ expect(world.getWrittenEntitiesSince(Sprite, tick)).toContain(entity);
+ world.disposeWriteReader(Sprite, reader);
+ });
+
it.each(['entity', 'global'] as const)('self-unsubscription does not skip the next %s listener', kind => {
const entity = spawn();
const next = vi.fn();
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 54e18f8a4..d5f676702 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'perf(animation): apply sprite frames through direct storage accessors':
+ { note: 'Sprite animation applies frames through direct component accessors.' },
'fix(audio): share native completion events across backend subscribers':
{ note: 'Native audio completion subscriptions are independent.' },
'fix(audio): retire platform handles before completion callbacks':