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
feat: add full live-edit play mode
esengine8cf07dfc8409
diff --git a/desktop/src-tauri/src/preview_template.html b/desktop/src-tauri/src/preview_template.htmlindex f585942cf..c40d61f95 100644--- a/desktop/src-tauri/src/preview_template.html+++ b/desktop/src-tauri/src/preview_template.html@@ -127,6 +127,44 @@setEntityProperty(msg.entityId, msg.component, msg.property, msg.value);response = { success: true };break;+ case 'spawn-entity': {+ const world = gameApp.world;+ const sdk = window.__esSdk;+ const entity = world.spawn();+ const nameDef = sdk.getComponent('Name');+ if (nameDef) world.insert(Number(entity), nameDef, { value: msg.name || 'New Entity' });+ if (msg.parentId != null) world.setParent(Number(entity), msg.parentId);+ response = getEntityData(Number(entity));+ break;+ }+ case 'despawn-entity':+ gameApp.world.despawn(msg.entityId);+ response = { success: true };+ break;+ case 'add-component': {+ const compDef = window.__esSdk.getComponent(msg.componentType);+ if (compDef) gameApp.world.insert(msg.entityId, compDef, msg.data || {});+ response = { success: true };+ break;+ }+ case 'remove-component': {+ const compDef = window.__esSdk.getComponent(msg.componentType);+ if (compDef) gameApp.world.remove(msg.entityId, compDef);+ response = { success: true };+ break;+ }+ case 'rename-entity': {+ const nameDef = window.__esSdk.getComponent('Name');+ if (nameDef) gameApp.world.insert(msg.entityId, nameDef, { value: msg.name });+ response = { success: true };+ break;+ }+ case 'reparent-entity': {+ if (msg.newParentId != null) gameApp.world.setParent(msg.entityId, msg.newParentId);+ else gameApp.world.removeParent(msg.entityId);+ response = { success: true };+ break;+ }case 'query-stats': {const entities = gameApp?.world?.getAllEntities() ?? [];response = { entityCount: entities.length, paused: gameApp?.isPaused() ?? false };@@ -195,10 +233,14 @@}function getComponentTypes(world, entityId) {+ const sdk = window.__esSdk;try {if (world.getComponentTypes) {const types = world.getComponentTypes(entityId);- return types.map(t => String(t));+ return types.map(t => String(t)).filter(t => {+ if (!sdk) return true;+ return sdk.getComponent(t) != null;+ });}} catch {}return [];diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.tsindex 0417b2bba..40a7b4652 100644--- a/editor/src/panels/InspectorPanel.ts+++ b/editor/src/panels/InspectorPanel.ts@@ -19,7 +19,8 @@ import { renderBitmapFontInspector } from './inspector/BitmapFontInspector';import { renderFolderInspector } from './inspector/FolderInspector';import { renderScriptInspector, renderSceneInspector, renderFileInspector } from './inspector/FileInspector';import { getPlayModeService } from '../services/PlayModeService';-import { renderRuntimeEntity, updateRuntimeEntityValues } from './inspector/RuntimeEntityRenderer';+import { RuntimeStoreProxy } from '../services/RuntimeStoreProxy';+import { renderRuntimeEntity } from './inspector/RuntimeEntityRenderer';// =============================================================================// InspectorPanel@@ -46,7 +47,9 @@ export class InspectorPanel {private playMode_: boolean = false;private playModeCleanups_: (() => void)[] = [];private runtimeEntityId_: number | null = null;- private runtimeRefreshTimer_: ReturnType<typeof setInterval> | null = null;+ private runtimeRefreshRafId_: number = 0;+ private runtimeRefreshPending_ = false;+ private runtimeProxy_: RuntimeStoreProxy | null = null;constructor(container: HTMLElement, store: EditorStore) {this.container_ = container;@@ -81,19 +84,25 @@ export class InspectorPanel {if (this.playMode_) {this.container_.classList.add('es-play-mode');hideMaterialPreview(this.materialPreviewState_);+ if (pms.bridge) {+ this.runtimeProxy_ = new RuntimeStoreProxy(+ pms.bridge, this.store_+ );+ }} else {this.container_.classList.remove('es-play-mode');this.stopRuntimeRefresh();this.runtimeEntityId_ = null;+ this.runtimeProxy_ = null;this.render();}}),pms.onSelectionChange((entityId) => {if (!this.playMode_) return;- if (entityId === this.runtimeEntityId_) return;+ if (entityId !== null && entityId === this.runtimeEntityId_) return;this.runtimeEntityId_ = entityId;if (entityId !== null) {- this.renderRuntimeEntity(entityId);+ this.renderPlayModeEntity(entityId);} else {this.renderPlayModeEmpty();}@@ -364,7 +373,7 @@ export class InspectorPanel {// Play Mode (Runtime Inspector)// =========================================================================- private async renderRuntimeEntity(entityId: number): Promise<void> {+ private async renderPlayModeEntity(runtimeEntityId: number): Promise<void> {this.stopRuntimeRefresh();this.disposeEditors();this.cleanupImageUrl();@@ -373,29 +382,78 @@ export class InspectorPanel {hideMaterialPreview(this.materialPreviewState_);const pms = getPlayModeService();- const data = await pms.querySelectedEntity();- if (!data || this.runtimeEntityId_ !== entityId) return;+ if (this.runtimeProxy_) {+ const freshData = await pms.queryEntityByRuntimeId(runtimeEntityId);+ if (!freshData || this.runtimeEntityId_ !== runtimeEntityId) return;++ this.runtimeProxy_.applyRuntimeData(runtimeEntityId, freshData);+ this.rebuildPlayModeEntity(runtimeEntityId as Entity);+ this.startRuntimeRefreshLoop(runtimeEntityId);+ } else {+ const freshData = await pms.queryEntityByRuntimeId(runtimeEntityId);+ if (!freshData || this.runtimeEntityId_ !== runtimeEntityId) return;++ this.contentContainer_.innerHTML = '';+ renderRuntimeEntity(this.contentContainer_, freshData, pms.bridge);+ this.updateFooter(`${freshData.components.length} components (Runtime)`);+ }+ }++ private rebuildPlayModeEntity(entity: Entity): void {+ if (!this.runtimeProxy_) return;+ const proxy = this.runtimeProxy_ as any;+ const entityData = proxy.getEntityData(entity as number);+ if (!entityData) {+ this.contentContainer_.innerHTML = '<div class="es-inspector-empty">Entity not found</div>';+ this.updateFooter('Error');+ return;+ }++ const componentCount = entityData.components.length;+ this.currentEntity_ = entity;+ this.currentAssetPath_ = null;+ this.currentComponentCount_ = componentCount;+ this.currentComponentOrder_ = entityData.components.map((c: any) => c.type).join(',');+ this.currentPrefabPath_ = undefined;+ this.disposeEditors();this.contentContainer_.innerHTML = '';- renderRuntimeEntity(this.contentContainer_, data, pms.bridge);- this.updateFooter(`${data.components.length} components (Runtime)`);- this.runtimeRefreshTimer_ = setInterval(async () => {- if (this.runtimeEntityId_ !== entityId) {- this.stopRuntimeRefresh();- return;- }- const fresh = await pms.querySelectedEntity();- if (!fresh) {- this.stopRuntimeRefresh();- this.contentContainer_.innerHTML = '<div class="es-inspector-empty">Entity despawned</div>';- this.updateFooter('Runtime mode');- return;- }- if (this.runtimeEntityId_ === entityId) {- updateRuntimeEntityValues(this.contentContainer_, fresh);+ renderEntityHeader(this.contentContainer_, entityData.name, entity, proxy);++ for (let i = 0; i < entityData.components.length; i++) {+ renderComponent(+ this.contentContainer_, entity, entityData.components[i],+ proxy, this.editors_, i, entityData.components.length+ );+ }++ renderAddComponentButton(this.contentContainer_, entity, entityData.components, proxy);+ this.updateFooter(`${componentCount} components (Live)`);+ }++ private updatePlayModeEditors(editorEntityId: number): void {+ if (!this.runtimeProxy_) return;+ const proxy = this.runtimeProxy_ as any;+ const entityData = proxy.getEntityData(editorEntityId);+ if (!entityData) return;++ for (const info of this.editors_) {+ const component = entityData.components.find((c: any) => c.type === info.componentType);+ if (component) {+ if (info.propertyName === '*') {+ const defaults = getDefaultComponentData(component.type);+ info.editor.update({ ...defaults, ...component.data });+ } else {+ let value = component.data[info.propertyName];+ if (value === undefined) {+ const defaults = getDefaultComponentData(component.type);+ value = defaults[info.propertyName];+ }+ info.editor.update(value);+ }}- }, 500);+ }}private renderPlayModeEmpty(): void {@@ -404,16 +462,51 @@ export class InspectorPanel {this.cleanupImageUrl();this.currentEntity_ = null;this.currentAssetPath_ = null;- this.contentContainer_.innerHTML = '<div class="es-inspector-empty">Select a runtime entity</div>';+ this.contentContainer_.innerHTML = '<div class="es-inspector-empty">Select an entity</div>';hideMaterialPreview(this.materialPreviewState_);- this.updateFooter('Runtime mode');+ this.updateFooter('Live mode');+ }++ private startRuntimeRefreshLoop(runtimeEntityId: number): void {+ const pms = getPlayModeService();+ const tick = async () => {+ if (this.runtimeEntityId_ !== runtimeEntityId) return;+ if (this.runtimeRefreshPending_) {+ this.runtimeRefreshRafId_ = requestAnimationFrame(tick);+ return;+ }+ this.runtimeRefreshPending_ = true;+ try {+ if (this.runtimeProxy_) {+ this.runtimeProxy_.prepareForQuery(runtimeEntityId);+ }+ const fresh = await pms.queryEntityByRuntimeId(runtimeEntityId);+ if (this.runtimeEntityId_ !== runtimeEntityId) return;+ if (!fresh) {+ this.contentContainer_.innerHTML = '<div class="es-inspector-empty">Entity despawned</div>';+ this.updateFooter('Runtime mode');+ return;+ }+ if (this.runtimeProxy_) {+ this.runtimeProxy_.applyRuntimeData(runtimeEntityId, fresh);+ this.updatePlayModeEditors(runtimeEntityId);+ }+ } finally {+ this.runtimeRefreshPending_ = false;+ }+ if (this.runtimeEntityId_ === runtimeEntityId) {+ this.runtimeRefreshRafId_ = requestAnimationFrame(tick);+ }+ };+ this.runtimeRefreshRafId_ = requestAnimationFrame(tick);}private stopRuntimeRefresh(): void {- if (this.runtimeRefreshTimer_) {- clearInterval(this.runtimeRefreshTimer_);- this.runtimeRefreshTimer_ = null;+ if (this.runtimeRefreshRafId_) {+ cancelAnimationFrame(this.runtimeRefreshRafId_);+ this.runtimeRefreshRafId_ = 0;}+ this.runtimeRefreshPending_ = false;}// =========================================================================diff --git a/editor/src/panels/game-view/GameViewBridge.ts b/editor/src/panels/game-view/GameViewBridge.tsindex 12218ca1d..cb2eab420 100644--- a/editor/src/panels/game-view/GameViewBridge.ts+++ b/editor/src/panels/game-view/GameViewBridge.ts@@ -89,6 +89,30 @@ export class GameViewBridge {return this.request('query-stats');}+ async spawnEntity(name?: string, parentId?: number | null): Promise<RuntimeEntityData> {+ return this.request('spawn-entity', { name, parentId });+ }++ async despawnEntity(entityId: number): Promise<void> {+ await this.request('despawn-entity', { entityId });+ }++ async addComponent(entityId: number, componentType: string, data?: Record<string, unknown>): Promise<void> {+ await this.request('add-component', { entityId, componentType, data });+ }++ async removeComponent(entityId: number, componentType: string): Promise<void> {+ await this.request('remove-component', { entityId, componentType });+ }++ async renameEntity(entityId: number, name: string): Promise<void> {+ await this.request('rename-entity', { entityId, name });+ }++ async reparentEntity(entityId: number, newParentId: number | null): Promise<void> {+ await this.request('reparent-entity', { entityId, newParentId });+ }+on(event: string, handler: EventHandler): () => void {if (!this.listeners_.has(event)) {this.listeners_.set(event, new Set());diff --git a/editor/src/panels/hierarchy/HierarchyPanel.ts b/editor/src/panels/hierarchy/HierarchyPanel.tsindex d80bd879f..5e0c343a8 100644--- a/editor/src/panels/hierarchy/HierarchyPanel.ts+++ b/editor/src/panels/hierarchy/HierarchyPanel.ts@@ -11,9 +11,8 @@ import { performSearch, selectNextResult, selectPreviousResult, focusSelectedResimport { setupKeyboard, selectRange } from './HierarchyKeyboard';import { setupDragAndDrop } from './HierarchyDragDrop';import { showEntityContextMenu, duplicateEntity, createEntityFromAsset } from './HierarchyContextMenu';-import { getPlayModeService } from '../../services/PlayModeService';-import type { RuntimeEntityData } from '../game-view/GameViewBridge';-import type { EntityData } from '../../types/SceneTypes';+import { showContextMenu, type ContextMenuItem } from '../../ui/ContextMenu';+import { getPlayModeService, runtimeToEntityData } from '../../services/PlayModeService';export class HierarchyPanel implements HierarchyState {private container_: HTMLElement;@@ -42,9 +41,10 @@ export class HierarchyPanel implements HierarchyState {lastClickEntityId: number | null = null;lastClickTime: number = 0;playMode: boolean = false;+ runtimeEntities?: HierarchyState['runtimeEntities'];private playModeCleanups_: (() => void)[] = [];private toolbar_: HTMLElement | null = null;- private editorExpandedIds_: Set<number> | null = null;+ private savedExpandedIds_: Set<number> | null = null;constructor(container: HTMLElement, store: EditorStore) {this.container_ = container;@@ -104,21 +104,23 @@ export class HierarchyPanel implements HierarchyState {this.playMode = state === 'playing';if (this.playMode) {this.container_.classList.add('es-play-mode');- this.setToolbarDisabled(true);- this.editorExpandedIds_ = new Set(this.expandedIds);- this.expandedIds = new Set();+ this.savedExpandedIds_ = new Set(this.expandedIds);+ this.updateRuntimeEntities();} else {this.container_.classList.remove('es-play-mode');- this.setToolbarDisabled(false);- if (this.editorExpandedIds_) {- this.expandedIds = this.editorExpandedIds_;- this.editorExpandedIds_ = null;+ this.runtimeEntities = undefined;+ if (this.savedExpandedIds_) {+ this.expandedIds = this.savedExpandedIds_;+ this.savedExpandedIds_ = null;}}this.render();}),pms.onEntityListUpdate(() => {- if (this.playMode) this.render();+ if (this.playMode) {+ this.updateRuntimeEntities();+ this.render();+ }}),pms.onSelectionChange(() => {if (this.playMode) this.renderVisibleRows();@@ -126,6 +128,26 @@ export class HierarchyPanel implements HierarchyState {);}+ private updateRuntimeEntities(): void {+ const pms = getPlayModeService();+ const entities = pms.runtimeEntities.map(runtimeToEntityData);++ const childrenMap = new Map<number | null, number[]>();+ for (const entity of entities) {+ const parent = entity.parent;+ if (!childrenMap.has(parent)) childrenMap.set(parent, []);+ childrenMap.get(parent)!.push(entity.id);+ }+ for (const entity of entities) {+ entity.children = childrenMap.get(entity.id) ?? [];+ if (entity.children.length > 0) {+ this.expandedIds.add(entity.id);+ }+ }++ this.runtimeEntities = entities;+ }+dispose(): void {for (const cleanup of this.playModeCleanups_) cleanup();this.playModeCleanups_ = [];@@ -144,7 +166,12 @@ export class HierarchyPanel implements HierarchyState {}private onStoreNotify(dirtyFlags?: ReadonlySet<DirtyFlag>): void {- if (this.playMode) return;+ if (this.playMode) {+ if (dirtyFlags?.has('selection')) {+ this.renderVisibleRows();+ }+ return;+ }if (dirtyFlags && !dirtyFlags.has('scene') && !dirtyFlags.has('hierarchy') && !dirtyFlags.has('selection')) {return;}@@ -162,12 +189,18 @@ export class HierarchyPanel implements HierarchyState {private setupEvents(): void {const addBtn = this.container_.querySelector('[data-action="add"]');addBtn?.addEventListener('click', () => {+ if (this.playMode) {+ const pms = getPlayModeService();+ pms.spawnEntity();+ return;+ }const entity = this.store.createEntity();- this.store.addComponent(entity, 'LocalTransform', getInitialComponentData('LocalTransform'));+ this.store.addComponent(entity, 'Transform', getInitialComponentData('Transform'));});const dupBtn = this.container_.querySelector('[data-action="duplicate"]');dupBtn?.addEventListener('click', () => {+ if (this.playMode) return;const selected = this.store.selectedEntity;if (selected !== null) {duplicateEntity(this, selected);@@ -182,7 +215,8 @@ export class HierarchyPanel implements HierarchyState {const expandAllBtn = this.container_.querySelector('[data-action="expand-all"]');expandAllBtn?.addEventListener('click', () => {- for (const entity of this.store.scene.entities) {+ const entities = this.runtimeEntities ?? this.store.scene.entities;+ for (const entity of entities) {if (entity.children.length > 0) {this.expandedIds.add(entity.id);}@@ -239,7 +273,9 @@ export class HierarchyPanel implements HierarchyState {if (!item?.classList.contains('es-hierarchy-item')) return;const entityId = parseInt(item.dataset.entityId ?? '', 10);if (!isNaN(entityId)) {- getPlayModeService().selectEntity(entityId);+ this.store.selectEntity(entityId as Entity, 'replace');+ const pms = getPlayModeService();+ pms.selectEntity(entityId);}return;}@@ -304,7 +340,14 @@ export class HierarchyPanel implements HierarchyState {});this.treeContainer.addEventListener('contextmenu', (e) => {- if (this.playMode) { e.preventDefault(); return; }+ if (this.playMode) {+ e.preventDefault();+ const target = e.target as HTMLElement;+ const item = target.closest('.es-hierarchy-item') as HTMLElement;+ const entityId = item ? parseInt(item.dataset.entityId ?? '', 10) : NaN;+ this.showPlayModeContextMenu(e.clientX, e.clientY, isNaN(entityId) ? null : entityId);+ return;+ }e.preventDefault();const target = e.target as HTMLElement;const item = target.closest('.es-hierarchy-item') as HTMLElement;@@ -323,8 +366,41 @@ export class HierarchyPanel implements HierarchyState {setupDragAndDrop(this, (asset, parent) => createEntityFromAsset(this, asset, parent));}+ private showPlayModeContextMenu(x: number, y: number, entityId: number | null): void {+ const pms = getPlayModeService();+ const items: ContextMenuItem[] = [];++ if (entityId !== null) {+ items.push(+ { label: 'Rename', icon: icons.pencil(14), onClick: () => {+ this.renamingEntityId = entityId;+ this.renderVisibleRows();+ } },+ { label: 'Delete', icon: icons.trash(14), onClick: () => {+ pms.despawnEntity(entityId);+ } },+ { label: '', separator: true },+ );+ }++ items.push(+ { label: 'Create Empty Entity', icon: icons.plus(14), onClick: () => {+ const parentId = entityId;+ pms.spawnEntity(undefined, parentId);+ } },+ );++ showContextMenu({ x, y, items });+ }+private startInlineRename(entityId: number): void {- const entityData = this.store.getEntityData(entityId);+ let entityData;+ if (this.playMode) {+ const pms = getPlayModeService();+ entityData = pms.getRuntimeEntityData(entityId);+ } else {+ entityData = this.store.getEntityData(entityId);+ }if (!entityData) return;this.renamingEntityId = entityId;@@ -344,7 +420,12 @@ export class HierarchyPanel implements HierarchyState {const commitRename = () => {const newName = input.value.trim();if (newName && newName !== entityData.name) {- this.store.renameEntity(entityId as Entity, newName);+ if (this.playMode) {+ const pms = getPlayModeService();+ pms.renameEntity(entityId, newName);+ } else {+ this.store.renameEntity(entityId as Entity, newName);+ }}this.renamingEntityId = null;this.renderVisibleRows();@@ -375,16 +456,12 @@ export class HierarchyPanel implements HierarchyState {}render(): void {- if (this.playMode) {- this.renderPlayMode();- return;- }-- const scene = this.store.scene;const selectedEntity = this.store.selectedEntity;if (this.prefabEditBar_) {- if (this.store.isEditingPrefab) {+ if (this.playMode) {+ this.prefabEditBar_.style.display = 'none';+ } else if (this.store.isEditingPrefab) {this.prefabEditBar_.style.display = '';const nameEl = this.prefabEditBar_.querySelector('.es-prefab-edit-name');if (nameEl) {@@ -421,8 +498,8 @@ export class HierarchyPanel implements HierarchyState {if (!this.footerContainer_) return;if (this.playMode) {- const count = getPlayModeService().runtimeEntities.length;- this.footerContainer_.textContent = `${count} ${count === 1 ? 'entity' : 'entities'} (Runtime)`;+ const count = this.runtimeEntities?.length ?? 0;+ this.footerContainer_.textContent = `${count} entities (Live)`;return;}@@ -485,58 +562,6 @@ export class HierarchyPanel implements HierarchyState {}}- private renderPlayMode(): void {- if (this.prefabEditBar_) {- this.prefabEditBar_.style.display = 'none';- }-- const entities = getPlayModeService().runtimeEntities;- const entityMap = new Map<number, RuntimeEntityData>();- for (const e of entities) entityMap.set(e.entityId, e);-- const rows: FlattenedRow[] = [];- const visited = new Set<number>();- const buildRows = (parentId: number | null, depth: number) => {- for (const e of entities) {- if (visited.has(e.entityId)) continue;- if ((e.parentId ?? null) !== parentId) continue;- visited.add(e.entityId);- const adapted = runtimeToEntityData(e);- const hasChildren = (e.children?.length ?? 0) > 0;- const isExpanded = this.expandedIds.has(e.entityId);- rows.push({ entity: adapted, depth, hasChildren, isExpanded });- if (hasChildren && isExpanded) {- buildRows(e.entityId, depth + 1);- }- }- };- buildRows(null, 0);-- this.flatRows = rows;- this.scrollContent.style.height = `${rows.length * ROW_HEIGHT}px`;- this.lastVisibleStart_ = -1;- this.lastVisibleEnd_ = -1;- this.renderVisibleRows();- this.updateFooter();- }-- private setToolbarDisabled(disabled: boolean): void {- if (!this.toolbar_) return;- const buttons = this.toolbar_.querySelectorAll('[data-action="add"], [data-action="duplicate"], [data-action="expand-all"], [data-action="collapse-all"]');- for (const btn of buttons) {- (btn as HTMLButtonElement).disabled = disabled;- }- if (this.searchInput) {- this.searchInput.disabled = disabled;- if (disabled) {- this.searchInput.value = '';- this.searchFilter = '';- this.searchResults = [];- this.selectedResultIndex = -1;- }- }- }-private onScroll(): void {if (this.scrollRafId_) return;this.scrollRafId_ = requestAnimationFrame(() => {@@ -548,14 +573,3 @@ export class HierarchyPanel implements HierarchyState {});}}--function runtimeToEntityData(r: RuntimeEntityData): EntityData {- return {- id: r.entityId,- name: r.name,- parent: r.parentId ?? null,- children: r.children ?? [],- components: r.components.map(c => ({ type: c.type, data: c.data })),- visible: true,- };-}diff --git a/editor/src/panels/hierarchy/HierarchySearch.ts b/editor/src/panels/hierarchy/HierarchySearch.tsindex d81d689bc..fda7d3449 100644--- a/editor/src/panels/hierarchy/HierarchySearch.ts+++ b/editor/src/panels/hierarchy/HierarchySearch.ts@@ -9,9 +9,9 @@ export function performSearch(state: HierarchyState): void {return;}- const scene = state.store.scene;+ const entities = state.runtimeEntities ?? state.store.scene.entities;const results = fuzzyFilter(- scene.entities,+ entities,state.searchFilter,(entity) => entity.name);diff --git a/editor/src/panels/hierarchy/HierarchyTree.ts b/editor/src/panels/hierarchy/HierarchyTree.tsindex d890941bc..2d028df20 100644--- a/editor/src/panels/hierarchy/HierarchyTree.ts+++ b/editor/src/panels/hierarchy/HierarchyTree.ts@@ -4,11 +4,10 @@ import type { FuzzyMatch } from '../../utils/fuzzy';import { icons } from '../../utils/icons';import { escapeHtml } from '../../utils/html';import type { FlattenedRow, HierarchyState } from './HierarchyTypes';-import { getPlayModeService } from '../../services/PlayModeService';export function buildFlatRows(state: HierarchyState): FlattenedRow[] {const rows: FlattenedRow[] = [];- const scene = state.store.scene;+ const entities = state.runtimeEntities ?? state.store.scene.entities;if (state.searchFilter) {for (const result of state.searchResults) {@@ -22,35 +21,48 @@ export function buildFlatRows(state: HierarchyState): FlattenedRow[] {return rows;}- const roots = scene.entities.filter(e => e.parent === null);- flattenDFS(state, roots, 0, rows);+ const roots = entities.filter(e => e.parent === null);+ const entityMap = state.runtimeEntities+ ? new Map(state.runtimeEntities.map(e => [e.id, e]))+ : null;+ flattenDFS(state, roots, 0, rows, entityMap);return rows;}-function flattenDFS(state: HierarchyState, entities: EntityData[], depth: number, rows: FlattenedRow[]): void {+function flattenDFS(+ state: HierarchyState,+ entities: EntityData[],+ depth: number,+ rows: FlattenedRow[],+ entityMap: Map<number, EntityData> | null,+): void {for (const entity of entities) {- const children = entity.children- .map(id => state.store.getEntityData(id))- .filter((e): e is EntityData => e !== null);+ const children = entityMap+ ? entity.children.map(id => entityMap.get(id)).filter((e): e is EntityData => e != null)+ : entity.children.map(id => state.store.getEntityData(id)).filter((e): e is EntityData => e != null);const hasChildren = children.length > 0;const isExpanded = state.expandedIds.has(entity.id);rows.push({ entity, depth, hasChildren, isExpanded });if (hasChildren && isExpanded) {- flattenDFS(state, children, depth + 1, rows);+ flattenDFS(state, children, depth + 1, rows, entityMap);}}}export function expandAncestors(state: HierarchyState, entityId: Entity): void {- const entity = state.store.getEntityData(entityId as number);+ const getEntity = state.runtimeEntities+ ? (id: number) => state.runtimeEntities!.find(e => e.id === id) ?? null+ : (id: number) => state.store.getEntityData(id);++ const entity = getEntity(entityId as number);if (!entity || entity.parent === null) return;let parentId: number | null = entity.parent;while (parentId !== null) {state.expandedIds.add(parentId);- const parent = state.store.getEntityData(parentId);+ const parent = getEntity(parentId);parentId = parent?.parent ?? null;}}@@ -100,20 +112,14 @@ export function renderSingleRow(state: HierarchyState, row: FlattenedRow, selectconst expandIcon = isExpanded ? icons.chevronDown(10) : icons.chevronRight(10);const inPlayMode = state.playMode;- const isVisible = inPlayMode ? true : state.store.isEntityVisible(entity.id);+ const isVisible = inPlayMode || state.store.isEntityVisible(entity.id);const visibilityIcon = isVisible ? icons.eye(10) : icons.eyeOff(10);let itemClass = 'es-hierarchy-item';- if (inPlayMode) {- if (entity.id === getPlayModeService().selectedEntityId) itemClass += ' es-selected';- } else {- if (state.store.selectedEntities.has(entity.id)) itemClass += ' es-selected';- }+ if (state.store.selectedEntities.has(entity.id)) itemClass += ' es-selected';if (!isVisible) itemClass += ' es-entity-hidden';- if (!inPlayMode) {- if (entity.prefab?.isRoot) itemClass += ' es-prefab-root';- else if (entity.prefab) itemClass += ' es-prefab-child';- }+ if (entity.prefab?.isRoot) itemClass += ' es-prefab-root';+ else if (entity.prefab) itemClass += ' es-prefab-child';if (hasChildren) itemClass += ' es-has-children';if (isExpanded) itemClass += ' es-expanded';if (!inPlayMode && entity.id === state.draggingEntityId) itemClass += ' es-dragging';@@ -140,7 +146,7 @@ export function renderSingleRow(state: HierarchyState, row: FlattenedRow, selectreturn `<div class="${itemClass}" data-entity-id="${entity.id}" role="treeitem"${ariaExpanded}><div class="es-hierarchy-row" draggable="${draggable}" style="padding-left: ${8 + depth * 16}px">${hasChildren ? `<span class="es-hierarchy-expand">${expandIcon}</span>` : '<span class="es-hierarchy-spacer"></span>'}- ${inPlayMode ? '' : `<span class="es-hierarchy-visibility">${visibilityIcon}</span>`}+ <span class="es-hierarchy-visibility">${visibilityIcon}</span><span class="es-hierarchy-icon">${icon}</span><span class="es-hierarchy-name">${nameHtml}</span><span class="es-hierarchy-type">${type}</span>diff --git a/editor/src/panels/hierarchy/HierarchyTypes.ts b/editor/src/panels/hierarchy/HierarchyTypes.tsindex f0fb5cd43..8d8487598 100644--- a/editor/src/panels/hierarchy/HierarchyTypes.ts+++ b/editor/src/panels/hierarchy/HierarchyTypes.ts@@ -36,6 +36,7 @@ export interface HierarchyState {lastClickEntityId: number | null;lastClickTime: number;playMode: boolean;+ runtimeEntities?: EntityData[];render(): void;renderVisibleRows(): void;}diff --git a/editor/src/services/PlayModeService.ts b/editor/src/services/PlayModeService.tsindex 8637a23ed..17b82be45 100644--- a/editor/src/services/PlayModeService.ts+++ b/editor/src/services/PlayModeService.ts@@ -1,4 +1,6 @@import type { GameViewBridge, RuntimeEntityData } from '../panels/game-view/GameViewBridge';+import type { EntityData } from '../types/SceneTypes';+import { getEditorStore, type SceneSnapshot } from '../store/EditorStore';export type PlayState = 'stopped' | 'playing';@@ -6,6 +8,17 @@ type StateChangeCallback = (state: PlayState) => void;type EntityListCallback = (entities: RuntimeEntityData[]) => void;type SelectionCallback = (entityId: number | null) => void;+export function runtimeToEntityData(re: RuntimeEntityData): EntityData {+ return {+ id: re.entityId,+ name: re.name,+ parent: re.parentId,+ children: re.children,+ components: re.components.map(c => ({ type: c.type, data: c.data })),+ visible: true,+ };+}+class PlayModeService {private state_: PlayState = 'stopped';private bridge_: GameViewBridge | null = null;@@ -17,14 +30,30 @@ class PlayModeService {private stateListeners_ = new Set<StateChangeCallback>();private entityListListeners_ = new Set<EntityListCallback>();private selectionListeners_ = new Set<SelectionCallback>();+ private snapshot_: SceneSnapshot | null = null;get state(): PlayState { return this.state_; }get bridge(): GameViewBridge | null { return this.bridge_; }get runtimeEntities(): RuntimeEntityData[] { return this.cachedEntities_; }get selectedEntityId(): number | null { return this.selectedEntityId_; }+ getRuntimeEntityData(entityId: number): EntityData | null {+ const re = this.cachedEntities_.find(e => e.entityId === entityId);+ if (re) return runtimeToEntityData(re);+ return null;+ }+enter(bridge: GameViewBridge): void {- if (this.state_ === 'playing') this.exit();+ if (this.state_ === 'playing') {+ this.stopPolling();+ this.bridge_ = bridge;+ this.cachedEntities_ = [];+ this.selectedEntityId_ = null;+ this.startPolling();+ this.emitSelectionChange();+ return;+ }+ this.snapshot_ = getEditorStore().takeSnapshot();this.bridge_ = bridge;this.state_ = 'playing';this.cachedEntities_ = [];@@ -39,6 +68,10 @@ class PlayModeService {this.state_ = 'stopped';this.cachedEntities_ = [];this.selectedEntityId_ = null;+ if (this.snapshot_) {+ getEditorStore().restoreSnapshot(this.snapshot_);+ this.snapshot_ = null;+ }this.emitStateChange();this.emitSelectionChange();}@@ -63,6 +96,16 @@ class PlayModeService {return () => { this.selectionListeners_.delete(cb); };}+ async queryEntityByRuntimeId(runtimeId: number): Promise<RuntimeEntityData | null> {+ if (!this.bridge_?.isReady) return null;+ try {+ return await this.bridge_.queryEntity(runtimeId);+ } catch (e) {+ console.warn('[PlayModeService] queryEntityByRuntimeId failed:', e);+ return null;+ }+ }+async refreshEntityList(): Promise<void> {if (this.isRefreshing_ || !this.bridge_?.isReady) return;this.isRefreshing_ = true;@@ -90,6 +133,72 @@ class PlayModeService {}}+ async spawnEntity(name?: string, parentId?: number | null): Promise<number | null> {+ if (!this.bridge_?.isReady) return null;+ try {+ const result = await this.bridge_.spawnEntity(name, parentId);+ await this.refreshEntityList();+ return result.entityId;+ } catch (e) {+ console.warn('[PlayModeService] spawnEntity failed:', e);+ return null;+ }+ }++ async despawnEntity(entityId: number): Promise<void> {+ if (!this.bridge_?.isReady) return;+ try {+ await this.bridge_.despawnEntity(entityId);+ if (this.selectedEntityId_ === entityId) {+ this.selectedEntityId_ = null;+ this.emitSelectionChange();+ }+ await this.refreshEntityList();+ } catch (e) {+ console.warn('[PlayModeService] despawnEntity failed:', e);+ }+ }++ async addComponent(entityId: number, componentType: string, data?: Record<string, unknown>): Promise<void> {+ if (!this.bridge_?.isReady) return;+ try {+ await this.bridge_.addComponent(entityId, componentType, data);+ await this.refreshEntityList();+ } catch (e) {+ console.warn('[PlayModeService] addComponent failed:', e);+ }+ }++ async removeComponent(entityId: number, componentType: string): Promise<void> {+ if (!this.bridge_?.isReady) return;+ try {+ await this.bridge_.removeComponent(entityId, componentType);+ await this.refreshEntityList();+ } catch (e) {+ console.warn('[PlayModeService] removeComponent failed:', e);+ }+ }++ async renameEntity(entityId: number, name: string): Promise<void> {+ if (!this.bridge_?.isReady) return;+ try {+ await this.bridge_.renameEntity(entityId, name);+ await this.refreshEntityList();+ } catch (e) {+ console.warn('[PlayModeService] renameEntity failed:', e);+ }+ }++ async reparentEntity(entityId: number, newParentId: number | null): Promise<void> {+ if (!this.bridge_?.isReady) return;+ try {+ await this.bridge_.reparentEntity(entityId, newParentId);+ await this.refreshEntityList();+ } catch (e) {+ console.warn('[PlayModeService] reparentEntity failed:', e);+ }+ }+private startPolling(): void {this.stopPolling();this.consecutiveFailures_ = 0;@@ -99,7 +208,7 @@ class PlayModeService {private schedulePoll(): void {if (this.state_ !== 'playing') return;- const delay = this.consecutiveFailures_ > 2 ? 5000 : 1000;+ const delay = this.consecutiveFailures_ > 2 ? 5000 : 500;this.pollTimer_ = setTimeout(async () => {await this.refreshEntityList();this.schedulePoll();diff --git a/editor/src/styles/hierarchy.css b/editor/src/styles/hierarchy.cssindex f889cb546..063038db2 100644--- a/editor/src/styles/hierarchy.css+++ b/editor/src/styles/hierarchy.css@@ -297,30 +297,17 @@}/* Play mode indicator */-.es-hierarchy-panel.es-play-mode {- border-top: 2px solid var(--es-play-mode);-}-.es-hierarchy-panel.es-play-mode .es-hierarchy-toolbar::after {- content: 'RUNTIME';+ content: 'LIVE';font-size: 9px;font-weight: 600;- color: var(--es-play-mode);- padding: 1px 5px;- border-radius: 2px;- background: rgba(74, 158, 255, 0.12);+ color: #fff;+ padding: 1px 6px;+ border-radius: 8px;+ background: rgba(74, 158, 255, 0.5);margin-left: auto;}-.es-hierarchy-panel.es-play-mode .es-hierarchy-item.es-selected > .es-hierarchy-row {- background: rgba(74, 158, 255, 0.3);- border-left-color: var(--es-play-mode);-}--.es-hierarchy-panel.es-play-mode .es-hierarchy-item.es-selected > .es-hierarchy-row .es-hierarchy-name {- color: var(--es-play-mode);-}-.es-hierarchy-footer {padding: 6px 12px;font-size: 11px;diff --git a/editor/src/styles/inspector.css b/editor/src/styles/inspector.cssindex 3d9b46bda..e8d3d62e1 100644--- a/editor/src/styles/inspector.css+++ b/editor/src/styles/inspector.css@@ -1202,17 +1202,17 @@}/* Play mode indicator */-.es-inspector-panel.es-play-mode {- border-top: 2px solid var(--es-play-mode);-}-.es-inspector-panel.es-play-mode .es-inspector-toolbar::after {- content: 'RUNTIME';+ content: 'LIVE';font-size: 9px;font-weight: 600;- color: var(--es-play-mode);- padding: 1px 5px;- border-radius: 2px;- background: rgba(74, 158, 255, 0.12);+ color: #fff;+ padding: 1px 6px;+ border-radius: 8px;+ background: rgba(74, 158, 255, 0.5);margin-left: auto;}++.es-inspector-panel.es-play-mode .es-inspector-content {+ transition: opacity 0.15s;+}