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 multi-window support for detaching panels to separate OS windows
esengineec9c5dfa2a58
diff --git a/desktop/panel-window.html b/desktop/panel-window.htmlnew file mode 100644index 000000000..f6904e7c8--- /dev/null+++ b/desktop/panel-window.html@@ -0,0 +1,39 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <link rel="icon" type="image/svg+xml" href="/favicon.svg">+ <title>ESEngine Panel</title>+ <style>+ * {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+ -webkit-user-select: none;+ user-select: none;+ }+ input, textarea, [contenteditable], .es-output-content, .es-output-content * {+ -webkit-user-select: text;+ user-select: text;+ }+ html, body {+ width: 100%;+ height: 100%;+ overflow: hidden;+ background: #1e1e1e;+ }+ #panel-root {+ width: 100%;+ height: 100%;+ color: var(--es-text-primary, #cccccc);+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+ font-size: 13px;+ }+ </style>+</head>+<body>+ <div id="panel-root"></div>+ <script type="module" src="/src/panel-window.ts"></script>+</body>+</html>diff --git a/desktop/src-tauri/capabilities/default.json b/desktop/src-tauri/capabilities/default.jsonindex d99639e47..643b417bb 100644--- a/desktop/src-tauri/capabilities/default.json+++ b/desktop/src-tauri/capabilities/default.json@@ -2,9 +2,13 @@"$schema": "../gen/schemas/desktop-schema.json","identifier": "default","description": "Default capabilities for ESEngine Editor",- "windows": ["main"],+ "windows": ["main", "panel-*"],"permissions": ["core:default",+ "core:webview:allow-create-webview-window",+ "core:window:allow-create",+ "core:window:allow-destroy",+ "core:window:allow-set-focus","shell:allow-open","dialog:default","dialog:allow-open",diff --git a/desktop/src-tauri/gen/schemas/capabilities.json b/desktop/src-tauri/gen/schemas/capabilities.jsonindex 207595de3..138e73090 100644--- a/desktop/src-tauri/gen/schemas/capabilities.json+++ b/desktop/src-tauri/gen/schemas/capabilities.json@@ -1 +1 @@-{"default":{"identifier":"default","description":"Default capabilities for ESEngine Editor","local":true,"windows":["main"],"permissions":["core:default","shell:allow-open","dialog:default","dialog:allow-open","dialog:allow-save","fs:default",{"identifier":"fs:allow-read-text-file","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-write-text-file","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-write-file","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-read-file","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-stat","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-exists","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-mkdir","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-read-dir","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-copy-file","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-remove","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-rename","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-watch","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-unwatch"},"updater:default","process:allow-restart"]}}\ No newline at end of file+{"default":{"identifier":"default","description":"Default capabilities for ESEngine Editor","local":true,"windows":["main","panel-*"],"permissions":["core:default","core:webview:allow-create-webview-window","core:window:allow-create","core:window:allow-destroy","core:window:allow-set-focus","shell:allow-open","dialog:default","dialog:allow-open","dialog:allow-save","fs:default",{"identifier":"fs:allow-read-text-file","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-write-text-file","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-write-file","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-read-file","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-stat","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-exists","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-mkdir","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-read-dir","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-copy-file","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-remove","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-rename","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-watch","allow":[{"path":"**/*"}]},{"identifier":"fs:allow-unwatch"},"updater:default","process:allow-restart"]}}\ No newline at end of filediff --git a/desktop/src/panel-window.ts b/desktop/src/panel-window.tsnew file mode 100644index 000000000..361f55b1a--- /dev/null+++ b/desktop/src/panel-window.ts@@ -0,0 +1,90 @@+import 'dockview-core/dist/styles/dockview.css';+import '@esengine/editor/styles';+import {+ setPlatformAdapter,+ setEditorContext,+ getPanel,+ registerBuiltinEditors,+ registerBuiltinSchemas,+ registerBuiltinPanels,+ getAssetDatabase,+ type PanelInstance,+ isOutputAppendable,+ RemoteEditorStore,+ CHANNEL_OUTPUT,+ type OutputMessage,+} from '@esengine/editor';+import { TauriPlatformAdapter } from './TauriPlatformAdapter';+import { nativeFS, nativeShell } from './native-fs';+import { invoke } from '@tauri-apps/api/core';+import { getVersion } from '@tauri-apps/api/app';+import { listen } from '@tauri-apps/api/event';++async function init(): Promise<void> {+ const params = new URLSearchParams(window.location.search);+ const panelId = params.get('panel');+ if (!panelId) {+ console.error('No panel specified in URL');+ return;+ }++ const version = await getVersion();+ setPlatformAdapter(new TauriPlatformAdapter());+ setEditorContext({+ fs: nativeFS,+ invoke,+ shell: nativeShell,+ version,+ });++ registerBuiltinEditors();+ registerBuiltinSchemas();+ registerBuiltinPanels({});++ const projectPath = params.get('projectPath');+ if (projectPath) {+ const projectDir = projectPath.replace(/[/\\][^/\\]+$/, '');+ const db = getAssetDatabase();+ await db.initialize(projectDir, nativeFS);+ }++ const container = document.getElementById('panel-root');+ if (!container) {+ console.error('Panel root container not found');+ return;+ }++ const desc = getPanel(panelId);+ if (!desc) {+ container.textContent = `Unknown panel: ${panelId}`;+ return;+ }++ document.title = desc.title;++ const store = new RemoteEditorStore(panelId);+ await store.connect();++ let panelInstance: PanelInstance | null = null;+ try {+ panelInstance = desc.factory(container, store as any);+ } catch (err) {+ console.error(`Failed to create panel "${panelId}":`, err);+ container.textContent = `Failed to load panel: ${(err as Error).message}`;+ return;+ }++ if (panelId === 'output' && panelInstance && isOutputAppendable(panelInstance)) {+ const outputPanel = panelInstance;+ await listen<OutputMessage>(CHANNEL_OUTPUT, (event) => {+ outputPanel.appendOutput(event.payload.text, event.payload.type);+ });+ }++ window.addEventListener('beforeunload', () => {+ store.disconnect();+ panelInstance?.dispose();+ });+}++init().catch(console.error);diff --git a/desktop/vite.config.ts b/desktop/vite.config.tsindex 1287c236c..c21ceaacb 100644--- a/desktop/vite.config.ts+++ b/desktop/vite.config.ts@@ -1,3 +1,4 @@+import { resolve } from 'path';import { defineConfig, type Plugin } from 'vite';const host = process.env.TAURI_DEV_HOST;@@ -43,5 +44,11 @@ export default defineConfig({target: 'esnext',minify: !process.env.TAURI_DEBUG ? 'esbuild' : false,sourcemap: !!process.env.TAURI_DEBUG,+ rollupOptions: {+ input: {+ main: resolve(__dirname, 'index.html'),+ 'panel-window': resolve(__dirname, 'panel-window.html'),+ },+ },},});diff --git a/editor/package.json b/editor/package.jsonindex 13a95db86..c61ca5d30 100644--- a/editor/package.json+++ b/editor/package.json@@ -30,6 +30,7 @@"lucide": "^0.563.0"},"devDependencies": {+ "@tauri-apps/api": "^2.0.0","@rollup/plugin-alias": "^6.0.0","@rollup/plugin-node-resolve": "^16.0.3","@rollup/plugin-typescript": "^11.1.5",diff --git a/editor/rollup.config.js b/editor/rollup.config.jsindex f9cc9b8a2..04b190881 100644--- a/editor/rollup.config.js+++ b/editor/rollup.config.js@@ -15,7 +15,7 @@ export default [format: 'es',sourcemap: true,},- external: [/^esengine(\/|$)/],+ external: [/^esengine(\/|$)/, /^@tauri-apps\//],onwarn(warning, warn) {if (warning.code === 'THIS_IS_UNDEFINED') return;warn(warning);@@ -45,7 +45,7 @@ export default [file: 'dist/index.d.ts',format: 'es',},- external: [/^esengine(\/|$)/],+ external: [/^esengine(\/|$)/, /^@tauri-apps\//],plugins: [dts()],},];diff --git a/editor/src/DockLayoutManager.ts b/editor/src/DockLayoutManager.tsindex 331a1a15f..570488475 100644--- a/editor/src/DockLayoutManager.ts+++ b/editor/src/DockLayoutManager.ts@@ -10,8 +10,22 @@ import type { EditorStore } from './store/EditorStore';import { getPanel, type PanelDescriptor } from './panels/PanelRegistry';import type { PanelManager } from './PanelManager';import { showErrorToast } from './ui/Toast';+import { showContextMenu } from './ui/ContextMenu';const LAYOUT_STORAGE_KEY = 'esengine.editor.layout';+const NON_DETACHABLE_PANELS = new Set(['scene']);++export interface DetachPanelHandler {+ detachPanel(panelId: string, title: string): Promise<void>;+ detachGameView(previewUrl: string): Promise<void>;+ isDetached(panelId: string): boolean;+}++export interface DetachContext {+ handler: DetachPanelHandler;+ getPreviewUrl: () => Promise<string | null>;+ onPanelClosed: (callback: (panelId: string) => void) => (() => void);+}class EditorPanelRenderer implements IContentRenderer {private readonly element_: HTMLElement;@@ -52,12 +66,20 @@ export class DockLayoutManager {private activePanelDisposable_: { dispose(): void } | null = null;private saveTimer_: ReturnType<typeof setTimeout> | null = null;private lastActivePanelId_: string | null = null;+ private detachContext_: DetachContext | null = null;+ private contextMenuHandler_: ((e: MouseEvent) => void) | null = null;+ private panelClosedUnlisten_: (() => void) | null = null;constructor(panelManager: PanelManager, store: EditorStore) {this.panelManager_ = panelManager;this.store_ = store;}+ setDetachContext(context: DetachContext): void {+ this.detachContext_ = context;+ this.listenPanelClosed();+ }+get api(): DockviewApi | null {return this.api_;}@@ -75,6 +97,8 @@ export class DockLayoutManager {disableFloatingGroups: true,});+ this.setupTabContextMenu(container);+this.activePanelDisposable_ = this.api_.onDidActivePanelChange((panel) => {const newId = panel?.id ?? null;if (newId === this.lastActivePanelId_) return;@@ -238,11 +262,78 @@ export class DockLayoutManager {}}+ private setupTabContextMenu(container: HTMLElement): void {+ this.contextMenuHandler_ = (e: MouseEvent) => {+ if (!this.detachContext_) return;++ const target = e.target as HTMLElement;+ const tab = target.closest('.dv-tab') as HTMLElement | null;+ if (!tab) return;++ const panelId = this.resolvePanelIdFromTab(tab);+ if (!panelId || NON_DETACHABLE_PANELS.has(panelId)) return;++ e.preventDefault();+ e.stopPropagation();++ const isGame = panelId === 'game';+ const items = [{+ label: 'Open in New Window',+ onClick: () => this.handleDetachPanel(panelId, isGame),+ }];++ showContextMenu({ items, x: e.clientX, y: e.clientY });+ };++ container.addEventListener('contextmenu', this.contextMenuHandler_);+ }++ private resolvePanelIdFromTab(tab: HTMLElement): string | null {+ if (!this.api_) return null;+ const content = tab.querySelector('.dv-default-tab-content');+ const title = content?.textContent?.trim();+ if (!title) return null;++ for (const panel of this.api_.panels) {+ if (panel.title === title) return panel.id;+ }+ return null;+ }++ private async handleDetachPanel(panelId: string, isGame: boolean): Promise<void> {+ if (!this.detachContext_) return;++ try {+ if (isGame) {+ const url = await this.detachContext_.getPreviewUrl();+ if (!url) return;+ await this.detachContext_.handler.detachGameView(url);+ } else {+ const desc = getPanel(panelId);+ const title = desc?.title ?? panelId;+ await this.detachContext_.handler.detachPanel(panelId, title);+ }+ this.removePanel(panelId);+ this.panelManager_.removePanelInstance(panelId);+ } catch (err) {+ console.error(`Failed to detach panel "${panelId}":`, err);+ }+ }++ private listenPanelClosed(): void {+ if (!this.detachContext_) return;+ this.panelClosedUnlisten_ = this.detachContext_.onPanelClosed((panelId) => {+ this.showPanel(panelId);+ });+ }+dispose(): void {if (this.saveTimer_) {clearTimeout(this.saveTimer_);this.saveTimer_ = null;}+ this.panelClosedUnlisten_?.();+ this.panelClosedUnlisten_ = null;this.activePanelDisposable_?.dispose();this.activePanelDisposable_ = null;this.layoutChangeDisposable_?.dispose();diff --git a/editor/src/Editor.ts b/editor/src/Editor.tsindex 56cb49ce1..07a3a5f19 100644--- a/editor/src/Editor.ts+++ b/editor/src/Editor.ts@@ -75,6 +75,8 @@ import { ContentDrawer } from './ui/ContentDrawer';import {lockBuiltinPanels, clearExtensionPanels,} from './panels/PanelRegistry';+import { MainWindowBridge } from './multiwindow/MainWindowBridge';+import { WindowManager } from './multiwindow/WindowManager';export interface EditorOptions {projectPath?: string;@@ -105,6 +107,8 @@ export class Editor {private previewUrl_: string | null = null;private escapeHandler_: ((e: KeyboardEvent) => void) | null = null;private settingsDebounceTimer_: ReturnType<typeof setTimeout> | null = null;+ private mainWindowBridge_: MainWindowBridge | null = null;+ private windowManager_: WindowManager | null = null;constructor(container: HTMLElement, options?: EditorOptions) {this.container_ = container;@@ -154,6 +158,8 @@ export class Editor {this.menuManager_.setupMenuShortcuts();this.menuManager_.attach();+ this.initMultiWindow();+if (this.projectPath_) {this.setupEditorGlobals();this.assetLibraryReady_ = this.initializeAssetLibrary();@@ -484,6 +490,11 @@ export class Editor {}showAddressableWindow(): void {+ if (this.windowManager_) {+ this.windowManager_.detachPanel('addressable', 'Addressable Groups');+ return;+ }+if (this.addressableWindow_) {this.addressableWindow_.element.style.zIndex = '1001';return;@@ -676,7 +687,7 @@ export class Editor {const msg = errors.map(e => `${e.file}:${e.line} - ${e.message}`).join('\n');showErrorToast('Script compile failed', msg);for (const e of errors) {- this.panelManager_.appendOutput(`${e.file}:${e.line}:${e.column} - ${e.message}`, 'error');+ this.appendOutput(`${e.file}:${e.line}:${e.column} - ${e.message}`, 'error');}},onCompileSuccess: () => {@@ -887,13 +898,13 @@ export class Editor {private async executeShellCommand(fullCommand: string): Promise<void> {if (!this.projectPath_) {- this.panelManager_.appendOutput('Error: No project loaded\n', 'error');+ this.appendOutput('Error: No project loaded\n', 'error');return;}const shell = getEditorContext().shell;if (!shell) {- this.panelManager_.appendOutput('Error: Shell not available\n', 'error');+ this.appendOutput('Error: Shell not available\n', 'error');return;}@@ -905,20 +916,20 @@ export class Editor {const cmd = parts[0];const args = parts.slice(1);- this.panelManager_.appendOutput(`> ${fullCommand}\n`, 'command');+ this.appendOutput(`> ${fullCommand}\n`, 'command');try {const result = await shell.execute(cmd, args, projectDir, (stream: string, data: string) => {- this.panelManager_.appendOutput(data + '\n', stream === 'stderr' ? 'stderr' : 'stdout');+ this.appendOutput(data + '\n', stream === 'stderr' ? 'stderr' : 'stdout');});if (result.code !== 0) {- this.panelManager_.appendOutput(`Process exited with code ${result.code}\n`, 'error');+ this.appendOutput(`Process exited with code ${result.code}\n`, 'error');} else {- this.panelManager_.appendOutput(`Done.\n`, 'success');+ this.appendOutput(`Done.\n`, 'success');}} catch (err) {- this.panelManager_.appendOutput(`Error: ${err}\n`, 'error');+ this.appendOutput(`Error: ${err}\n`, 'error');}}@@ -965,7 +976,7 @@ export class Editor {if (stack) {text += '\n' + stack;}- this.panelManager_.appendOutput(text + '\n', type);+ this.appendOutput(text + '\n', type);};console.log = (...args) => { original.log(...args); forward('stdout', args); };@@ -1111,6 +1122,33 @@ export class Editor {document.addEventListener('keydown', this.escapeHandler_);}+ get windowManager(): WindowManager | null {+ return this.windowManager_;+ }++ appendOutput(text: string, type: 'command' | 'stdout' | 'stderr' | 'error' | 'success'): void {+ this.panelManager_.appendOutput(text, type);+ this.mainWindowBridge_?.broadcastOutput(text, type);+ }++ private initMultiWindow(): void {+ if (typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window) {+ this.mainWindowBridge_ = new MainWindowBridge(this.store_);+ this.mainWindowBridge_.start();+ this.windowManager_ = new WindowManager();+ this.windowManager_.setProjectPath(this.projectPath_);++ if (this.dockLayout_) {+ const bridge = this.mainWindowBridge_;+ this.dockLayout_.setDetachContext({+ handler: this.windowManager_,+ getPreviewUrl: () => this.startPreviewServer(),+ onPanelClosed: (cb) => bridge.onPanelClosed(cb),+ });+ }+ }+ }+dispose(): void {if (this.addressableWindow_) {this.addressableWindow_.panel.dispose();@@ -1122,6 +1160,8 @@ export class Editor {document.removeEventListener('keydown', this.escapeHandler_);this.escapeHandler_ = null;}+ this.windowManager_?.closeAll();+ this.mainWindowBridge_?.dispose();this.contentDrawer_?.dispose();this.menuManager_.dispose();this.scriptLoader_?.dispose();diff --git a/editor/src/index.ts b/editor/src/index.tsindex fcc3d2c20..217d5c587 100644--- a/editor/src/index.ts+++ b/editor/src/index.ts@@ -75,6 +75,7 @@ export {InspectorPanel,SceneViewPanel,OutputPanel,+ registerBuiltinPanels,} from './panels';// =============================================================================@@ -246,7 +247,7 @@ export { icons } from './utils/icons';// Asset// =============================================================================-export { AssetPathResolver, getGlobalPathResolver } from './asset';+export { AssetPathResolver, getGlobalPathResolver, getAssetDatabase } from './asset';// =============================================================================// Math@@ -422,3 +423,28 @@ export {clearDrawCallbacks,type DrawCallback,} from 'esengine';++// =============================================================================+// Multi-Window+// =============================================================================++export {+ RemoteEditorStore,+ MainWindowBridge,+ WindowManager,+ serializeEditorState,+ CHANNEL_STATE,+ CHANNEL_ACTION,+ CHANNEL_ACTION_RESULT,+ CHANNEL_PANEL_OPENED,+ CHANNEL_PANEL_CLOSED,+ CHANNEL_OUTPUT,+ type SerializedEditorState,+ type ActionType,+ type ActionMessage,+ type ActionResultMessage,+ type PanelOpenedMessage,+ type PanelClosedMessage,+ type OutputType,+ type OutputMessage,+} from './multiwindow';diff --git a/editor/src/multiwindow/MainWindowBridge.ts b/editor/src/multiwindow/MainWindowBridge.tsnew file mode 100644index 000000000..ab35598b1--- /dev/null+++ b/editor/src/multiwindow/MainWindowBridge.ts@@ -0,0 +1,212 @@+import type { Entity } from 'esengine';+import type { EditorStore } from '../store/EditorStore';+import { emit, listen, type UnlistenFn } from '@tauri-apps/api/event';+import { serializeEditorState } from './stateSerializer';+import {+ CHANNEL_STATE,+ CHANNEL_ACTION,+ CHANNEL_ACTION_RESULT,+ CHANNEL_PANEL_OPENED,+ CHANNEL_PANEL_CLOSED,+ CHANNEL_OUTPUT,+ type ActionMessage,+ type ActionResultMessage,+ type PanelOpenedMessage,+ type PanelClosedMessage,+ type OutputMessage,+ type OutputType,+} from './protocol';++export class MainWindowBridge {+ private store_: EditorStore;+ private unlisteners_: UnlistenFn[] = [];+ private unsubscribe_: (() => void) | null = null;+ private started_ = false;++ constructor(store: EditorStore) {+ this.store_ = store;+ }++ async start(): Promise<void> {+ if (this.started_) return;+ this.started_ = true;++ const unlistenAction = await listen<ActionMessage>(CHANNEL_ACTION, (event) => {+ this.handleAction(event.payload);+ });++ const unlistenPanelOpened = await listen<PanelOpenedMessage>(CHANNEL_PANEL_OPENED, () => {+ this.broadcastState();+ });++ this.unlisteners_.push(unlistenAction, unlistenPanelOpened);++ this.unsubscribe_ = this.store_.subscribe(() => {+ this.broadcastState();+ });+ }++ broadcastState(): void {+ const serialized = serializeEditorState(this.store_);+ emit(CHANNEL_STATE, serialized);+ }++ broadcastOutput(text: string, type: OutputType): void {+ const msg: OutputMessage = { text, type };+ emit(CHANNEL_OUTPUT, msg);+ }++ onPanelClosed(callback: (panelId: string) => void): () => void {+ let active = true;+ let unlisten: UnlistenFn | null = null;++ listen<PanelClosedMessage>(CHANNEL_PANEL_CLOSED, (event) => {+ if (active) {+ callback(event.payload.panelId);+ }+ }).then(fn => {+ if (active) {+ unlisten = fn;+ } else {+ fn();+ }+ });++ return () => {+ active = false;+ unlisten?.();+ };+ }++ dispose(): void {+ for (const unlisten of this.unlisteners_) {+ unlisten();+ }+ this.unlisteners_ = [];+ this.unsubscribe_?.();+ this.unsubscribe_ = null;+ this.started_ = false;+ }++ private handleAction(msg: ActionMessage): void {+ try {+ const result = this.executeAction(msg);+ const response: ActionResultMessage = { id: msg.id, result };+ emit(CHANNEL_ACTION_RESULT, response);+ } catch (err) {+ const response: ActionResultMessage = {+ id: msg.id,+ error: err instanceof Error ? err.message : String(err),+ };+ emit(CHANNEL_ACTION_RESULT, response);+ }+ }++ private executeAction(msg: ActionMessage): unknown {+ const store = this.store_;+ const args = msg.args;++ switch (msg.type) {+ case 'selectEntity':+ store.selectEntity(+ args[0] as Entity | null,+ (args[1] as 'replace' | 'add' | 'toggle') ?? 'replace',+ );+ return undefined;++ case 'selectEntities':+ store.selectEntities(args[0] as number[]);+ return undefined;++ case 'selectAsset':+ store.selectAsset(args[0] as Parameters<typeof store.selectAsset>[0]);+ return undefined;++ case 'createEntity': {+ const entity = store.createEntity(+ args[0] as string | undefined,+ (args[1] as Entity | null) ?? null,+ );+ return entity;+ }++ case 'deleteEntity':+ store.deleteEntity(args[0] as Entity);+ return undefined;++ case 'deleteSelectedEntities':+ store.deleteSelectedEntities();+ return undefined;++ case 'renameEntity':+ store.renameEntity(args[0] as Entity, args[1] as string);+ return undefined;++ case 'reparentEntity':+ store.reparentEntity(args[0] as Entity, args[1] as Entity | null);+ return undefined;++ case 'moveEntity':+ store.moveEntity(args[0] as Entity, args[1] as Entity | null, args[2] as number);+ return undefined;++ case 'addComponent':+ store.addComponent(+ args[0] as Entity,+ args[1] as string,+ args[2] as Record<string, unknown>,+ );+ return undefined;++ case 'removeComponent':+ store.removeComponent(args[0] as Entity, args[1] as string);+ return undefined;++ case 'reorderComponent':+ store.reorderComponent(args[0] as Entity, args[1] as number, args[2] as number);+ return undefined;++ case 'updateProperty':+ store.updateProperty(+ args[0] as Entity,+ args[1] as string,+ args[2] as string,+ args[3],+ args[4],+ );+ return undefined;++ case 'updateProperties':+ store.updateProperties(+ args[0] as Entity,+ args[1] as string,+ args[2] as { property: string; oldValue: unknown; newValue: unknown }[],+ );+ return undefined;++ case 'updatePropertyDirect':+ store.updatePropertyDirect(+ args[0] as Entity,+ args[1] as string,+ args[2] as string,+ args[3],+ );+ return undefined;++ case 'toggleVisibility':+ store.toggleVisibility(args[0] as number);+ return undefined;++ case 'undo':+ store.undo();+ return undefined;++ case 'redo':+ store.redo();+ return undefined;++ default:+ throw new Error(`Unknown action type: ${msg.type}`);+ }+ }+}diff --git a/editor/src/multiwindow/RemoteEditorStore.ts b/editor/src/multiwindow/RemoteEditorStore.tsnew file mode 100644index 000000000..f5e6188e1--- /dev/null+++ b/editor/src/multiwindow/RemoteEditorStore.ts@@ -0,0 +1,384 @@+import type { Entity } from 'esengine';+import type { SceneData, EntityData, ComponentData } from '../types/SceneTypes';+import type { EditorState, EditorListener, AssetSelection } from '../store/EditorStore';+import { emit, listen, type UnlistenFn } from '@tauri-apps/api/event';+import {+ CHANNEL_STATE,+ CHANNEL_ACTION,+ CHANNEL_ACTION_RESULT,+ CHANNEL_PANEL_OPENED,+ type SerializedEditorState,+ type ActionMessage,+ type ActionResultMessage,+ type ActionType,+} from './protocol';++const ACTION_TIMEOUT = 10_000;++let actionIdCounter = 0;++function nextActionId(): string {+ return `action-${++actionIdCounter}-${Date.now()}`;+}++export class RemoteEditorStore {+ private state_: EditorState;+ private entityMap_ = new Map<number, EntityData>();+ private sceneVersion_ = 0;+ private canUndo_ = false;+ private canRedo_ = false;+ private isEditingPrefab_ = false;+ private prefabEditingPath_: string | null = null;++ private listeners_ = new Set<EditorListener>();+ private pendingActions_ = new Map<string, { resolve: (v: unknown) => void; reject: (e: Error) => void }>();+ private unlisteners_: UnlistenFn[] = [];+ private panelId_: string;++ constructor(panelId: string) {+ this.panelId_ = panelId;+ this.state_ = {+ scene: { version: '1', name: 'Untitled', entities: [] },+ selectedEntities: new Set(),+ selectedAsset: null,+ isDirty: false,+ filePath: null,+ };+ }++ // =========================================================================+ // Connection+ // =========================================================================++ async connect(): Promise<void> {+ const unlistenState = await listen<SerializedEditorState>(CHANNEL_STATE, (event) => {+ this.applySnapshot(event.payload);+ });++ const unlistenResult = await listen<ActionResultMessage>(CHANNEL_ACTION_RESULT, (event) => {+ const pending = this.pendingActions_.get(event.payload.id);+ if (pending) {+ this.pendingActions_.delete(event.payload.id);+ if (event.payload.error) {+ pending.reject(new Error(event.payload.error));+ } else {+ pending.resolve(event.payload.result);+ }+ }+ });++ this.unlisteners_.push(unlistenState, unlistenResult);++ await emit(CHANNEL_PANEL_OPENED, {+ panelId: this.panelId_,+ windowLabel: '',+ });+ }++ disconnect(): void {+ for (const unlisten of this.unlisteners_) {+ unlisten();+ }+ this.unlisteners_ = [];+ this.pendingActions_.clear();+ }++ // =========================================================================+ // State Access (read-only, from snapshot)+ // =========================================================================++ get state(): Readonly<EditorState> {+ return this.state_;+ }++ get scene(): SceneData {+ return this.state_.scene;+ }++ get sceneVersion(): number {+ return this.sceneVersion_;+ }++ get selectedEntities(): ReadonlySet<number> {+ return this.state_.selectedEntities;+ }++ get selectedEntity(): Entity | null {+ if (this.state_.selectedEntities.size !== 1) return null;+ return this.state_.selectedEntities.values().next().value as Entity;+ }++ get selectedAsset(): AssetSelection | null {+ return this.state_.selectedAsset;+ }++ get isDirty(): boolean {+ return this.state_.isDirty;+ }++ get filePath(): string | null {+ return this.state_.filePath;+ }++ get canUndo(): boolean {+ return this.canUndo_;+ }++ get canRedo(): boolean {+ return this.canRedo_;+ }++ get isEditingPrefab(): boolean {+ return this.isEditingPrefab_;+ }++ get prefabEditingPath(): string | null {+ return this.prefabEditingPath_;+ }++ getEntityData(entityId: number): EntityData | null {+ return this.entityMap_.get(entityId) ?? null;+ }++ getSelectedEntityData(): EntityData | null {+ const entity = this.selectedEntity;+ if (entity === null) return null;+ return this.entityMap_.get(entity) ?? null;+ }++ getSelectedEntitiesData(): EntityData[] {+ const result: EntityData[] = [];+ for (const id of this.state_.selectedEntities) {+ const data = this.entityMap_.get(id);+ if (data) result.push(data);+ }+ return result;+ }++ getComponent(entity: Entity, type: string): ComponentData | null {+ const data = this.entityMap_.get(entity);+ if (!data) return null;+ return data.components.find(c => c.type === type) ?? null;+ }++ isEntityVisible(entityId: number): boolean {+ const data = this.entityMap_.get(entityId);+ return data?.visible !== false;+ }++ isEntityDirectlyHidden(entityId: number): boolean {+ const data = this.entityMap_.get(entityId);+ if (!data || data.visible !== false) return false;+ const parentId = data.parent;+ if (parentId === null) return true;+ const parentData = this.entityMap_.get(parentId);+ return parentData?.visible !== false;+ }++ isPrefabInstance(entityId: number): boolean {+ const data = this.entityMap_.get(entityId);+ return !!data?.prefab;+ }++ isPrefabRoot(entityId: number): boolean {+ const data = this.entityMap_.get(entityId);+ if (!data?.prefab) return false;+ const parentData = data.parent !== null ? this.entityMap_.get(data.parent) : null;+ return !parentData?.prefab || parentData.prefab.instanceId !== data.prefab.instanceId;+ }++ getPrefabInstanceId(entityId: number): string | undefined {+ return this.entityMap_.get(entityId)?.prefab?.instanceId;+ }++ getPrefabPath(entityId: number): string | undefined {+ return this.entityMap_.get(entityId)?.prefab?.prefabPath;+ }++ // =========================================================================+ // Subscription+ // =========================================================================++ subscribe(listener: EditorListener): () => void {+ this.listeners_.add(listener);+ return () => this.listeners_.delete(listener);+ }++ subscribeToPropertyChanges(): () => void {+ return () => {};+ }++ subscribeToHierarchyChanges(): () => void {+ return () => {};+ }++ subscribeToEntityLifecycle(): () => void {+ return () => {};+ }++ subscribeToComponentChanges(): () => void {+ return () => {};+ }++ subscribeToVisibilityChanges(): () => void {+ return () => {};+ }++ subscribeToSceneSync(): () => void {+ return () => {};+ }++ onFocusEntity(): () => void {+ return () => {};+ }++ // =========================================================================+ // Mutation Methods (forwarded to main window)+ // =========================================================================++ selectEntity(entity: Entity | null, mode: 'replace' | 'add' | 'toggle' = 'replace'): void {+ this.fireAction('selectEntity', [entity, mode]);+ }++ selectEntities(entities: number[]): void {+ this.fireAction('selectEntities', [entities]);+ }++ selectAsset(asset: AssetSelection | null): void {+ this.fireAction('selectAsset', [asset]);+ }++ createEntity(name?: string, parent?: Entity | null): Entity {+ this.fireAction('createEntity', [name, parent ?? null]);+ return 0 as Entity;+ }++ async createEntityAsync(name?: string, parent?: Entity | null): Promise<Entity> {+ const result = await this.fireActionAsync('createEntity', [name, parent ?? null]);+ return result as Entity;+ }++ deleteEntity(entity: Entity): void {+ this.fireAction('deleteEntity', [entity]);+ }++ deleteSelectedEntities(): void {+ this.fireAction('deleteSelectedEntities', []);+ }++ renameEntity(entity: Entity, name: string): void {+ this.fireAction('renameEntity', [entity, name]);+ }++ reparentEntity(entity: Entity, newParent: Entity | null): void {+ this.fireAction('reparentEntity', [entity, newParent]);+ }++ moveEntity(entity: Entity, newParent: Entity | null, index: number): void {+ this.fireAction('moveEntity', [entity, newParent, index]);+ }++ addComponent(entity: Entity, type: string, data: Record<string, unknown>): void {+ this.fireAction('addComponent', [entity, type, data]);+ }++ removeComponent(entity: Entity, type: string): void {+ this.fireAction('removeComponent', [entity, type]);+ }++ reorderComponent(entity: Entity, fromIndex: number, toIndex: number): void {+ this.fireAction('reorderComponent', [entity, fromIndex, toIndex]);+ }++ updateProperty(+ entity: Entity,+ componentType: string,+ propertyName: string,+ oldValue: unknown,+ newValue: unknown,+ ): void {+ this.fireAction('updateProperty', [entity, componentType, propertyName, oldValue, newValue]);+ }++ updateProperties(+ entity: Entity,+ componentType: string,+ changes: { property: string; oldValue: unknown; newValue: unknown }[],+ ): void {+ this.fireAction('updateProperties', [entity, componentType, changes]);+ }++ updatePropertyDirect(+ entity: Entity,+ componentType: string,+ propertyName: string,+ newValue: unknown,+ ): void {+ this.fireAction('updatePropertyDirect', [entity, componentType, propertyName, newValue]);+ }++ toggleVisibility(entityId: number): void {+ this.fireAction('toggleVisibility', [entityId]);+ }++ undo(): void {+ this.fireAction('undo', []);+ }++ redo(): void {+ this.fireAction('redo', []);+ }++ // No-op stubs for methods only relevant to main window+ notifyChange(): void {}+ focusEntity(): void {}+ selectRange(): void {}++ // =========================================================================+ // Internal+ // =========================================================================++ private applySnapshot(snapshot: SerializedEditorState): void {+ this.state_ = {+ scene: snapshot.scene,+ selectedEntities: new Set(snapshot.selectedEntities),+ selectedAsset: snapshot.selectedAsset,+ isDirty: snapshot.isDirty,+ filePath: snapshot.filePath,+ };+ this.canUndo_ = snapshot.canUndo;+ this.canRedo_ = snapshot.canRedo;+ this.isEditingPrefab_ = snapshot.isEditingPrefab;+ this.prefabEditingPath_ = snapshot.prefabEditingPath;+ this.sceneVersion_ = snapshot.sceneVersion;++ this.entityMap_.clear();+ for (const entity of snapshot.scene.entities) {+ this.entityMap_.set(entity.id, entity);+ }++ for (const listener of this.listeners_) {+ listener(this.state_);+ }+ }++ private fireAction(type: ActionType, args: unknown[]): void {+ const msg: ActionMessage = { id: nextActionId(), type, args };+ emit(CHANNEL_ACTION, msg);+ }++ private fireActionAsync(type: ActionType, args: unknown[]): Promise<unknown> {+ return new Promise((resolve, reject) => {+ const msg: ActionMessage = { id: nextActionId(), type, args };+ this.pendingActions_.set(msg.id, { resolve, reject });+ emit(CHANNEL_ACTION, msg);++ setTimeout(() => {+ if (this.pendingActions_.has(msg.id)) {+ this.pendingActions_.delete(msg.id);+ reject(new Error(`Action ${type} timed out`));+ }+ }, ACTION_TIMEOUT);+ });+ }+}diff --git a/editor/src/multiwindow/WindowManager.ts b/editor/src/multiwindow/WindowManager.tsnew file mode 100644index 000000000..3a8e50e4b--- /dev/null+++ b/editor/src/multiwindow/WindowManager.ts@@ -0,0 +1,127 @@+import { WebviewWindow } from '@tauri-apps/api/webviewWindow';+import { emit } from '@tauri-apps/api/event';+import { CHANNEL_PANEL_CLOSED, type PanelClosedMessage } from './protocol';++interface DetachedPanel {+ windowLabel: string;+ panelId: string;+ window: WebviewWindow;+}++export class WindowManager {+ private detachedPanels_ = new Map<string, DetachedPanel>();+ private projectPath_: string | null = null;++ setProjectPath(projectPath: string | null): void {+ this.projectPath_ = projectPath;+ }++ async detachPanel(panelId: string, title: string): Promise<void> {+ const existing = this.detachedPanels_.get(panelId);+ if (existing) {+ await existing.window.setFocus();+ return;+ }++ let url = `panel-window.html?panel=${encodeURIComponent(panelId)}`;+ if (this.projectPath_) {+ url += `&projectPath=${encodeURIComponent(this.projectPath_)}`;+ }++ const windowLabel = `panel-${panelId}-${Date.now()}`;+ const webviewWindow = new WebviewWindow(windowLabel, {+ url,+ title,+ width: 400,+ height: 600,+ minWidth: 300,+ minHeight: 200,+ center: true,+ decorations: true,+ resizable: true,+ });++ await this.waitForWindowCreation(webviewWindow);++ const entry: DetachedPanel = {+ windowLabel,+ panelId,+ window: webviewWindow,+ };++ this.detachedPanels_.set(panelId, entry);++ webviewWindow.once('tauri://close-requested', async () => {+ this.detachedPanels_.delete(panelId);+ const msg: PanelClosedMessage = { panelId, windowLabel };+ await emit(CHANNEL_PANEL_CLOSED, msg);+ await webviewWindow.destroy();+ });+ }++ async detachGameView(previewUrl: string): Promise<void> {+ const panelId = 'game';+ const existing = this.detachedPanels_.get(panelId);+ if (existing) {+ await existing.window.setFocus();+ return;+ }++ const windowLabel = `panel-game-${Date.now()}`;+ const webviewWindow = new WebviewWindow(windowLabel, {+ url: previewUrl,+ title: 'Game Preview',+ width: 800,+ height: 600,+ minWidth: 400,+ minHeight: 300,+ center: true,+ decorations: true,+ resizable: true,+ });++ await this.waitForWindowCreation(webviewWindow);++ const entry: DetachedPanel = {+ windowLabel,+ panelId,+ window: webviewWindow,+ };++ this.detachedPanels_.set(panelId, entry);++ webviewWindow.once('tauri://close-requested', async () => {+ this.detachedPanels_.delete(panelId);+ const msg: PanelClosedMessage = { panelId, windowLabel };+ await emit(CHANNEL_PANEL_CLOSED, msg);+ await webviewWindow.destroy();+ });+ }++ isDetached(panelId: string): boolean {+ return this.detachedPanels_.has(panelId);+ }++ async closeAll(): Promise<void> {+ const entries = Array.from(this.detachedPanels_.values());+ this.detachedPanels_.clear();+ for (const entry of entries) {+ try {+ await entry.window.destroy();+ } catch {+ // window may already be closed+ }+ }+ }++ private waitForWindowCreation(webviewWindow: WebviewWindow): Promise<void> {+ return new Promise((resolve, reject) => {+ webviewWindow.once('tauri://created', () => {+ resolve();+ });+ webviewWindow.once('tauri://error', (e) => {+ reject(new Error(`Failed to create window: ${e.payload}`));+ });+ });+ }+}diff --git a/editor/src/multiwindow/index.ts b/editor/src/multiwindow/index.tsnew file mode 100644index 000000000..7f213652c--- /dev/null+++ b/editor/src/multiwindow/index.ts@@ -0,0 +1,22 @@+export { RemoteEditorStore } from './RemoteEditorStore';+export { MainWindowBridge } from './MainWindowBridge';+export { WindowManager } from './WindowManager';++export {+ CHANNEL_STATE,+ CHANNEL_ACTION,+ CHANNEL_ACTION_RESULT,+ CHANNEL_PANEL_OPENED,+ CHANNEL_PANEL_CLOSED,+ CHANNEL_OUTPUT,+ type SerializedEditorState,+ type ActionType,+ type ActionMessage,+ type ActionResultMessage,+ type PanelOpenedMessage,+ type PanelClosedMessage,+ type OutputType,+ type OutputMessage,+} from './protocol';++export { serializeEditorState } from './stateSerializer';diff --git a/editor/src/multiwindow/protocol.ts b/editor/src/multiwindow/protocol.tsnew file mode 100644index 000000000..692550d2b--- /dev/null+++ b/editor/src/multiwindow/protocol.ts@@ -0,0 +1,91 @@+import type { SceneData } from '../types/SceneTypes';+import type { AssetSelection } from '../store/EditorStore';++// =============================================================================+// Tauri Event Channels+// =============================================================================++export const CHANNEL_STATE = 'editor:state';+export const CHANNEL_ACTION = 'editor:action';+export const CHANNEL_ACTION_RESULT = 'editor:action-result';+export const CHANNEL_PANEL_OPENED = 'editor:panel-opened';+export const CHANNEL_PANEL_CLOSED = 'editor:panel-closed';+export const CHANNEL_OUTPUT = 'editor:output';++// =============================================================================+// State Snapshot+// =============================================================================++export interface SerializedEditorState {+ scene: SceneData;+ selectedEntities: number[];+ selectedAsset: AssetSelection | null;+ isDirty: boolean;+ filePath: string | null;+ canUndo: boolean;+ canRedo: boolean;+ isEditingPrefab: boolean;+ prefabEditingPath: string | null;+ sceneVersion: number;+}++// =============================================================================+// Action Messages+// =============================================================================++export type ActionType =+ | 'selectEntity'+ | 'selectEntities'+ | 'selectAsset'+ | 'createEntity'+ | 'deleteEntity'+ | 'deleteSelectedEntities'+ | 'renameEntity'+ | 'reparentEntity'+ | 'moveEntity'+ | 'addComponent'+ | 'removeComponent'+ | 'reorderComponent'+ | 'updateProperty'+ | 'updateProperties'+ | 'updatePropertyDirect'+ | 'toggleVisibility'+ | 'undo'+ | 'redo';++export interface ActionMessage {+ id: string;+ type: ActionType;+ args: unknown[];+}++export interface ActionResultMessage {+ id: string;+ result?: unknown;+ error?: string;+}++// =============================================================================+// Panel Messages+// =============================================================================++export interface PanelOpenedMessage {+ panelId: string;+ windowLabel: string;+}++export interface PanelClosedMessage {+ panelId: string;+ windowLabel: string;+}++// =============================================================================+// Output Messages+// =============================================================================++export type OutputType = 'command' | 'stdout' | 'stderr' | 'error' | 'success';++export interface OutputMessage {+ text: string;+ type: OutputType;+}diff --git a/editor/src/multiwindow/stateSerializer.ts b/editor/src/multiwindow/stateSerializer.tsnew file mode 100644index 000000000..9c931860a--- /dev/null+++ b/editor/src/multiwindow/stateSerializer.ts@@ -0,0 +1,17 @@+import type { EditorStore } from '../store/EditorStore';+import type { SerializedEditorState } from './protocol';++export function serializeEditorState(store: EditorStore): SerializedEditorState {+ return {+ scene: store.scene,+ selectedEntities: Array.from(store.selectedEntities),+ selectedAsset: store.selectedAsset,+ isDirty: store.isDirty,+ filePath: store.filePath,+ canUndo: store.canUndo,+ canRedo: store.canRedo,+ isEditingPrefab: store.isEditingPrefab,+ prefabEditingPath: store.prefabEditingPath,+ sceneVersion: store.sceneVersion,+ };+}diff --git a/editor/src/panels/builtinPanels.ts b/editor/src/panels/builtinPanels.tsindex ef81983da..330ad2449 100644--- a/editor/src/panels/builtinPanels.ts+++ b/editor/src/panels/builtinPanels.ts@@ -5,6 +5,7 @@ import { SceneViewPanel } from './scene-view/SceneViewPanel';import { GameViewPanel } from './game-view/GameViewPanel';import { ContentBrowserPanel } from './content-browser/ContentBrowserPanel';import { OutputPanel } from './OutputPanel';+import { AddressablePanel } from './AddressablePanel';import { icons } from '../utils/icons';export interface BuiltinPanelOptions {@@ -75,4 +76,14 @@ export function registerBuiltinPanels(options: BuiltinPanelOptions): void {factory: (c) => new OutputPanel(c),});+ registerPanel({+ id: 'addressable',+ title: 'Addressable Groups',+ icon: icons.list(14),+ position: 'bottom',+ order: 2,+ defaultVisible: false,+ factory: (c, s) => new AddressablePanel(c, s),+ });+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a1018df1b..e5854b007 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -85,6 +85,9 @@ importers:'@rollup/plugin-typescript':specifier: ^11.1.5+ '@tauri-apps/api':+ specifier: ^2.0.0+ version: 2.10.1'@vitest/ui':specifier: ^2.1.8version: 2.1.9([email protected])@@ -2125,7 +2128,7 @@ snapshots:sirv: 3.0.2tinyglobby: 0.2.15tinyrainbow: 1.2.0- vitest: 2.1.9(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])+ vitest: 2.1.9(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])'@vitest/[email protected]':dependencies: