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
refactor: replace RuntimeSyncService with inline renderer sync
esengineea519dbac032
diff --git a/editor/src/panels/inspector/EntityInspector.ts b/editor/src/panels/inspector/EntityInspector.tsindex 88fe997b0..dae7d2fff 100644--- a/editor/src/panels/inspector/EntityInspector.ts+++ b/editor/src/panels/inspector/EntityInspector.ts@@ -364,6 +364,13 @@ export function renderComponent(continue;}+ if (propMeta.hiddenWhen?.hasComponent) {+ const ed = store.getEntityData(entity as number);+ if (ed?.components.some(c => c.type === propMeta.hiddenWhen!.hasComponent)) {+ continue;+ }+ }+const row = document.createElement('div');row.className = 'es-property-row';diff --git a/editor/src/property/PropertyEditor.ts b/editor/src/property/PropertyEditor.tsindex 7f8db7145..da0bd11fe 100644--- a/editor/src/property/PropertyEditor.ts+++ b/editor/src/property/PropertyEditor.ts@@ -16,6 +16,7 @@ export interface PropertyMeta {options?: { label: string; value: unknown }[];fileFilter?: string[];dependsOn?: string;+ hiddenWhen?: { hasComponent: string };}export interface PropertyEditorContext {diff --git a/editor/src/renderer/EditorCamera.ts b/editor/src/renderer/EditorCamera.tsindex b921b05ba..c7220b7b9 100644--- a/editor/src/renderer/EditorCamera.ts+++ b/editor/src/renderer/EditorCamera.ts@@ -13,17 +13,28 @@ export class EditorCamera {zoom: number = 1;minZoom: number = 0.1;maxZoom: number = 10;+ orthoHalfHeight: number = 0;private matrix_ = new Float32Array(16);+ private getHalfSize(viewportWidth: number, viewportHeight: number): { halfW: number; halfH: number } {+ if (this.orthoHalfHeight > 0) {+ const halfH = this.orthoHalfHeight / this.zoom;+ return { halfW: halfH * (viewportWidth / viewportHeight), halfH };+ }+ return {+ halfW: (viewportWidth / 2) / this.zoom,+ halfH: (viewportHeight / 2) / this.zoom,+ };+ }+getViewProjection(viewportWidth: number, viewportHeight: number): Float32Array {- const halfWidth = (viewportWidth / 2) / this.zoom;- const halfHeight = (viewportHeight / 2) / this.zoom;+ const { halfW, halfH } = this.getHalfSize(viewportWidth, viewportHeight);- const left = -halfWidth - this.panX;- const right = halfWidth - this.panX;- const bottom = -halfHeight + this.panY;- const top = halfHeight + this.panY;+ const left = -halfW - this.panX;+ const right = halfW - this.panX;+ const bottom = -halfH + this.panY;+ const top = halfH + this.panY;const near = -1000;const far = 1000;@@ -61,13 +72,12 @@ export class EditorCamera {const ndcX = (screenX / viewportWidth) * 2 - 1;const ndcY = 1 - (screenY / viewportHeight) * 2;- const halfWidth = (viewportWidth / 2) / this.zoom;- const halfHeight = (viewportHeight / 2) / this.zoom;+ const { halfW, halfH } = this.getHalfSize(viewportWidth, viewportHeight);- const worldX = ndcX * halfWidth + this.panX;- const worldY = ndcY * halfHeight + this.panY;-- return { x: worldX, y: worldY };+ return {+ x: ndcX * halfW + this.panX,+ y: ndcY * halfH + this.panY,+ };}/**@@ -79,24 +89,24 @@ export class EditorCamera {viewportWidth: number,viewportHeight: number): { x: number; y: number } {- const halfWidth = (viewportWidth / 2) / this.zoom;- const halfHeight = (viewportHeight / 2) / this.zoom;-- const ndcX = (worldX - this.panX) / halfWidth;- const ndcY = (worldY - this.panY) / halfHeight;+ const { halfW, halfH } = this.getHalfSize(viewportWidth, viewportHeight);- const screenX = (ndcX + 1) / 2 * viewportWidth;- const screenY = (1 - ndcY) / 2 * viewportHeight;+ const ndcX = (worldX - this.panX) / halfW;+ const ndcY = (worldY - this.panY) / halfH;- return { x: screenX, y: screenY };+ return {+ x: (ndcX + 1) / 2 * viewportWidth,+ y: (1 - ndcY) / 2 * viewportHeight,+ };}/*** @brief Pan by screen delta*/pan(deltaScreenX: number, deltaScreenY: number, viewportWidth: number, viewportHeight: number): void {- const worldDeltaX = (deltaScreenX / viewportWidth) * (viewportWidth / this.zoom);- const worldDeltaY = (deltaScreenY / viewportHeight) * (viewportHeight / this.zoom);+ const { halfW, halfH } = this.getHalfSize(viewportWidth, viewportHeight);+ const worldDeltaX = (deltaScreenX / viewportWidth) * (2 * halfW);+ const worldDeltaY = (deltaScreenY / viewportHeight) * (2 * halfH);this.panX -= worldDeltaX;this.panY += worldDeltaY;diff --git a/editor/src/renderer/EditorSceneRenderer.ts b/editor/src/renderer/EditorSceneRenderer.tsindex 0748372d6..781df644d 100644--- a/editor/src/renderer/EditorSceneRenderer.ts+++ b/editor/src/renderer/EditorSceneRenderer.ts@@ -3,8 +3,17 @@* @brief WebGL scene renderer for editor scene view*/-import type { ESEngineModule } from 'esengine';+import type { ESEngineModule, CppRegistry, LayoutRect } from 'esengine';import {+ App,+ UICameraInfo,+ UIEvents,+ UIEventQueue,+ Input,+ InputState,+ setEditorMode,+ uiPlugins,+ ButtonState,RenderPipeline,Renderer,createMaskProcessor,@@ -21,11 +30,13 @@ import {} from 'esengine';import type { SpineModuleController } from 'esengine/spine';import type { SceneData, ComponentData } from '../types/SceneTypes';-import type { EditorStore } from '../store/EditorStore';+import type { EditorStore, PropertyChangeEvent } from '../store/EditorStore';import { EditorCamera } from './EditorCamera';import { EditorSceneManager } from '../scene/EditorSceneManager';-import { RuntimeSyncService } from '../sync/RuntimeSyncService';import { AssetPathResolver } from '../asset';+import { getAssetEventBus } from '../events/AssetEventBus';+import { getDependencyGraph } from '../asset/AssetDependencyGraph';+import type { TransformValue } from '../math/Transform';// =============================================================================// EditorSceneRenderer@@ -33,8 +44,8 @@ import { AssetPathResolver } from '../asset';export class EditorSceneRenderer {private module_: ESEngineModule | null = null;+ private app_: App | null = null;private sceneManager_: EditorSceneManager | null = null;- private syncService_: RuntimeSyncService | null = null;private pipeline_: RenderPipeline | null = null;private camera_: EditorCamera;private pathResolver_: AssetPathResolver;@@ -42,6 +53,10 @@ export class EditorSceneRenderer {private initialized_ = false;private startTime_ = 0;private lastElapsed_ = 0;+ private unsubscribes_: (() => void)[] = [];+ private dirtyEntities_ = new Set<number>();+ private rafId_: number | null = null;+ private renderCallback_: (() => void) | null = null;constructor() {this.camera_ = new EditorCamera();@@ -53,6 +68,10 @@ export class EditorSceneRenderer {this.setupSyncService();}+ setRenderCallback(callback: (() => void) | null): void {+ this.renderCallback_ = callback;+ }+async init(module: ESEngineModule, canvas: HTMLCanvasElement): Promise<boolean> {if (this.initialized_) return true;@@ -92,7 +111,30 @@ export class EditorSceneRenderer {this.pipeline_ = new RenderPipeline();this.startTime_ = performance.now();- this.sceneManager_ = new EditorSceneManager(module, this.pathResolver_);+ const app = App.new();+ const cppRegistry = new module.Registry() as unknown as CppRegistry;+ app.connectCpp(cppRegistry, module);++ app.insertResource(UICameraInfo, {+ viewProjection: new Float32Array(16),+ vpX: 0, vpY: 0, vpW: 0, vpH: 0,+ screenW: 0, screenH: 0,+ worldLeft: 0, worldBottom: 0, worldRight: 0, worldTop: 0,+ worldMouseX: 0, worldMouseY: 0,+ valid: false,+ });++ app.insertResource(Input, new InputState());+ app.insertResource(UIEvents, new UIEventQueue());++ setEditorMode(true);+ for (const plugin of uiPlugins) {+ app.addPlugin(plugin);+ }+ this.app_ = app;++ this.sceneManager_ = new EditorSceneManager(module, this.pathResolver_, app.world);+ this.sceneManager_.registerSystems(app);this.pipeline_.setMaskProcessor(createMaskProcessor(module, this.sceneManager_.world));@@ -104,10 +146,172 @@ export class EditorSceneRenderer {}private setupSyncService(): void {- if (this.syncService_) return;+ if (this.unsubscribes_.length > 0) return;if (!this.store_ || !this.sceneManager_) return;- this.syncService_ = new RuntimeSyncService(this.store_, this.sceneManager_);+ const store = this.store_;+ const sm = this.sceneManager_;++ this.unsubscribes_.push(+ store.subscribeToPropertyChanges((e) => this.handlePropertyChange(e)),+ store.subscribeToHierarchyChanges((e) => {+ sm.reparentEntity(e.entity, e.newParent);+ }),+ store.subscribeToVisibilityChanges((e) => {+ if (e.visible) {+ sm.showEntity(e.entity);+ } else {+ sm.hideEntity(e.entity);+ }+ }),+ store.subscribeToEntityLifecycle((e) => {+ if (e.type === 'created') {+ sm.spawnEntity(e.entity, e.parent);+ } else {+ sm.removeEntity(e.entity);+ this.dirtyEntities_.delete(e.entity);+ }+ }),+ store.subscribeToComponentChanges((e) => {+ if (e.action === 'removed') {+ sm.removeComponentFromEntity(e.entity, e.componentType);+ }+ this.scheduleEntityUpdate(e.entity);+ }),+ getAssetEventBus().on('material', (e) => {+ if (e.type === 'asset:modified') this.onAssetModified(e.path);+ }),+ getAssetEventBus().on('texture', (e) => {+ if (e.type === 'asset:modified') this.onAssetModified(e.path);+ }),+ );++ store.worldTransforms_.setCppWorldTransformProvider((entityId: number) => {+ return this.getCppWorldTransform(entityId);+ });+ }++ private handlePropertyChange(event: PropertyChangeEvent): void {+ if (!this.sceneManager_?.hasEntity(event.entity)) return;++ switch (event.componentType) {+ case 'UIRect':+ case 'ScreenSpace':+ this.scheduleDescendantUpdates(event.entity);+ break;+ case 'Canvas':+ this.syncCanvasToCamera(event.entity);+ break;+ case 'Button':+ this.syncButtonTransitionColor(event.entity);+ break;+ case 'TextInput':+ if (event.propertyName === 'backgroundColor') {+ this.store_!.updatePropertyDirect(event.entity, 'Sprite', 'color', event.newValue);+ }+ break;+ }++ this.scheduleEntityUpdate(event.entity);+ }++ // =========================================================================+ // Sync Helpers+ // =========================================================================++ private syncCanvasToCamera(canvasEntityId: number): void {+ const canvasData = this.store_!.getEntityData(canvasEntityId);+ if (!canvasData) return;++ const canvasComp = canvasData.components.find(c => c.type === 'Canvas');+ const resolution = canvasComp?.data?.designResolution as { x: number; y: number } | undefined;+ if (!resolution) return;++ const orthoSize = resolution.y / 2;++ for (const entity of this.store_!.scene.entities) {+ const cameraComp = entity.components.find(c => c.type === 'Camera');+ if (!cameraComp) continue;++ this.store_!.updatePropertyDirect(entity.id, 'Camera', 'orthoSize', orthoSize);+ this.scheduleEntityUpdate(entity.id);+ break;+ }+ }++ private syncButtonTransitionColor(entityId: number): void {+ const entityData = this.store_!.getEntityData(entityId);+ if (!entityData) return;++ const buttonComp = entityData.components.find(c => c.type === 'Button');+ if (!buttonComp) return;++ const transition = buttonComp.data.transition as {+ normalColor: { r: number; g: number; b: number; a: number };+ hoveredColor: { r: number; g: number; b: number; a: number };+ pressedColor: { r: number; g: number; b: number; a: number };+ disabledColor: { r: number; g: number; b: number; a: number };+ } | null;+ if (!transition) return;++ const spriteComp = entityData.components.find(c => c.type === 'Sprite');+ if (!spriteComp) return;++ const state = (buttonComp.data.state as number) ?? ButtonState.Normal;+ const colorMap: Record<number, { r: number; g: number; b: number; a: number }> = {+ [ButtonState.Normal]: transition.normalColor,+ [ButtonState.Hovered]: transition.hoveredColor,+ [ButtonState.Pressed]: transition.pressedColor,+ [ButtonState.Disabled]: transition.disabledColor,+ };+ const color = colorMap[state] ?? transition.normalColor;++ this.store_!.updatePropertyDirect(entityId, 'Sprite', 'color', { ...color });+ this.scheduleEntityUpdate(entityId);+ }++ // =========================================================================+ // Dirty Entity Scheduling+ // =========================================================================++ private scheduleDescendantUpdates(entityId: number): void {+ const entityData = this.store_!.getEntityData(entityId);+ if (!entityData) return;+ for (const childId of entityData.children) {+ this.scheduleEntityUpdate(childId);+ this.scheduleDescendantUpdates(childId);+ }+ }++ private scheduleEntityUpdate(entityId: number): void {+ this.dirtyEntities_.add(entityId);+ if (this.rafId_ !== null) return;+ this.rafId_ = requestAnimationFrame(() => {+ this.rafId_ = null;+ this.flushDirtyEntities();+ });+ }++ private flushDirtyEntities(): void {+ const entities = [...this.dirtyEntities_];+ this.dirtyEntities_.clear();+ for (const entityId of entities) {+ this.syncEntity(entityId);+ }+ }++ private async syncEntity(entityId: number): Promise<void> {+ if (!this.store_!.isEntityVisible(entityId)) return;+ const entityData = this.store_!.getEntityData(entityId);+ if (!entityData) return;+ await this.sceneManager_!.updateEntity(entityId, entityData.components, entityData);+ this.renderCallback_?.();+ }++ private onAssetModified(path: string): void {+ for (const entityId of getDependencyGraph().getUsers(path)) {+ this.scheduleEntityUpdate(entityId);+ }}setProjectDir(projectDir: string): void {@@ -197,6 +401,39 @@ export class EditorSceneRenderer {return this.sceneManager_?.onSpineInstanceReady(listener) ?? (() => {});}+ getCanvasRect(): LayoutRect | null {+ return this.sceneManager_?.getCanvasRect() ?? null;+ }++ getComputedLayoutSize(entityId: number): { x: number; y: number } | null {+ if (!this.module_ || !this.sceneManager_) return null;+ const entity = this.sceneManager_.getEntityMap().get(entityId);+ if (entity === undefined) return null;+ const registry = this.sceneManager_.registry;+ const w = this.module_.getUIRectComputedWidth(registry, entity);+ const h = this.module_.getUIRectComputedHeight(registry, entity);+ if (w <= 0 && h <= 0) return null;+ return { x: w, y: h };+ }++ getCppWorldTransform(entityId: number): TransformValue | null {+ if (!this.sceneManager_) return null;+ const entity = this.sceneManager_.getEntityMap().get(entityId);+ if (entity === undefined) return null;+ const registry = this.sceneManager_.registry;+ if (!registry.hasTransform(entity)) return null;+ const wt = registry.getTransform(entity);+ return {+ position: { x: wt.worldPosition.x, y: wt.worldPosition.y, z: wt.worldPosition.z },+ rotation: { x: wt.worldRotation.x, y: wt.worldRotation.y, z: wt.worldRotation.z, w: wt.worldRotation.w },+ scale: { x: wt.worldScale.x, y: wt.worldScale.y, z: wt.worldScale.z },+ };+ }++ computeLayoutSize(entityId: number): { x: number; y: number } | null {+ return this.getComputedLayoutSize(entityId);+ }+// =========================================================================// Rendering// =========================================================================@@ -206,9 +443,18 @@ export class EditorSceneRenderer {if (width <= 0 || height <= 0) return;if (this.sceneManager_.isBusy) return;+ this.sceneManager_.setViewportSize(width, height);+const bg = this.findCanvasBackgroundColor();Renderer.setClearColor(bg.r, bg.g, bg.b, bg.a);+ const canvasRect = this.sceneManager_.getCanvasRect();+ if (canvasRect) {+ this.camera_.orthoHalfHeight = (canvasRect.top - canvasRect.bottom) / 2;+ } else {+ this.camera_.orthoHalfHeight = 0;+ }+const matrix = this.camera_.getViewProjection(width, height);const elapsed = (performance.now() - this.startTime_) / 1000;@@ -216,6 +462,20 @@ export class EditorSceneRenderer {const registry = { _cpp: cppReg };try {+ if (this.app_) {+ const uiCamera = this.app_.getResource(UICameraInfo);+ if (canvasRect) {+ uiCamera.worldLeft = canvasRect.left;+ uiCamera.worldBottom = canvasRect.bottom;+ uiCamera.worldRight = canvasRect.right;+ uiCamera.worldTop = canvasRect.top;+ uiCamera.valid = true;+ } else {+ uiCamera.valid = false;+ }+ this.app_.tick(1 / 60);+ }+Renderer.setViewport(0, 0, width, height);Renderer.clearBuffers(3);Renderer.begin(matrix);@@ -258,16 +518,27 @@ export class EditorSceneRenderer {// =========================================================================dispose(): void {- if (this.syncService_) {- this.syncService_.dispose();- this.syncService_ = null;+ if (this.rafId_ !== null) {+ cancelAnimationFrame(this.rafId_);+ this.rafId_ = null;}+ this.dirtyEntities_.clear();+ for (const unsub of this.unsubscribes_) unsub();+ this.unsubscribes_ = [];if (this.sceneManager_) {this.sceneManager_.dispose();this.sceneManager_ = null;}+ if (this.app_) {+ const world = this.app_.world;+ const reg = world.getCppRegistry();+ world.disconnectCpp();+ if (reg) (reg as any).delete();+ this.app_ = null;+ }+if (this.module_ && this.initialized_) {shutdownDrawAPI();shutdownGeometryAPI();diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.tsindex 12fe4a5c5..bb4123978 100644--- a/editor/src/scene/EditorSceneManager.ts+++ b/editor/src/scene/EditorSceneManager.ts@@ -6,38 +6,29 @@import type { ESEngineModule, CppRegistry, Entity } from 'esengine';import {World,+ App,loadComponent,- LocalTransform,+ remapEntityFields,+ Transform,Sprite,BitmapText,Renderer,- INVALID_TEXTURE,+ Text,+ TextInput,+ getComponentAssetFieldDescriptors,+ getComponentSpineFieldDescriptor,INVALID_FONT,INVALID_MATERIAL,- TextRenderer,- TextAlign,- TextVerticalAlign,- TextOverflow,+ DEFAULT_SPINE_SKIN,UIRect,UIMask,- FillDirection,- applyDirectionalFill,- syncFillSpriteSize,- computeFillAnchors,- computeHandleAnchors,- computeFillSize,- DEFAULT_SPRITE_SIZE,- DEFAULT_FONT_FAMILY,- DEFAULT_FONT_SIZE,- DEFAULT_LINE_HEIGHT,- DEFAULT_SPINE_SKIN,+ defineSystem,+ Schedule,type SceneComponentData,- type TextData,- type BitmapTextData,- type LocalTransformData,- type WorldTransformData,- type UIRectData,- type UIMaskData,+ type TransformData,+ type TextInputData,+ type LayoutRect,+ ScaleMode,} from 'esengine';import type { SpineModuleController } from 'esengine/spine';import { submitSpineMeshesToCore } from 'esengine/spine';@@ -47,43 +38,21 @@ import { AssetPathResolver } from '../asset/AssetPathResolver';import { getDependencyGraph } from '../asset/AssetDependencyGraph';import { getAssetLibrary, isUUID } from '../asset/AssetLibrary';import {- type Transform,- getUIRectFromEntity,- computeAdjustedLocalTransform,- findCanvasWorldRect,transformToMatrix4x4,} from '../math/Transform';--const TEXT_RENDER_LAYER = 25;-const BitmapTextAlign = {Left: 0,Center: 1,Right: 2,} as const;-const SPRITE_SUPPRESSING_COMPONENTS = new Set(['Text', 'SpineAnimation']);--const EDITOR_IGNORED_COMPONENTS = new Set([- 'Interactable',- 'Button',- 'ScreenSpace',- 'Slider',- 'ProgressBar',- 'Toggle',- 'ScrollView',- 'Dropdown',- 'LayoutGroup',- 'Image',- 'Draggable',- 'Focusable',- 'SafeArea',- 'ListView',- 'Canvas',- 'Camera',+const COMPONENT_SUPPRESS_RULES = new Map<string, Set<string>>([+ ['Sprite', new Set(['Text', 'SpineAnimation'])],]);+const EDITOR_IGNORED_COMPONENTS = new Set<string>();+// =============================================================================// EditorSceneManager// =============================================================================@@ -93,7 +62,6 @@ export class EditorSceneManager {private world_: World;private assetServer_: EditorAssetServer;private pathResolver_: AssetPathResolver;- private textRenderer_: TextRenderer;private entityMap_ = new Map<number, Entity>();private entityDataMap_ = new Map<number, EntityData>();private sceneData_: SceneData | null = null;@@ -107,21 +75,94 @@ export class EditorSceneManager {private spineCurrentState_ = new Map<number, { animation: string; skin: string; loop: boolean }>();private spineReadyListeners_ = new Set<(entityId: number) => void>();private updatingEntities_ = new Map<number, Promise<void>>();- private cachedCanvasRect_: import('esengine').LayoutRect | null | undefined;+ private viewportAspect_ = 0;+ private postLoadHooks_ = new Map<string, (entityId: number, data: Record<string, any>) => Promise<void>>();++ private ownsWorld_: boolean;- constructor(module: ESEngineModule, pathResolver: AssetPathResolver) {+ constructor(module: ESEngineModule, pathResolver: AssetPathResolver, world?: World) {this.module_ = module;this.pathResolver_ = pathResolver;- this.world_ = new World();- this.world_.connectCpp(new module.Registry() as CppRegistry);+ if (world) {+ this.world_ = world;+ this.ownsWorld_ = false;+ } else {+ this.world_ = new World();+ this.world_.connectCpp(new module.Registry() as CppRegistry);+ this.ownsWorld_ = true;+ }this.assetServer_ = new EditorAssetServer(module, pathResolver);- this.textRenderer_ = new TextRenderer(module);+ this.postLoadHooks_.set('SpineAnimation', (id, data) => this.syncSpineInstance(id, data));}setProjectDir(projectDir: string): void {this.pathResolver_.setProjectDir(projectDir);}+ setViewportSize(width: number, height: number): void {+ if (height > 0) {+ this.viewportAspect_ = width / height;+ }+ }++ getCanvasRect(): LayoutRect | null {+ let designResolution: { x: number; y: number } | null = null;+ let scaleMode = ScaleMode.FixedHeight as number;+ let matchWidthOrHeight = 0.5;+ let cameraPos = { x: 0, y: 0 };++ for (const [_, entityData] of this.entityDataMap_) {+ const canvas = entityData.components.find(c => c.type === 'Canvas');+ if (canvas?.data?.designResolution) {+ designResolution = canvas.data.designResolution as { x: number; y: number };+ scaleMode = (canvas.data.scaleMode as number) ?? ScaleMode.FixedHeight;+ matchWidthOrHeight = (canvas.data.matchWidthOrHeight as number) ?? 0.5;+ }+ const camera = entityData.components.find(c => c.type === 'Camera');+ if (camera) {+ const lt = entityData.components.find(c => c.type === 'Transform');+ if (lt?.data?.position) {+ const pos = lt.data.position as { x: number; y: number };+ cameraPos = { x: pos.x, y: pos.y };+ }+ }+ }++ if (!designResolution) return null;++ const baseOrthoSize = designResolution.y / 2;+ const designAspect = designResolution.x / designResolution.y;+ const actualAspect = this.viewportAspect_ > 0 ? this.viewportAspect_ : designAspect;++ const orthoForWidth = baseOrthoSize * designAspect / actualAspect;+ const orthoForHeight = baseOrthoSize;+ let halfH: number;+ switch (scaleMode) {+ case ScaleMode.FixedWidth:+ halfH = orthoForWidth; break;+ case ScaleMode.FixedHeight:+ halfH = orthoForHeight; break;+ case ScaleMode.Expand:+ halfH = Math.max(orthoForWidth, orthoForHeight); break;+ case ScaleMode.Shrink:+ halfH = Math.min(orthoForWidth, orthoForHeight); break;+ case ScaleMode.Match:+ halfH = Math.pow(orthoForWidth, 1 - matchWidthOrHeight)+ * Math.pow(orthoForHeight, matchWidthOrHeight);+ break;+ default:+ halfH = orthoForHeight;+ }+ const halfW = halfH * actualAspect;++ return {+ left: cameraPos.x - halfW,+ bottom: cameraPos.y - halfH,+ right: cameraPos.x + halfW,+ top: cameraPos.y + halfH,+ };+ }+setSpineController(controller: SpineModuleController | null): void {this.clearSpineInstances();this.spineController_ = controller;@@ -134,9 +175,15 @@ export class EditorSceneManager {for (const [entityId, entityData] of this.entityDataMap_) {const spineComp = entityData.components.find(c => c.type === 'SpineAnimation');if (!spineComp) continue;- const entity = this.entityMap_.get(entityId);- if (entity === undefined) continue;- await this.syncSpineAnimation(entity, spineComp.data, entityId);+ const data = spineComp.data as Record<string, any>;+ const skelRef = data.skeletonPath ?? '';+ const atlasRef = data.atlasPath ?? '';+ if (!skelRef || !atlasRef) continue;+ await this.syncSpineInstance(entityId, {+ ...data,+ skeletonPath: this.resolveAssetRef(skelRef),+ atlasPath: this.resolveAssetRef(atlasRef),+ });}}@@ -185,10 +232,6 @@ export class EditorSceneManager {this.entityMap_.set(entityData.id, this.world_.spawn());}- this.cachedCanvasRect_ = findCanvasWorldRect(- Array.from(this.entityDataMap_.values()),- );-const loadPromises: Promise<void>[] = [];for (const entityData of scene.entities) {if (entityData.parent !== null) {@@ -203,165 +246,37 @@ export class EditorSceneManager {}}await Promise.all(loadPromises);-- this.applyFillStates();-- this.cachedCanvasRect_ = undefined;- }-- private applyFillStates(): void {- for (const [_, entityData] of this.entityDataMap_) {- for (const comp of entityData.components) {- if (comp.type === 'Slider') {- this.applySliderFillState(entityData, comp.data);- break;- }- if (comp.type === 'ProgressBar') {- this.applyProgressBarFillState(entityData, comp.data);- break;- }- }- }- }-- private applySliderFillState(entityData: EntityData, data: Record<string, any>): void {- const value = data.value as number ?? 0;- const minValue = data.minValue as number ?? 0;- const maxValue = data.maxValue as number ?? 1;- const direction = data.direction as number ?? FillDirection.LeftToRight;- const fillEntityId = data.fillEntity as number ?? 0;- const handleEntityId = data.handleEntity as number ?? 0;-- const range = maxValue - minValue;- const normalizedValue = range > 0 ? (value - minValue) / range : 0;-- const parentSize = this.getEntityUIRectSize(entityData);- this.applyFillToWorld(fillEntityId, direction, normalizedValue, parentSize.x, parentSize.y);- this.applyHandleToWorld(handleEntityId, direction, normalizedValue);- }-- private applyProgressBarFillState(entityData: EntityData, data: Record<string, any>): void {- const value = Math.max(0, Math.min(1, data.value as number ?? 0));- const direction = data.direction as number ?? FillDirection.LeftToRight;- const fillEntityId = data.fillEntity as number ?? 0;-- const parentSize = this.getEntityUIRectSize(entityData);- this.applyFillToWorld(fillEntityId, direction, value, parentSize.x, parentSize.y);- }-- private getEntityUIRectSize(entityData: EntityData): { x: number; y: number } {- const uiRectComp = entityData.components.find(c => c.type === 'UIRect');- const size = uiRectComp?.data?.size as { x: number; y: number } | undefined;- return { x: size?.x ?? 0, y: size?.y ?? 0 };- }-- private applyFillToWorld(- fillEntityId: number, direction: number, normalizedValue: number,- parentW: number, parentH: number,- ): void {- if (fillEntityId === 0) return;- const fillEntity = this.entityMap_.get(fillEntityId);- if (fillEntity === undefined) return;- applyDirectionalFill(this.world_, fillEntity, direction, normalizedValue);- syncFillSpriteSize(this.world_, fillEntity, direction, normalizedValue, parentW, parentH);-- const fillEntityData = this.entityDataMap_.get(fillEntityId);- if (fillEntityData) {- const uiRectComp = fillEntityData.components.find(c => c.type === 'UIRect');- if (uiRectComp) {- const anchors = computeFillAnchors(direction, normalizedValue);- uiRectComp.data.anchorMin = anchors.anchorMin;- uiRectComp.data.anchorMax = anchors.anchorMax;- uiRectComp.data.offsetMin = anchors.offsetMin;- uiRectComp.data.offsetMax = anchors.offsetMax;- uiRectComp.data.size = computeFillSize(direction, normalizedValue, parentW, parentH);- }- }- this.syncEntityTransform(fillEntityId);- }-- private applyHandleToWorld(handleEntityId: number, direction: number, normalizedValue: number): void {- if (handleEntityId === 0) return;- const handleEntity = this.entityMap_.get(handleEntityId);- if (handleEntity === undefined) return;- if (!this.world_.has(handleEntity, UIRect)) return;- const handleRect = this.world_.get(handleEntity, UIRect) as UIRectData;- const anchors = computeHandleAnchors(direction, normalizedValue);- handleRect.anchorMin = anchors.anchorMin;- handleRect.anchorMax = anchors.anchorMax;- handleRect.offsetMin = { x: 0, y: 0 };- handleRect.offsetMax = { x: 0, y: 0 };- this.world_.insert(handleEntity, UIRect, handleRect);-- const handleEntityData = this.entityDataMap_.get(handleEntityId);- if (handleEntityData) {- const uiRectComp = handleEntityData.components.find(c => c.type === 'UIRect');- if (uiRectComp) {- uiRectComp.data.anchorMin = anchors.anchorMin;- uiRectComp.data.anchorMax = anchors.anchorMax;- uiRectComp.data.offsetMin = { x: 0, y: 0 };- uiRectComp.data.offsetMax = { x: 0, y: 0 };- }- }- this.syncEntityTransform(handleEntityId);}private async loadEntityComponents(entityData: EntityData): Promise<void> {const entity = this.entityMap_.get(entityData.id)!;+ getDependencyGraph().clearEntity(entityData.id);+ this.assetServer_.releaseMaterialInstance(entityData.id);for (const comp of entityData.components) {- await this.loadComponentWithEditorLogic(entity, comp, entityData.id);+ await this.loadComponentForEntity(entity, comp, entityData.id);}}- private async loadComponentWithEditorLogic(+ private async loadComponentForEntity(entity: Entity,comp: ComponentData,- entityId: number+ entityId: number,): Promise<void> {- switch (comp.type) {- case 'LocalTransform':- this.syncTransform(entity, comp.data, entityId);- break;-- case 'Sprite': {- const entityData = this.entityDataMap_.get(entityId);- const suppressed = entityData?.components.some(- c => SPRITE_SUPPRESSING_COMPONENTS.has(c.type)- );- if (!suppressed) {- await this.syncSprite(entity, comp.data, entityId);- }- break;- }-- case 'Text':- this.syncText(entity, comp.data, entityId);- break;-- case 'BitmapText':- await this.syncBitmapText(entity, comp.data, entityId);- break;+ if (EDITOR_IGNORED_COMPONENTS.has(comp.type)) return;- case 'SpineAnimation':- await this.syncSpineAnimation(entity, comp.data, entityId);- break;+ const suppressors = COMPONENT_SUPPRESS_RULES.get(comp.type);+ if (suppressors) {+ const ed = this.entityDataMap_.get(entityId);+ if (ed?.components.some(c => suppressors.has(c.type))) return;+ }- case 'UIRect':- this.world_.insert(entity, UIRect, comp.data as unknown as UIRectData);- break;- case 'UIMask':- this.world_.insert(entity, UIMask, comp.data as unknown as UIMaskData);- break;- case 'TextInput':- this.syncTextInput(entity, comp.data, entityId);- break;+ const resolved: ComponentData = { type: comp.type, data: { ...comp.data } };+ remapEntityFields(resolved as SceneComponentData, this.entityMap_);+ await this.resolveComponentAssets(resolved, entityId);+ loadComponent(this.world_, entity, resolved as SceneComponentData);- default:- if (!EDITOR_IGNORED_COMPONENTS.has(comp.type)) {- loadComponent(this.world_, entity, comp as SceneComponentData);- }- break;- }+ const hook = this.postLoadHooks_.get(comp.type);+ if (hook) await hook(entityId, resolved.data as Record<string, any>);}// =========================================================================@@ -403,27 +318,13 @@ export class EditorSceneManager {}}+ getDependencyGraph().clearEntity(entityId);+ this.assetServer_.releaseMaterialInstance(entityId);for (const comp of components) {- await this.loadComponentWithEditorLogic(entity, comp, entityId);+ await this.loadComponentForEntity(entity, comp, entityId);}}- syncEntityTransform(entityId: number): void {- const entity = this.entityMap_.get(entityId);- if (entity === undefined) return;- this.syncTransform(entity, null, entityId);- }-- syncTextForEntity(entityId: number): void {- const entity = this.entityMap_.get(entityId);- if (entity === undefined) return;- const entityData = this.entityDataMap_.get(entityId);- if (!entityData) return;- const textComp = entityData.components.find(c => c.type === 'Text');- if (!textComp) return;- this.syncText(entity, textComp.data, entityId);- }-reparentEntity(entityId: number, newParentId: number | null): void {const entity = this.entityMap_.get(entityId);if (entity === undefined) return;@@ -436,14 +337,6 @@ export class EditorSceneManager {} else {this.world_.removeParent(entity);}-- const entityData = this.entityDataMap_.get(entityId);- if (entityData) {- const transformComp = entityData.components.find(c => c.type === 'LocalTransform');- if (transformComp) {- this.syncTransform(entity, transformComp.data, entityId);- }- }}removeEntity(entityId: number): void {@@ -485,8 +378,8 @@ export class EditorSceneManager {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);+ case 'Transform':+ if (this.world_.has(entity, Transform)) this.world_.remove(entity, Transform);break;case 'Sprite':if (this.world_.has(entity, Sprite)) this.world_.remove(entity, Sprite);@@ -501,9 +394,11 @@ export class EditorSceneManager {if (this.world_.has(entity, UIMask)) this.world_.remove(entity, UIMask);break;case 'Text':+ if (this.world_.has(entity, Text)) this.world_.remove(entity, Text);+ break;case 'TextInput':- this.textRenderer_.release(entity);- if (this.world_.has(entity, Sprite)) this.world_.remove(entity, Sprite);+ if (this.world_.has(entity, TextInput)) this.world_.remove(entity, TextInput);+ if (this.world_.has(entity, Text)) this.world_.remove(entity, Text);break;case 'SpineAnimation':this.destroySpineInstance(entityId);@@ -559,10 +454,6 @@ export class EditorSceneManager {return this.assetServer_;}- get textRenderer(): TextRenderer {- return this.textRenderer_;- }-// =========================================================================// Spine Module Rendering// =========================================================================@@ -598,19 +489,12 @@ export class EditorSceneManager {const registry = this.registry;let transform: Float32Array | undefined;- if (registry.hasWorldTransform(entity)) {- const wt = registry.getWorldTransform(entity) as WorldTransformData;- transform = transformToMatrix4x4({- position: wt.position,- rotation: wt.rotation,- scale: { x: wt.scale.x * scaleX, y: wt.scale.y * scaleY, z: wt.scale.z },- });- } else if (registry.hasLocalTransform(entity)) {- const lt = registry.getLocalTransform(entity) as LocalTransformData;+ if (registry.hasTransform(entity)) {+ const wt = registry.getTransform(entity) as TransformData;transform = transformToMatrix4x4({- position: lt.position,- rotation: lt.rotation,- scale: { x: lt.scale.x * scaleX, y: lt.scale.y * scaleY, z: lt.scale.z },+ position: wt.worldPosition,+ rotation: wt.worldRotation,+ scale: { x: wt.worldScale.x * scaleX, y: wt.worldScale.y * scaleY, z: wt.worldScale.z },});}@@ -716,48 +600,52 @@ export class EditorSceneManager {this.entityMap_.clear();this.entityDataMap_.clear();this.sceneData_ = null;- this.textRenderer_.releaseAll();}dispose(): void {this.clear();this.assetServer_.releaseAll();- const registry = this.registry;- this.world_.disconnectCpp();- registry.delete();+ if (this.ownsWorld_) {+ const registry = this.registry;+ this.world_.disconnectCpp();+ registry.delete();+ }}// =========================================================================- // Component Sync (Editor-specific logic)+ // System Registration// =========================================================================- syncScreenSpaceDescendants(entityId: number): void {- const entityData = this.entityDataMap_.get(entityId);- if (!entityData) return;- for (const childId of entityData.children) {- this.syncEntityTransform(childId);- this.syncScreenSpaceDescendants(childId);- }+ registerSystems(app: App): void {+ const self = this;++ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(+ [],+ () => {+ for (const entity of self.world_.getEntitiesWithComponents([TextInput])) {+ const input = self.world_.get(entity, TextInput) as TextInputData;+ const isEmpty = !input.value;+ const displayText = isEmpty ? input.placeholder : input.value;+ if (!displayText) {+ if (self.world_.has(entity, Text)) self.world_.remove(entity, Text);+ continue;+ }+ self.world_.insert(entity, Text, {+ content: displayText,+ fontFamily: input.fontFamily,+ fontSize: input.fontSize,+ color: isEmpty ? input.placeholderColor : input.color,+ wordWrap: false,+ });+ }+ },+ { name: 'EditorTextInputVisualSystem' },+ ), { runBefore: ['TextSystem'] });}- private syncTransform(entity: Entity, _data: Record<string, unknown> | null, entityId: number): void {- const entityData = this.entityDataMap_.get(entityId);- if (!entityData) return;-- const canvasRect = this.cachedCanvasRect_ !== undefined- ? this.cachedCanvasRect_- : findCanvasWorldRect(Array.from(this.entityDataMap_.values()));-- const adjustedLocal = computeAdjustedLocalTransform(- entityData, (id) => this.entityDataMap_.get(id), undefined, canvasRect,- );-- this.world_.insert(entity, LocalTransform, {- position: adjustedLocal.position,- rotation: adjustedLocal.rotation,- scale: adjustedLocal.scale,- });- }+ // =========================================================================+ // Generic Asset Resolution+ // =========================================================================private resolveAssetRef(ref: string): string {if (isUUID(ref)) {@@ -766,204 +654,90 @@ export class EditorSceneManager {return ref;}- private async syncSprite(entity: Entity, data: Record<string, any>, entityId: number): Promise<void> {- let textureHandle = INVALID_TEXTURE as number;- let materialHandle = INVALID_MATERIAL as number;+ private async resolveComponentAssets(comp: ComponentData, entityId: number): Promise<void> {+ const data = comp.data as Record<string, any>;- getDependencyGraph().clearEntity(entityId);- this.assetServer_.releaseMaterialInstance(entityId);+ const descriptors = getComponentAssetFieldDescriptors(comp.type);+ for (const desc of descriptors) {+ const ref = data[desc.field];+ if (typeof ref !== 'string' || !ref) continue;- const rawTexture = data.texture;- const textureRef = typeof rawTexture === 'string' && rawTexture !== String(INVALID_TEXTURE)- ? rawTexture : '';- if (textureRef) {- const texturePath = this.resolveAssetRef(textureRef);- const info = await this.assetServer_.loadTexture(texturePath);- textureHandle = info.handle;- getDependencyGraph().registerUsage(textureRef, entityId);- }+ const resolved = this.resolveAssetRef(ref);+ getDependencyGraph().registerUsage(ref, entityId);- const materialRef = data.material;- if (materialRef && typeof materialRef === 'string') {- const materialPath = this.resolveAssetRef(materialRef);- try {- const loaded = await this.assetServer_.loadMaterial(materialPath);- const overrides = data.materialOverrides;-- if (overrides && Object.keys(overrides).length > 0) {- materialHandle = this.assetServer_.createMaterialInstance(- materialPath, entityId, overrides- );- } else {- materialHandle = loaded.handle;+ switch (desc.type) {+ case 'texture': {+ const info = await this.assetServer_.loadTexture(resolved);+ data[desc.field] = info.handle;+ break;+ }+ case 'material': {+ try {+ const loaded = await this.assetServer_.loadMaterial(resolved);+ const overrides = data.materialOverrides;+ if (overrides && Object.keys(overrides).length > 0) {+ data[desc.field] = this.assetServer_.createMaterialInstance(+ resolved, entityId, overrides,+ );+ } else {+ data[desc.field] = loaded.handle;+ }+ } catch (err) {+ console.warn(`[EditorSceneManager] Failed to load material: ${resolved}`, err);+ data[desc.field] = INVALID_MATERIAL;+ }+ break;+ }+ case 'font': {+ try {+ data[desc.field] = await this.assetServer_.loadBitmapFont(resolved);+ } catch (err) {+ console.warn(`[EditorSceneManager] Failed to load bitmap font: ${resolved}`, err);+ data[desc.field] = INVALID_FONT;+ }+ break;}- getDependencyGraph().registerUsage(materialRef, entityId);- } catch (err) {- console.warn(`[EditorSceneManager] Failed to load material: ${materialPath}`, err);- }- }-- if (this.world_.has(entity, Sprite)) {- this.world_.remove(entity, Sprite);- }-- let spriteSize = data.size ?? DEFAULT_SPRITE_SIZE;- const entityData = this.entityDataMap_.get(entityId);- const uiRect = entityData?.components.find(c => c.type === 'UIRect');- if (uiRect?.data?.size) {- spriteSize = uiRect.data.size;- }-- this.world_.insert(entity, Sprite, {- texture: textureHandle,- color: data.color ?? { r: 1, g: 1, b: 1, a: 1 },- size: spriteSize,- uvOffset: data.uvOffset ?? { x: 0, y: 0 },- uvScale: data.uvScale ?? { x: 1, y: 1 },- layer: data.layer ?? 0,- flipX: data.flipX ?? false,- flipY: data.flipY ?? false,- material: materialHandle,- enabled: data.enabled ?? true,- });- }-- private syncText(entity: Entity, data: Record<string, any>, entityId: number): void {- const entityData = this.entityDataMap_.get(entityId);- const uiRectData = entityData ? getUIRectFromEntity(entityData) : null;-- const textData: TextData = {- content: data.content ?? '',- fontFamily: data.fontFamily ?? DEFAULT_FONT_FAMILY,- fontSize: data.fontSize ?? DEFAULT_FONT_SIZE,- color: data.color ?? { r: 1, g: 1, b: 1, a: 1 },- align: data.align ?? TextAlign.Left,- verticalAlign: data.verticalAlign ?? TextVerticalAlign.Top,- wordWrap: data.wordWrap ?? true,- overflow: data.overflow ?? TextOverflow.Visible,- lineHeight: data.lineHeight ?? DEFAULT_LINE_HEIGHT,- };-- if (!textData.content) {- if (this.world_.has(entity, Sprite)) {- this.world_.remove(entity, Sprite);}- this.textRenderer_.release(entity);- return;}- this.renderAndInsertTextSprite(entity, textData, uiRectData);- }+ const spineDesc = getComponentSpineFieldDescriptor(comp.type);+ if (spineDesc) {+ const skelRef = data[spineDesc.skeletonField] ?? '';+ const atlasRef = data[spineDesc.atlasField] ?? '';- private syncTextInput(entity: Entity, data: Record<string, any>, entityId: number): void {- const entityData = this.entityDataMap_.get(entityId);- const uiRectData = entityData ? getUIRectFromEntity(entityData) : null;-- const value = data.value ?? '';- const placeholder = data.placeholder ?? '';- const isEmpty = value.length === 0;- const displayText = isEmpty ? placeholder : value;- if (!displayText) return;-- const textData: TextData = {- content: displayText,- fontFamily: data.fontFamily ?? DEFAULT_FONT_FAMILY,- fontSize: data.fontSize ?? DEFAULT_FONT_SIZE,- color: isEmpty- ? (data.placeholderColor ?? { r: 0.6, g: 0.6, b: 0.6, a: 1 })- : (data.color ?? { r: 1, g: 1, b: 1, a: 1 }),- align: TextAlign.Left,- verticalAlign: TextVerticalAlign.Middle,- wordWrap: false,- overflow: TextOverflow.Clip,- lineHeight: data.lineHeight ?? DEFAULT_LINE_HEIGHT,- };+ if (skelRef && atlasRef) {+ const skelPath = this.resolveAssetRef(skelRef);+ const atlasPath = this.resolveAssetRef(atlasRef);- this.renderAndInsertTextSprite(entity, textData, uiRectData);- }+ getDependencyGraph().registerUsage(skelRef, entityId);+ getDependencyGraph().registerUsage(atlasRef, entityId);- private renderAndInsertTextSprite(- entity: Entity,- textData: TextData,- uiRectData: { size: { x: number; y: number } } | null,- ): void {- const result = this.textRenderer_.renderForEntity(entity, textData, uiRectData);- if (result.textureHandle === (INVALID_TEXTURE as number)) return;-- this.world_.insert(entity, Sprite, {- texture: result.textureHandle,- color: { r: 1, g: 1, b: 1, a: 1 },- size: { x: result.width, y: result.height },- uvOffset: { x: 0, y: 0 },- uvScale: { x: 1, y: 1 },- layer: TEXT_RENDER_LAYER,- flipX: false,- flipY: false,- });- }+ data[spineDesc.skeletonField] = skelPath;+ data[spineDesc.atlasField] = atlasPath;- private async syncBitmapText(entity: Entity, data: Record<string, any>, _entityId: number): Promise<void> {- let fontHandle = INVALID_FONT as number;-- const fontRef = data.font;- if (fontRef && typeof fontRef === 'string') {- try {- const fontPath = this.resolveAssetRef(fontRef);- fontHandle = await this.assetServer_.loadBitmapFont(fontPath);- } catch (err) {- console.warn(`[EditorSceneManager] Failed to load bitmap font: ${fontRef}`, err);+ if (!this.spineController_) {+ const result = await this.assetServer_.loadSpine(skelPath, atlasPath);+ if (!result.success) {+ console.warn(`[EditorSceneManager] Failed to load Spine: ${result.error}`);+ }+ }}}-- if (fontHandle === (INVALID_FONT as number)) {- return;- }-- if (this.world_.has(entity, BitmapText)) {- this.world_.remove(entity, BitmapText);- }-- this.world_.insert(entity, BitmapText, {- text: data.text ?? '',- color: data.color ?? { r: 1, g: 1, b: 1, a: 1 },- fontSize: data.fontSize ?? 1.0,- align: data.align ?? 0,- spacing: data.spacing ?? 0,- layer: data.layer ?? 0,- font: fontHandle,- enabled: data.enabled ?? true,- });}- private async syncSpineAnimation(entity: Entity, data: Record<string, any>, entityId: number): Promise<void> {- const skeletonRef = data.skeletonPath ?? '';- const atlasRef = data.atlasPath ?? '';-- if (!skeletonRef || !atlasRef) return;-- const skeletonPath = this.resolveAssetRef(skeletonRef);- const atlasPath = this.resolveAssetRef(atlasRef);+ // =========================================================================+ // Spine Instance Sync (post-load hook)+ // =========================================================================- getDependencyGraph().clearEntity(entityId);- getDependencyGraph().registerUsage(skeletonRef, entityId);- getDependencyGraph().registerUsage(atlasRef, entityId);+ private async syncSpineInstance(entityId: number, data: Record<string, any>): Promise<void> {+ if (!this.spineController_) return;- if (this.spineController_) {- await this.syncSpineViaModule(entityId, skeletonPath, atlasPath, data);- } else {- await this.syncSpineViaCore(entity, entityId, skeletonPath, atlasPath, data);- }- }+ const controller = this.spineController_;+ const skeletonPath = data.skeletonPath ?? '';+ const atlasPath = data.atlasPath ?? '';+ if (!skeletonPath || !atlasPath) return;- private async syncSpineViaModule(- entityId: number,- skeletonPath: string,- atlasPath: string,- data: Record<string, any>,- ): Promise<void> {- const controller = this.spineController_!;const cacheKey = `${skeletonPath}:${atlasPath}`;-const existingKey = this.spineInstanceKeys_.get(entityId);let instanceId = this.spineInstances_.get(entityId);@@ -973,7 +747,7 @@ export class EditorSceneManager {let skeletonHandle = this.spineSkeletons_.get(cacheKey);if (skeletonHandle === undefined) {const result = await this.assetServer_.assetLoader.loadSpineToModule(- controller, skeletonPath, atlasPath+ controller, skeletonPath, atlasPath,);if (!result.success || result.skeletonHandle === undefined) {console.warn(`[EditorSceneManager] Failed to load Spine to module: ${result.error}`);@@ -1019,51 +793,4 @@ export class EditorSceneManager {this.spineCurrentState_.set(entityId, { animation, skin, loop });}-- private async syncSpineViaCore(- entity: Entity,- entityId: number,- skeletonPath: string,- atlasPath: string,- data: Record<string, any>,- ): Promise<void> {- const result = await this.assetServer_.loadSpine(skeletonPath, atlasPath);- if (!result.success) {- console.warn(`[EditorSceneManager] Failed to load Spine: ${result.error}`);- return;- }-- let materialHandle = INVALID_MATERIAL as number;- const materialRef = data.material;- if (materialRef && typeof materialRef === 'string') {- const materialPath = this.resolveAssetRef(materialRef);- try {- const loaded = await this.assetServer_.loadMaterial(materialPath);- materialHandle = loaded.handle;- getDependencyGraph().registerUsage(materialRef, entityId);- } catch (err) {- console.warn(`[EditorSceneManager] Failed to load material: ${materialPath}`, err);- }- }-- loadComponent(this.world_, entity, {- type: 'SpineAnimation',- data: {- skeletonPath,- atlasPath,- skin: data.skin ?? DEFAULT_SPINE_SKIN,- animation: data.animation ?? '',- timeScale: data.timeScale ?? 1,- loop: data.loop ?? true,- playing: data.playing ?? true,- flipX: data.flipX ?? false,- flipY: data.flipY ?? false,- color: data.color ?? { r: 1, g: 1, b: 1, a: 1 },- layer: data.layer ?? 0,- skeletonScale: data.skeletonScale ?? 1,- material: materialHandle,- enabled: data.enabled ?? true,- },- });- }}diff --git a/editor/src/scene/uiLayoutUtils.ts b/editor/src/scene/uiLayoutUtils.tsdeleted file mode 100644index 48300b1c3..000000000--- a/editor/src/scene/uiLayoutUtils.ts+++ /dev/null@@ -1 +0,0 @@-export { computeFillAnchors, computeHandleAnchors, computeFillSize } from 'esengine';diff --git a/editor/src/services/RuntimeStoreProxy.ts b/editor/src/services/RuntimeStoreProxy.tsnew file mode 100644index 000000000..5976af1cd--- /dev/null+++ b/editor/src/services/RuntimeStoreProxy.ts@@ -0,0 +1,244 @@+import type { Entity } from 'esengine';+import type { GameViewBridge, RuntimeEntityData } from '../panels/game-view/GameViewBridge';+import type { EditorStore } from '../store/EditorStore';+import type { SceneData, EntityData, ComponentData } from '../types/SceneTypes';+import { getPlayModeService } from './PlayModeService';++export class RuntimeStoreProxy {+ private bridge_: GameViewBridge;+ private editorStore_: EditorStore;+ private runtimeCache_ = new Map<number, Record<string, Record<string, unknown>>>();+ private pendingWrites_ = new Map<string, { value: unknown; stale: boolean }>();++ constructor(bridge: GameViewBridge, editorStore: EditorStore) {+ this.bridge_ = bridge;+ this.editorStore_ = editorStore;+ }++ get scene(): SceneData {+ return this.editorStore_.scene;+ }++ get selectedEntities(): ReadonlySet<number> {+ return this.editorStore_.selectedEntities;+ }++ get selectedEntity(): Entity | null {+ return this.editorStore_.selectedEntity;+ }++ get selectedAsset() {+ return null;+ }++ get isEditingPrefab(): boolean {+ return false;+ }++ get prefabEditingPath(): string | null {+ return null;+ }++ getEntityData(entityId: number): EntityData | null {+ const pms = getPlayModeService();+ const runtimeData = pms.getRuntimeEntityData(entityId);+ if (runtimeData) {+ const cache = this.runtimeCache_.get(entityId);+ let components = runtimeData.components;+ if (cache) {+ components = components.map(comp => {+ const runtimeValues = cache[comp.type];+ if (!runtimeValues) return comp;+ return { type: comp.type, data: { ...comp.data, ...runtimeValues } };+ });+ }++ const prefix = `${entityId}:`;+ for (const [key, pw] of this.pendingWrites_) {+ if (!key.startsWith(prefix)) continue;+ for (let i = 0; i < components.length; i++) {+ const compPrefix = `${entityId}:${components[i].type}:`;+ if (key.startsWith(compPrefix)) {+ const prop = key.slice(compPrefix.length);+ components[i] = {+ type: components[i].type,+ data: { ...components[i].data, [prop]: pw.value },+ };+ }+ }+ }++ return { ...runtimeData, components };+ }+ return null;+ }++ getSelectedEntityData(): EntityData | null {+ const entity = this.selectedEntity;+ if (entity === null) return null;+ return this.getEntityData(entity as number);+ }++ getSelectedEntitiesData(): EntityData[] {+ const result: EntityData[] = [];+ for (const id of this.selectedEntities) {+ const data = this.getEntityData(id);+ if (data) result.push(data);+ }+ return result;+ }++ isEntityVisible(_entityId: number): boolean {+ return true;+ }++ getComponent(entity: Entity, type: string): ComponentData | null {+ const data = this.getEntityData(entity as number);+ return data?.components.find(c => c.type === type) ?? null;+ }++ updateProperty(+ entity: Entity,+ componentType: string,+ propertyName: string,+ _oldValue: unknown,+ newValue: unknown,+ ): void {+ this.recordPendingWrite(entity as number, componentType, propertyName, newValue);+ this.bridge_.setEntityProperty(entity as number, componentType, propertyName, newValue);+ }++ updateProperties(+ entity: Entity,+ componentType: string,+ changes: { property: string; oldValue: unknown; newValue: unknown }[],+ ): void {+ for (const change of changes) {+ this.recordPendingWrite(entity as number, componentType, change.property, change.newValue);+ this.bridge_.setEntityProperty(entity as number, componentType, change.property, change.newValue);+ }+ }++ updatePropertyDirect(+ entity: Entity,+ componentType: string,+ propertyName: string,+ newValue: unknown,+ ): void {+ this.recordPendingWrite(entity as number, componentType, propertyName, newValue);+ this.bridge_.setEntityProperty(entity as number, componentType, propertyName, newValue);+ }++ renameEntity(entity: Entity, name: string): void {+ const pms = getPlayModeService();+ pms.renameEntity(entity as number, name);+ }++ toggleVisibility(_entityId: number): void {+ // visibility toggle not applicable in play mode+ }++ removeComponent(entity: Entity, type: string): void {+ const pms = getPlayModeService();+ pms.removeComponent(entity as number, type);+ }++ reorderComponent(_entity: Entity, _fromIndex: number, _toIndex: number): void {+ // reorder not supported via bridge+ }++ addComponent(entity: Entity, type: string, data: Record<string, unknown>): void {+ const pms = getPlayModeService();+ pms.addComponent(entity as number, type, data);+ }++ deleteEntity(entity: Entity): void {+ const pms = getPlayModeService();+ pms.despawnEntity(entity as number);+ }++ createEntity(name?: string, parent?: Entity | null): Entity {+ const pms = getPlayModeService();+ const parentId = parent != null ? Number(parent) : null;+ pms.spawnEntity(name, parentId);+ return 0 as Entity;+ }++ selectEntity(entity: Entity | null, _mode?: 'replace' | 'add' | 'toggle'): void {+ this.editorStore_.selectEntity(entity, _mode);+ }++ selectEntities(entities: number[]): void {+ this.editorStore_.selectEntities(entities);+ }++ focusEntity(entityId: number): void {+ this.editorStore_.focusEntity(entityId);+ }++ onFocusEntity(listener: (entityId: number) => void): () => void {+ return this.editorStore_.onFocusEntity(listener);+ }++ subscribe(listener: any): () => void {+ return this.editorStore_.subscribe(listener);+ }++ subscribeToPropertyChanges(listener: any): () => void {+ return this.editorStore_.subscribeToPropertyChanges(listener);+ }++ isPrefabInstance(_entityId: number): boolean {+ return false;+ }++ isPrefabRoot(_entityId: number): boolean {+ return false;+ }++ getPrefabInstanceId(_entityId: number): string | undefined {+ return undefined;+ }++ getPrefabPath(_entityId: number): string | undefined {+ return undefined;+ }++ prepareForQuery(entityId: number): void {+ const prefix = `${entityId}:`;+ for (const [key, pw] of this.pendingWrites_) {+ if (key.startsWith(prefix)) {+ pw.stale = true;+ }+ }+ }++ applyRuntimeData(entityId: number, runtimeEntity: RuntimeEntityData): void {+ const prefix = `${entityId}:`;+ for (const [key, pw] of this.pendingWrites_) {+ if (key.startsWith(prefix) && pw.stale) {+ this.pendingWrites_.delete(key);+ }+ }++ const compCache: Record<string, Record<string, unknown>> = {};+ for (const comp of runtimeEntity.components) {+ compCache[comp.type] = comp.data;+ }+ this.runtimeCache_.set(entityId, compCache);+ }++ clearCache(): void {+ this.runtimeCache_.clear();+ this.pendingWrites_.clear();+ }++ private pendingKey(entityId: number, componentType: string, propertyName: string): string {+ return `${entityId}:${componentType}:${propertyName}`;+ }++ private recordPendingWrite(entityId: number, componentType: string, propertyName: string, value: unknown): void {+ const key = this.pendingKey(entityId, componentType, propertyName);+ this.pendingWrites_.set(key, { value, stale: false });+ }+}diff --git a/editor/src/store/EditorStore.ts b/editor/src/store/EditorStore.tsindex 242684aec..66605fbd4 100644--- a/editor/src/store/EditorStore.ts+++ b/editor/src/store/EditorStore.ts@@ -3,7 +3,7 @@ import type { SceneData, EntityData, ComponentData } from '../types/SceneTypes';import { createEmptyScene } from '../types/SceneTypes';import { CommandHistory, type Command } from '../commands';import { WorldTransformCache } from '../transform/WorldTransformCache';-import type { Transform } from '../math/Transform';+import type { TransformValue } from '../math/Transform';import { SelectionService } from './SelectionService';import { SceneOperations } from './SceneOperations';import { PrefabEditService } from './PrefabEditService';@@ -72,6 +72,13 @@ export interface ComponentChangeEvent {export type ComponentChangeListener = (event: ComponentChangeEvent) => void;+export interface SceneSnapshot {+ scene: SceneData;+ selectedEntities: number[];+ isDirty: boolean;+ filePath: string | null;+}+// =============================================================================// EditorStore// =============================================================================@@ -225,6 +232,26 @@ export class EditorStore {this.notify('scene');}+ takeSnapshot(): SceneSnapshot {+ return {+ scene: JSON.parse(JSON.stringify(this.state_.scene)),+ selectedEntities: [...this.state_.selectedEntities],+ isDirty: this.state_.isDirty,+ filePath: this.state_.filePath,+ };+ }++ restoreSnapshot(snapshot: SceneSnapshot): void {+ this.state_.scene = snapshot.scene;+ this.state_.selectedEntities = new Set(snapshot.selectedEntities);+ this.state_.isDirty = snapshot.isDirty;+ this.state_.filePath = snapshot.filePath;+ this.rebuildEntityMap();+ this.worldTransforms_.setScene(this.state_.scene);+ this.notifySceneSync();+ this.notify('scene');+ }+markSaved(filePath: string | null = null): void {this.state_.isDirty = false;if (filePath) {@@ -408,7 +435,7 @@ export class EditorStore {// World Transform// =========================================================================- getWorldTransform(entityId: number): Transform {+ getWorldTransform(entityId: number): TransformValue {return this.worldTransforms_.getWorldTransform(entityId);}diff --git a/editor/src/sync/RuntimeSyncService.ts b/editor/src/sync/RuntimeSyncService.tsdeleted file mode 100644index f5e8a74a3..000000000--- a/editor/src/sync/RuntimeSyncService.ts+++ /dev/null@@ -1,310 +0,0 @@-/**- * @file RuntimeSyncService.ts- * @brief Syncs editor state changes to runtime rendering- */--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';-import { ButtonState, FillDirection } from 'esengine';-import { computeFillAnchors, computeHandleAnchors, computeFillSize } from '../scene/uiLayoutUtils';--export class RuntimeSyncService {- private unsubscribes_: (() => void)[] = [];- private dirtyEntities_ = new Set<number>();- private rafId_: number | null = null;-- constructor(- private store_: EditorStore,- private sceneManager_: EditorSceneManager- ) {- this.setup();- }-- private setup(): void {- this.unsubscribes_.push(- this.store_.subscribeToPropertyChanges((event) => {- this.onPropertyChange(event);- })- );-- this.unsubscribes_.push(- this.store_.subscribeToHierarchyChanges((event) => {- this.onHierarchyChange(event);- })- );-- this.unsubscribes_.push(- this.store_.subscribeToVisibilityChanges((event) => {- this.onVisibilityChange(event);- })- );-- 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') {- this.onMaterialModified(event.path);- }- })- );-- this.unsubscribes_.push(- getAssetEventBus().on('texture', (event) => {- if (event.type === 'asset:modified') {- this.onTextureModified(event.path);- }- })- );- }-- private onVisibilityChange(event: VisibilityChangeEvent): void {- if (event.visible) {- this.sceneManager_.showEntity(event.entity);- } else {- this.sceneManager_.hideEntity(event.entity);- }- }-- 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);- }-- if (event.componentType === 'UIRect' || event.componentType === 'ScreenSpace') {- this.sceneManager_.syncEntityTransform(event.entity);- this.sceneManager_.syncScreenSpaceDescendants(event.entity);- }-- if (event.componentType === 'Text') {- this.sceneManager_.syncTextForEntity(event.entity);- }-- this.scheduleEntityUpdate(event.entity);-- if (event.componentType === 'Canvas') {- this.syncCanvasToCamera(event.entity);- }-- if (event.componentType === 'Button') {- this.syncButtonTransitionColor(event.entity);- }-- if (event.componentType === 'TextInput' && event.propertyName === 'backgroundColor') {- this.store_.updatePropertyDirect(event.entity, 'Sprite', 'color', event.newValue);- }-- if (event.componentType === 'Slider') {- this.syncSliderChildren(event.entity);- }-- if (event.componentType === 'ProgressBar') {- this.syncProgressBarChildren(event.entity);- }- }-- private syncCanvasToCamera(canvasEntityId: number): void {- const canvasData = this.store_.getEntityData(canvasEntityId);- if (!canvasData) return;-- const canvasComp = canvasData.components.find(c => c.type === 'Canvas');- const resolution = canvasComp?.data?.designResolution as { x: number; y: number } | undefined;- if (!resolution) return;-- const orthoSize = resolution.y / 2;-- for (const entity of this.store_.scene.entities) {- const cameraComp = entity.components.find(c => c.type === 'Camera');- if (!cameraComp) continue;-- this.store_.updatePropertyDirect(entity.id, 'Camera', 'orthoSize', orthoSize);- this.scheduleEntityUpdate(entity.id);- break;- }- }-- private syncButtonTransitionColor(entityId: number): void {- const entityData = this.store_.getEntityData(entityId);- if (!entityData) return;-- const buttonComp = entityData.components.find(c => c.type === 'Button');- if (!buttonComp) return;-- const transition = buttonComp.data.transition as {- normalColor: { r: number; g: number; b: number; a: number };- hoveredColor: { r: number; g: number; b: number; a: number };- pressedColor: { r: number; g: number; b: number; a: number };- disabledColor: { r: number; g: number; b: number; a: number };- } | null;- if (!transition) return;-- const spriteComp = entityData.components.find(c => c.type === 'Sprite');- if (!spriteComp) return;-- const state = (buttonComp.data.state as number) ?? ButtonState.Normal;- const colorMap: Record<number, { r: number; g: number; b: number; a: number }> = {- [ButtonState.Normal]: transition.normalColor,- [ButtonState.Hovered]: transition.hoveredColor,- [ButtonState.Pressed]: transition.pressedColor,- [ButtonState.Disabled]: transition.disabledColor,- };- const color = colorMap[state] ?? transition.normalColor;-- this.store_.updatePropertyDirect(entityId, 'Sprite', 'color', { ...color });- this.scheduleEntityUpdate(entityId);- }-- private syncSliderChildren(entityId: number): void {- const entityData = this.store_.getEntityData(entityId);- if (!entityData) return;-- const sliderComp = entityData.components.find(c => c.type === 'Slider');- if (!sliderComp) return;-- const value = sliderComp.data.value as number ?? 0;- const minValue = sliderComp.data.minValue as number ?? 0;- const maxValue = sliderComp.data.maxValue as number ?? 1;- const direction = sliderComp.data.direction as number ?? FillDirection.LeftToRight;- const fillEntity = sliderComp.data.fillEntity as number ?? 0;- const handleEntity = sliderComp.data.handleEntity as number ?? 0;-- const range = maxValue - minValue;- const normalizedValue = range > 0 ? (value - minValue) / range : 0;-- const uiRectComp = entityData.components.find(c => c.type === 'UIRect');- const sliderW = (uiRectComp?.data?.size as { x: number; y: number })?.x ?? 0;- const sliderH = (uiRectComp?.data?.size as { x: number; y: number })?.y ?? 0;-- if (fillEntity !== 0) {- const fillAnchors = computeFillAnchors(direction, normalizedValue);- this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'anchorMin', fillAnchors.anchorMin);- this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'anchorMax', fillAnchors.anchorMax);- this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'offsetMin', fillAnchors.offsetMin);- this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'offsetMax', fillAnchors.offsetMax);- this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'size',- computeFillSize(direction, normalizedValue, sliderW, sliderH));- this.scheduleEntityUpdate(fillEntity);- }-- if (handleEntity !== 0) {- const handleAnchors = computeHandleAnchors(direction, normalizedValue);- this.store_.updatePropertyDirect(handleEntity, 'UIRect', 'anchorMin', handleAnchors.anchorMin);- this.store_.updatePropertyDirect(handleEntity, 'UIRect', 'anchorMax', handleAnchors.anchorMax);- this.store_.updatePropertyDirect(handleEntity, 'UIRect', 'offsetMin', { x: 0, y: 0 });- this.store_.updatePropertyDirect(handleEntity, 'UIRect', 'offsetMax', { x: 0, y: 0 });- this.scheduleEntityUpdate(handleEntity);- }- }-- private syncProgressBarChildren(entityId: number): void {- const entityData = this.store_.getEntityData(entityId);- if (!entityData) return;-- const barComp = entityData.components.find(c => c.type === 'ProgressBar');- if (!barComp) return;-- const value = Math.max(0, Math.min(1, barComp.data.value as number ?? 0));- const direction = barComp.data.direction as number ?? FillDirection.LeftToRight;- const fillEntity = barComp.data.fillEntity as number ?? 0;-- const uiRectComp = entityData.components.find(c => c.type === 'UIRect');- const barW = (uiRectComp?.data?.size as { x: number; y: number })?.x ?? 0;- const barH = (uiRectComp?.data?.size as { x: number; y: number })?.y ?? 0;-- if (fillEntity !== 0) {- const fillAnchors = computeFillAnchors(direction, value);- this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'anchorMin', fillAnchors.anchorMin);- this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'anchorMax', fillAnchors.anchorMax);- this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'offsetMin', fillAnchors.offsetMin);- this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'offsetMax', fillAnchors.offsetMax);- this.store_.updatePropertyDirect(fillEntity, 'UIRect', 'size',- computeFillSize(direction, value, barW, barH));- this.scheduleEntityUpdate(fillEntity);- }- }-- private onHierarchyChange(event: HierarchyChangeEvent): void {- this.sceneManager_.reparentEntity(event.entity, event.newParent);- }-- private onMaterialModified(path: string): void {- const users = getDependencyGraph().getUsers(path);- for (const entityId of users) {- this.scheduleEntityUpdate(entityId);- }- }-- private onTextureModified(path: string): void {- const users = getDependencyGraph().getUsers(path);- for (const entityId of users) {- this.scheduleEntityUpdate(entityId);- }- }-- private scheduleEntityUpdate(entityId: number): void {- this.dirtyEntities_.add(entityId);- if (this.rafId_ !== null) return;- this.rafId_ = requestAnimationFrame(() => {- this.rafId_ = null;- this.flushDirtyEntities();- });- }-- private flushDirtyEntities(): void {- const entities = [...this.dirtyEntities_];- this.dirtyEntities_.clear();- for (const entityId of entities) {- this.syncEntity(entityId);- }- }-- private async syncEntity(entityId: number): Promise<void> {- if (!this.store_.isEntityVisible(entityId)) return;- const entityData = this.store_.getEntityData(entityId);- if (!entityData) return;- await this.sceneManager_.updateEntity(entityId, entityData.components, entityData);- }-- dispose(): void {- if (this.rafId_ !== null) {- cancelAnimationFrame(this.rafId_);- this.rafId_ = null;- }- this.dirtyEntities_.clear();-- for (const unsubscribe of this.unsubscribes_) {- unsubscribe();- }- this.unsubscribes_ = [];- }-}diff --git a/editor/src/sync/index.ts b/editor/src/sync/index.tsdeleted file mode 100644index 471600a88..000000000--- a/editor/src/sync/index.ts+++ /dev/null@@ -1,6 +0,0 @@-/**- * @file index.ts- * @brief Sync module exports- */--export { RuntimeSyncService } from './RuntimeSyncService';