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
fix(animation): preserve listener snapshots and callback ownership
yhh2dee21e81882
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ca70ad1d2..6cb4e748b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **Sprite animation events tolerate listener and entity changes.** Self-unsubscription no longer skips the next listener, and listeners registered during dispatch start with a later event. Callbacks that remove, replace or despawn an animator cannot have their changes overwritten by the old update. Listener lists use copy-on-write at registration rather than copying on each animated frame.+- **Tilemap edits respect layer locks and stroke ownership.** Locked layers reject paints and tileset changes before taking snapshots. Live strokes require their original scene, layer binding and edit world; stale completion or cancellation cannot affect reused handles. Locking a layer rolls back its unfinished stroke.- **Tilemap data is available before renderer initialization.** Headless tile reads, edits and chunk serialization use the context's own data service without requiring graphics setup. Initializing the renderer keeps any preloaded maps; shutdown and reinitialization create a fresh service.diff --git a/sdk/src/animation/SpriteAnimator.ts b/sdk/src/animation/SpriteAnimator.tsindex 344a67a04..75c5b33bf 100644--- a/sdk/src/animation/SpriteAnimator.ts+++ b/sdk/src/animation/SpriteAnimator.ts@@ -81,7 +81,7 @@ export class SpriteAnimationAPI {private readonly clips = new Map<string, SpriteAnimClip>();private assetClips_: ((ref: string) => SpriteAnimClip | undefined) | null = null;private readonly entityListeners = new Map<Entity, SpriteAnimEventHandler[]>();- private readonly globalListeners: SpriteAnimEventHandler[] = [];+ private globalListeners: SpriteAnimEventHandler[] = [];// -- clip registry --------------------------------------------------------@@ -124,27 +124,23 @@ export class SpriteAnimationAPI {// -- frame-event listeners ------------------------------------------------onEvent(entity: Entity, handler: SpriteAnimEventHandler): () => void {- let list = this.entityListeners.get(entity);- if (!list) {- list = [];- this.entityListeners.set(entity, list);- }- list.push(handler);+ this.entityListeners.set(entity, [...(this.entityListeners.get(entity) ?? []), handler]);return () => {const arr = this.entityListeners.get(entity);if (arr) {const idx = arr.indexOf(handler);- if (idx >= 0) arr.splice(idx, 1);- if (arr.length === 0) this.entityListeners.delete(entity);+ if (idx < 0) return;+ if (arr.length === 1) this.entityListeners.delete(entity);+ else this.entityListeners.set(entity, [...arr.slice(0, idx), ...arr.slice(idx + 1)]);}};}onEventGlobal(handler: SpriteAnimEventHandler): () => void {- this.globalListeners.push(handler);+ this.globalListeners = [...this.globalListeners, handler];return () => {const idx = this.globalListeners.indexOf(handler);- if (idx >= 0) this.globalListeners.splice(idx, 1);+ if (idx >= 0) this.globalListeners = [...this.globalListeners.slice(0, idx), ...this.globalListeners.slice(idx + 1)];};}@@ -152,22 +148,33 @@ export class SpriteAnimationAPI {this.entityListeners.delete(entity);}- private fireEvents(entity: Entity, clip: SpriteAnimClip, prevFrame: number, newFrame: number): void {- if (!clip.events || clip.events.length === 0) return;+ private isCurrentAnimator(world: World, entity: Entity, animator: SpriteAnimatorData, clipName: string, clip: SpriteAnimClip): boolean {+ return world.tryGet(entity, SpriteAnimator) === animator+ && animator.clip === clipName && this.getClip(clipName) === clip;+ }++ private fireEvents(world: World, entity: Entity, animator: SpriteAnimatorData, clipName: string, clip: SpriteAnimClip, prevFrame: number, newFrame: number): boolean {+ if (!clip.events || clip.events.length === 0) return true;for (const evt of clip.events) {if (shouldFireEvent(evt.frame, prevFrame, newFrame, clip.frames.length, clip.loop)) {const listeners = this.entityListeners.get(entity);+ // Registration uses copy-on-write: these event snapshots stay+ // stable without allocating listener arrays on every frame.+ const globals = this.globalListeners;if (listeners) {for (const handler of listeners) {handler(evt, entity);+ if (!this.isCurrentAnimator(world, entity, animator, clipName, clip)) return false;}}- for (const handler of this.globalListeners) {+ for (const handler of globals) {handler(evt, entity);+ if (!this.isCurrentAnimator(world, entity, animator, clipName, clip)) return false;}}}+ return true;}// -- per-frame system -----------------------------------------------------@@ -176,10 +183,14 @@ export class SpriteAnimationAPI {const entities = world.getEntitiesWithComponents([SpriteAnimator]);for (const entity of entities) {- const animator = world.get(entity, SpriteAnimator) as SpriteAnimatorData;+ // An earlier entity's event can remove a later entity/component+ // from the query snapshot we are currently walking.+ const animator = world.tryGet(entity, SpriteAnimator);+ if (!animator) continue;if (!animator.enabled || !animator.playing || !animator.clip) continue;- const clip = this.getClip(animator.clip);+ const clipName = animator.clip;+ const clip = this.getClip(clipName);if (!clip || clip.frames.length === 0) continue;// playing raised on a finished one-shot = replay from the top@@ -226,7 +237,7 @@ export class SpriteAnimationAPI {}if (frameChanged) {- this.fireEvents(entity, clip, prevFrame, animator.currentFrame);+ if (!this.fireEvents(world, entity, animator, clipName, clip, prevFrame, animator.currentFrame)) continue;}if (frameChanged && world.has(entity, Sprite)) {diff --git a/sdk/tests/fsm-sprite-anim.test.ts b/sdk/tests/fsm-sprite-anim.test.tsindex f2dc93c76..b0dace8a3 100644--- a/sdk/tests/fsm-sprite-anim.test.ts+++ b/sdk/tests/fsm-sprite-anim.test.ts@@ -119,6 +119,7 @@ describe('finished-latch flag contract (system side)', () => {return {getEntitiesWithComponents: () => [1],get: (_e: number, c: { _name: string }) => comps.get(c._name),+ tryGet: (_e: number, c: { _name: string }) => comps.get(c._name) ?? null,has: (_e: number, c: { _name: string }) => comps.has(c._name),insert: (_e: number, c: { _name: string }, data: unknown) => void comps.set(c._name, data),} as unknown as World;diff --git a/sdk/tests/sprite-events-wasm.test.ts b/sdk/tests/sprite-events-wasm.test.tsnew file mode 100644index 000000000..dc3ce372a--- /dev/null+++ b/sdk/tests/sprite-events-wasm.test.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { World } from '../src/ecs/world';+import type { CppRegistry, ESEngineModule } from '../src/wasm';+import { SpriteAnimator, SpriteAnimationAPI } from '../src/animation/SpriteAnimator';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';++describe.skipIf(!HAS_WASM)('sprite animation callback lifecycle on real WASM', () => {+ let engine: ESEngineModule;+ let registry: CppRegistry;+ let world: World;+ let animation: SpriteAnimationAPI;+ beforeAll(async () => { engine = await loadWasmModule(); });+ beforeEach(() => {+ registry = new engine.Registry();+ world = new World(); world.connectCpp(registry, engine);+ animation = new SpriteAnimationAPI();+ animation.registerClip({ name: 'walk', frames: [{ texture: 0 }, { texture: 0 }], fps: 10, loop: true, events: [{ frame: 0, name: 'enter' }] });+ });+ afterEach(() => {+ for (const entity of world.getAllEntities()) world.despawn(entity);+ world.disconnectCpp(); registry.delete();+ });+ const spawn = () => { const entity = world.spawn(); world.insert(entity, SpriteAnimator, { clip: 'walk' }); return entity; };++ it.each(['entity', 'global'] as const)('self-unsubscription does not skip the next %s listener', kind => {+ const entity = spawn();+ const next = vi.fn();+ let off = () => {};+ if (kind === 'entity') {+ off = animation.onEvent(entity, () => off()); animation.onEvent(entity, next);+ } else {+ off = animation.onEventGlobal(() => off()); animation.onEventGlobal(next);+ }+ animation.update(world, 0);+ expect(next).toHaveBeenCalledOnce();+ });++ it('does not deliver the current event to a listener added inside its callback', () => {+ const entity = spawn(); const late = vi.fn();+ animation.onEvent(entity, () => animation.onEventGlobal(late));+ animation.update(world, 0);+ expect(late).not.toHaveBeenCalled();+ });++ it('does not recreate an animator removed by its callback', () => {+ const entity = spawn();+ animation.onEvent(entity, () => world.remove(entity, SpriteAnimator));+ animation.update(world, 0);+ expect(world.has(entity, SpriteAnimator)).toBe(false);+ });++ it('retains a replacement animator installed by its callback', () => {+ const entity = spawn();+ animation.onEvent(entity, () => world.insert(entity, SpriteAnimator, { clip: 'replacement', playing: false }));+ animation.update(world, 0);+ expect(world.get(entity, SpriteAnimator).clip).toBe('replacement');+ expect(world.get(entity, SpriteAnimator).playing).toBe(false);+ });++ it('does not leave phantom animation components after a callback despawns its entity', () => {+ const entity = spawn();+ animation.onEvent(entity, () => world.despawn(entity));+ expect(() => animation.update(world, 0)).not.toThrow();+ expect(world.valid(entity)).toBe(false);+ expect(world.getEntitiesWithComponents([SpriteAnimator])).toHaveLength(0);+ });++ it('skips a later query entry removed by an earlier entity callback', () => {+ const first = spawn(); const later = spawn();+ animation.onEvent(first, () => world.despawn(later));+ expect(() => animation.update(world, 0)).not.toThrow();+ expect(world.valid(later)).toBe(false);+ expect(world.getEntitiesWithComponents([SpriteAnimator])).toEqual([first]);+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 7f8d62532..e6c012a74 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 = {+ 'fix(animation): preserve listener snapshots and callback ownership':+ { note: 'Sprite animation events tolerate listener and entity changes.' },'fix(tilemap): scope paint strokes and respect layer locks':{ note: 'Tilemap edits respect layer locks and stroke ownership.' },'fix(editor): sync tilemap stroke ownership checks':