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: add entity lifecycle and component change events for Store→SceneManager sync
esenginee8ba980af2e1
diff --git a/editor/src/Editor.ts b/editor/src/Editor.tsindex dd6d7c5b9..ecb0a26dc 100644--- a/editor/src/Editor.ts+++ b/editor/src/Editor.ts@@ -215,6 +215,15 @@ export class Editor {return null;}+ onSpineInstanceReady(listener: (entityId: number) => void): () => void {+ for (const panel of this.panelInstances_.values()) {+ if (isSpineInfoProvider(panel)) {+ return panel.onSpineInstanceReady(listener);+ }+ }+ return () => {};+ }+// =========================================================================// Panel Operations// =========================================================================diff --git a/editor/src/panels/AddressablePanel.ts b/editor/src/panels/AddressablePanel.tsindex 276a86521..fe775156e 100644--- a/editor/src/panels/AddressablePanel.ts+++ b/editor/src/panels/AddressablePanel.ts@@ -14,6 +14,21 @@ import { showInputDialog, showConfirmDialog } from '../ui/dialog';import { showContextMenu } from '../ui/ContextMenu';import { showErrorToast, showSuccessToast } from '../ui/Toast';+function getAssetTypeFromPath(path: string): AssetType {+ const ext = path.substring(path.lastIndexOf('.')).toLowerCase();+ switch (ext) {+ case '.esscene': return 'scene';+ case '.ts': case '.js': return 'script';+ case '.png': case '.jpg': case '.jpeg': case '.gif': case '.webp': case '.bmp': return 'image';+ case '.mp3': case '.wav': case '.ogg': case '.flac': return 'audio';+ case '.json': return 'json';+ case '.esmaterial': return 'material';+ case '.esshader': return 'shader';+ case '.bmfont': return 'font';+ default: return 'file';+ }+}+const LABEL_COLORS = ['#61afef', '#e06c75', '#98c379', '#d19a66','#c678dd', '#56b6c2', '#e5c07b', '#be5046',@@ -857,7 +872,7 @@ export class AddressablePanel implements PanelInstance {const name = entry.path.split('/').pop() || '';this.store_.selectAsset({path: fullPath,- type: entry.type as AssetType,+ type: getAssetTypeFromPath(entry.path),name,});}diff --git a/editor/src/panels/PanelRegistry.ts b/editor/src/panels/PanelRegistry.tsindex d05a3d58e..998b12a7a 100644--- a/editor/src/panels/PanelRegistry.ts+++ b/editor/src/panels/PanelRegistry.ts@@ -54,6 +54,7 @@ export interface SpineControllerAware {export interface SpineInfoProvider {getSpineSkeletonInfo(entityId: number): { animations: string[]; skins: string[] } | null;+ onSpineInstanceReady(listener: (entityId: number) => void): () => void;}export function isResizable(p: PanelInstance): p is PanelInstance & Resizable {diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.tsindex e3bcb95af..282760439 100644--- a/editor/src/panels/SceneViewPanel.ts+++ b/editor/src/panels/SceneViewPanel.ts@@ -257,6 +257,10 @@ export class SceneViewPanel {return this.sceneRenderer_?.getSpineSkeletonInfo(entityId) ?? null;}+ onSpineInstanceReady(listener: (entityId: number) => void): () => void {+ return this.sceneRenderer_?.onSpineInstanceReady(listener) ?? (() => {});+ }+private async initWebGLRenderer(): Promise<void> {if (this.webglInitPending_ || this.webglInitialized_) return;if (!this.app_?.wasmModule || !this.webglCanvas_) return;@@ -295,7 +299,6 @@ export class SceneViewPanel {await this.sceneRenderer_.syncScene(this.store_.scene);}- private lastEntityCount_ = -1;private lastLoadVersion_ = -1;private async onSceneChanged(): Promise<void> {diff --git a/editor/src/property/editors.ts b/editor/src/property/editors.tsindex aac1440a3..f17ba95b1 100644--- a/editor/src/property/editors.ts+++ b/editor/src/property/editors.ts@@ -1138,7 +1138,6 @@ function createSpineAnimationEditor(refreshBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 2v6h-6M3 12a9 9 0 0 1 15-6.7L21 8M3 22v-6h6M21 12a9 9 0 0 1-15 6.7L3 16"></path></svg>`;let currentAnimations: string[] = [];- let retryTimer: ReturnType<typeof setTimeout> | null = null;const updateOptions = (animations: string[], currentValue: string) => {select.innerHTML = '';@@ -1161,8 +1160,6 @@ function createSpineAnimationEditor(currentAnimations = animations;};- let retryCount = 0;-const loadAnimations = async () => {const skeletonRef = getComponentValue?.('skeletonPath') as string;const skeletonPath = skeletonRef ? resolveToPath(skeletonRef) : '';@@ -1177,16 +1174,19 @@ function createSpineAnimationEditor(if (data) {const animations = getAnimationNames(data);updateOptions(animations, String(value ?? ''));- retryCount = 0;} else {updateOptions([], String(value ?? ''));- if (skeletonPath.endsWith('.skel') && retryCount < 3) {- retryCount++;- retryTimer = setTimeout(loadAnimations, 500 * retryCount);- }}};+ const editor = getEditorInstance();+ const unsubSpineReady = editor?.onSpineInstanceReady((entityId) => {+ const selected = editor.store.selectedEntity as number | null;+ if (selected === entityId) {+ loadAnimations();+ }+ }) ?? null;+select.addEventListener('change', () => {onChange(select.value);});@@ -1211,7 +1211,7 @@ function createSpineAnimationEditor(}},dispose() {- if (retryTimer) clearTimeout(retryTimer);+ unsubSpineReady?.();wrapper.remove();},};@@ -1239,8 +1239,6 @@ function createSpineSkinEditor(refreshBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 2v6h-6M3 12a9 9 0 0 1 15-6.7L21 8M3 22v-6h6M21 12a9 9 0 0 1-15 6.7L3 16"></path></svg>`;let currentSkins: string[] = [];- let skinRetryTimer: ReturnType<typeof setTimeout> | null = null;- let skinRetryCount = 0;const updateOptions = (skins: string[], currentValue: string) => {select.innerHTML = '';@@ -1279,16 +1277,19 @@ function createSpineSkinEditor(if (data) {const skins = getSkinNames(data);updateOptions(skins.length > 0 ? skins : ['default'], String(value ?? 'default'));- skinRetryCount = 0;} else {updateOptions(['default'], String(value ?? 'default'));- if (skeletonPath.endsWith('.skel') && skinRetryCount < 3) {- skinRetryCount++;- skinRetryTimer = setTimeout(loadSkins, 500 * skinRetryCount);- }}};+ const editor = getEditorInstance();+ const unsubSpineReady = editor?.onSpineInstanceReady((entityId) => {+ const selected = editor.store.selectedEntity as number | null;+ if (selected === entityId) {+ loadSkins();+ }+ }) ?? null;+select.addEventListener('change', () => {onChange(select.value);});@@ -1313,7 +1314,7 @@ function createSpineSkinEditor(}},dispose() {- if (skinRetryTimer) clearTimeout(skinRetryTimer);+ unsubSpineReady?.();wrapper.remove();},};diff --git a/editor/src/renderer/EditorSceneRenderer.ts b/editor/src/renderer/EditorSceneRenderer.tsindex 55d336cb2..d3869c4b6 100644--- a/editor/src/renderer/EditorSceneRenderer.ts+++ b/editor/src/renderer/EditorSceneRenderer.ts@@ -166,6 +166,10 @@ export class EditorSceneRenderer {return this.sceneManager_?.getSpineSkeletonInfo(entityId) ?? null;}+ onSpineInstanceReady(listener: (entityId: number) => void): () => void {+ return this.sceneManager_?.onSpineInstanceReady(listener) ?? (() => {});+ }+// =========================================================================// Rendering// =========================================================================diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.tsindex 9950bcf43..ec7889621 100644--- a/editor/src/scene/EditorSceneManager.ts+++ b/editor/src/scene/EditorSceneManager.ts@@ -56,6 +56,7 @@ export class EditorSceneManager {private spineSkeletons_ = new Map<string, number>();private spineInstanceKeys_ = new Map<number, string>();private spineCurrentState_ = new Map<number, { animation: string; skin: string; loop: boolean }>();+ private spineReadyListeners_ = new Set<(entityId: number) => void>();constructor(module: ESEngineModule, pathResolver: AssetPathResolver) {this.module_ = module;@@ -191,13 +192,20 @@ export class EditorSceneManager {// Incremental Updates// =========================================================================- async updateEntity(entityId: number, components: ComponentData[]): Promise<void> {- const entity = this.entityMap_.get(entityId);- if (!entity) return;+ async updateEntity(entityId: number, components: ComponentData[], entityData?: EntityData): Promise<void> {+ let entity = this.entityMap_.get(entityId);+ if (!entity) {+ entity = this.world_.spawn();+ this.entityMap_.set(entityId, entity);+ }- const existingData = this.entityDataMap_.get(entityId);- if (existingData) {- existingData.components = components;+ if (entityData) {+ this.entityDataMap_.set(entityId, entityData);+ } else {+ const existing = this.entityDataMap_.get(entityId);+ if (existing) {+ existing.components = components;+ }}for (const comp of components) {@@ -244,6 +252,41 @@ export class EditorSceneManager {}}+ spawnEntity(entityId: number, parentId: number | null): void {+ if (this.entityMap_.has(entityId)) return;+ const entity = this.world_.spawn();+ this.entityMap_.set(entityId, entity);+ if (parentId !== null) {+ const parentEntity = this.entityMap_.get(parentId);+ if (parentEntity !== undefined) {+ this.world_.setParent(entity, parentEntity);+ }+ }+ }++ hasEntity(entityId: number): boolean {+ return this.entityMap_.has(entityId);+ }++ removeComponentFromEntity(entityId: number, componentType: string): void {+ const entity = this.entityMap_.get(entityId);+ if (entity === undefined) return;+ switch (componentType) {+ case 'LocalTransform':+ if (this.world_.has(entity, LocalTransform)) this.world_.remove(entity, LocalTransform);+ break;+ case 'Sprite':+ if (this.world_.has(entity, Sprite)) this.world_.remove(entity, Sprite);+ break;+ case 'BitmapText':+ if (this.world_.has(entity, BitmapText)) this.world_.remove(entity, BitmapText);+ break;+ case 'SpineAnimation':+ this.destroySpineInstance(entityId);+ break;+ }+ }+// =========================================================================// Visibility// =========================================================================@@ -357,6 +400,11 @@ export class EditorSceneManager {return this.spineInstances_.has(entityId);}+ onSpineInstanceReady(listener: (entityId: number) => void): () => void {+ this.spineReadyListeners_.add(listener);+ return () => this.spineReadyListeners_.delete(listener);+ }+getSpineSkeletonInfo(entityId: number): { animations: string[]; skins: string[] } | null {if (!this.spineController_) return null;const instanceId = this.spineInstances_.get(entityId);@@ -631,6 +679,10 @@ export class EditorSceneManager {this.spineInstances_.set(entityId, instanceId);this.spineInstanceKeys_.set(entityId, cacheKey);this.spineCurrentState_.delete(entityId);++ for (const cb of this.spineReadyListeners_) {+ cb(entityId);+ }}const skin = data.skin ?? 'default';diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.tsindex d41d96bfb..e4372fdf2 100644--- a/editor/src/store/EditorStore.ts+++ b/editor/src/store/EditorStore.ts@@ -67,6 +67,22 @@ export interface VisibilityChangeEvent {export type VisibilityChangeListener = (event: VisibilityChangeEvent) => void;+export interface EntityLifecycleEvent {+ entity: number;+ type: 'created' | 'deleted';+ parent: number | null;+}++export type EntityLifecycleListener = (event: EntityLifecycleEvent) => void;++export interface ComponentChangeEvent {+ entity: number;+ componentType: string;+ action: 'added' | 'removed';+}++export type ComponentChangeListener = (event: ComponentChangeEvent) => void;+// =============================================================================// EditorStore// =============================================================================@@ -79,6 +95,8 @@ export class EditorStore {private hierarchyListeners_: Set<HierarchyChangeListener> = new Set();private focusListeners_: Set<(entityId: number) => void> = new Set();private visibilityListeners_: Set<VisibilityChangeListener> = new Set();+ private entityLifecycleListeners_: Set<EntityLifecycleListener> = new Set();+ private componentChangeListeners_: Set<ComponentChangeListener> = new Set();private pendingNotify_ = false;private nextEntityId_ = 1;private sceneVersion_ = 0;@@ -319,6 +337,8 @@ export class EditorStore {);this.executeCommand(cmd);+ this.notifyEntityLifecycle({ entity: id, type: 'created', parent: parent as number | null });+if (parent !== null) {const parentData = this.entityMap_.get(parent as number);if (parentData && !parentData.visible) {@@ -336,12 +356,18 @@ export class EditorStore {}deleteEntity(entity: Entity): void {+ const descendants = this.collectDescendantIds(entity as number);const cmd = new DeleteEntityCommand(this.state_.scene, entity);this.executeCommand(cmd);if (this.state_.selectedEntity === entity) {this.state_.selectedEntity = null;}++ for (const id of descendants) {+ this.notifyEntityLifecycle({ entity: id, type: 'deleted', parent: null });+ }+ this.notifyEntityLifecycle({ entity: entity as number, type: 'deleted', parent: null });}reparentEntity(entity: Entity, newParent: Entity | null): void {@@ -378,12 +404,14 @@ export class EditorStore {addComponent(entity: Entity, type: string, data: Record<string, unknown>): void {const cmd = new AddComponentCommand(this.state_.scene, entity, type, data);this.executeCommand(cmd);+ this.notifyComponentChange({ entity: entity as number, componentType: type, action: 'added' });}removeComponent(entity: Entity, type: string): void {if (!isComponentRemovable(type)) return;const cmd = new RemoveComponentCommand(this.state_.scene, entity, type);this.executeCommand(cmd);+ this.notifyComponentChange({ entity: entity as number, componentType: type, action: 'removed' });}updateProperty(@@ -538,6 +566,16 @@ export class EditorStore {return () => this.hierarchyListeners_.delete(listener);}+ subscribeToEntityLifecycle(listener: EntityLifecycleListener): () => void {+ this.entityLifecycleListeners_.add(listener);+ return () => this.entityLifecycleListeners_.delete(listener);+ }++ subscribeToComponentChanges(listener: ComponentChangeListener): () => void {+ this.componentChangeListeners_.add(listener);+ return () => this.componentChangeListeners_.delete(listener);+ }+// =========================================================================// Private// =========================================================================@@ -574,6 +612,29 @@ export class EditorStore {}}+ private notifyEntityLifecycle(event: EntityLifecycleEvent): void {+ for (const listener of this.entityLifecycleListeners_) {+ listener(event);+ }+ }++ private notifyComponentChange(event: ComponentChangeEvent): void {+ for (const listener of this.componentChangeListeners_) {+ listener(event);+ }+ }++ private collectDescendantIds(entityId: number): number[] {+ const result: number[] = [];+ const entityData = this.entityMap_.get(entityId);+ if (!entityData) return result;+ for (const childId of entityData.children) {+ result.push(...this.collectDescendantIds(childId));+ result.push(childId);+ }+ return result;+ }+private rebuildEntityMap(): void {this.entityMap_.clear();for (const entity of this.state_.scene.entities) {diff --git a/editor/src/sync/RuntimeSyncService.ts b/editor/src/sync/RuntimeSyncService.tsindex fb823a0c7..be7d42c4c 100644--- a/editor/src/sync/RuntimeSyncService.ts+++ b/editor/src/sync/RuntimeSyncService.ts@@ -3,7 +3,7 @@* @brief Syncs editor state changes to runtime rendering*/-import type { EditorStore, PropertyChangeEvent, HierarchyChangeEvent, VisibilityChangeEvent } from '../store/EditorStore';+import type { EditorStore, PropertyChangeEvent, HierarchyChangeEvent, VisibilityChangeEvent, EntityLifecycleEvent, ComponentChangeEvent } from '../store/EditorStore';import type { EditorSceneManager } from '../scene/EditorSceneManager';import { getAssetEventBus, type AssetEvent } from '../events/AssetEventBus';import { getDependencyGraph } from '../asset/AssetDependencyGraph';@@ -39,6 +39,18 @@ export class RuntimeSyncService {}));+ this.unsubscribes_.push(+ this.store_.subscribeToEntityLifecycle((event) => {+ this.onEntityLifecycle(event);+ })+ );++ this.unsubscribes_.push(+ this.store_.subscribeToComponentChanges((event) => {+ this.onComponentChange(event);+ })+ );+this.unsubscribes_.push(getAssetEventBus().on('material', (event) => {if (event.type === 'asset:modified') {@@ -64,7 +76,25 @@ export class RuntimeSyncService {}}+ private onEntityLifecycle(event: EntityLifecycleEvent): void {+ if (event.type === 'created') {+ this.sceneManager_.spawnEntity(event.entity, event.parent);+ } else {+ this.sceneManager_.removeEntity(event.entity);+ this.dirtyEntities_.delete(event.entity);+ }+ }++ private onComponentChange(event: ComponentChangeEvent): void {+ if (event.action === 'removed') {+ this.sceneManager_.removeComponentFromEntity(event.entity, event.componentType);+ }+ this.scheduleEntityUpdate(event.entity);+ }+private onPropertyChange(event: PropertyChangeEvent): void {+ if (!this.sceneManager_.hasEntity(event.entity)) return;+if (event.componentType === 'LocalTransform') {this.sceneManager_.syncEntityTransform(event.entity);}@@ -140,7 +170,7 @@ export class RuntimeSyncService {if (!this.store_.isEntityVisible(entityId)) return;const entityData = this.store_.getEntityData(entityId);if (!entityData) return;- await this.sceneManager_.updateEntity(entityId, entityData.components);+ await this.sceneManager_.updateEntity(entityId, entityData.components, entityData);}dispose(): void {