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(editor): Play runs in an isolated realm — Game panel (R2)
esengine1276e5281331
diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex ec34b9f81..5d183fd10 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -299,7 +299,13 @@ async function handleEstella(request: Request): Promise<Response> {const bytes = await readFile(abs);const ext = path.extname(abs).slice(1).toLowerCase();return new Response(new Uint8Array(bytes), {- headers: { 'content-type': ASSET_MIME[ext] ?? 'application/octet-stream' },+ headers: {+ 'content-type': ASSET_MIME[ext] ?? 'application/octet-stream',+ // The play realm (app:// origin) loads project assets cross-scheme via+ // <img crossorigin> + fetch; allow it. estella:// is only reachable inside+ // the Electron app, so there is no untrusted-web exposure.+ 'access-control-allow-origin': '*',+ },});} catch (err) {return new Response(String(err), { status: 404 });@@ -309,9 +315,24 @@ async function handleEstella(request: Request): Promise<Response> {// app://local/<path> → the built renderer (dist/). Serves index.html, the wasm// glue + binary, the play realm host page, and bundled assets over a stable// origin. Path-escape guarded to dist/.+const PROJECT_PREFIX = '__project__/';+async function handleApp(request: Request): Promise<Response> {try {const rel = decodeURIComponent(new URL(request.url).pathname).replace(/^\/+/, '') || 'index.html';+ // app://local/__project__/<path> → project asset (so the play realm, which is+ // SAME-ORIGIN with the editor under app://, can read project files — custom+ // schemes can't cross-fetch each other, so estella:// is unreachable from the+ // app:// realm). Sandboxed to the open project root.+ if (rel.startsWith(PROJECT_PREFIX)) {+ if (!projectRoot) return new Response('no project open', { status: 503 });+ const abs = resolveInRoot(projectRoot, rel.slice(PROJECT_PREFIX.length));+ const bytes = await readFile(abs);+ const ext = path.extname(abs).slice(1).toLowerCase();+ return new Response(new Uint8Array(bytes), {+ headers: { 'content-type': ASSET_MIME[ext] ?? 'application/octet-stream', 'access-control-allow-origin': '*' },+ });+ }const abs = path.join(RENDERER_DIST, rel);if (abs !== RENDERER_DIST && !abs.startsWith(RENDERER_DIST + path.sep)) {return new Response('forbidden', { status: 403 });@@ -319,7 +340,7 @@ async function handleApp(request: Request): Promise<Response> {const bytes = await readFile(abs);const ext = path.extname(abs).slice(1).toLowerCase();return new Response(new Uint8Array(bytes), {- headers: { 'content-type': APP_MIME[ext] ?? 'application/octet-stream' },+ headers: { 'content-type': APP_MIME[ext] ?? 'application/octet-stream', 'access-control-allow-origin': '*' },});} catch (err) {return new Response(String(err), { status: 404 });diff --git a/desktop/index.html b/desktop/index.htmlindex 0ca8e2c6e..ba97c9ebe 100644--- a/desktop/index.html+++ b/desktop/index.html@@ -4,7 +4,7 @@<meta charset="UTF-8" /><metahttp-equiv="Content-Security-Policy"- content="default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: estella:; font-src 'self' data:; connect-src 'self' ws: estella:; worker-src 'self' blob:;"+ content="default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: estella:; font-src 'self' data:; connect-src 'self' ws: estella:; worker-src 'self' blob:; frame-src 'self';"/><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Estella Editor</title>diff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex a90a1cb30..5c54e5762 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -5,11 +5,15 @@ import { StatusBar } from '@/layout/StatusBar';import { DockLayout } from '@/layout/DockLayout';import { ActivityBar } from '@/layout/ActivityBar';import { ContentDrawer } from '@/layout/ContentDrawer';-import { defaultSession } from '@/engine/EditorSession';+import '@/engine/EditorSession'; // side effect: constructs defaultSession → wires the editor engineimport { Launcher } from '@/launcher/Launcher';import { Toaster } from '@/components/Toaster';import { useEditorStore } from '@/store/editorStore';import { commands } from '@/commands';+import { PlayRealm } from '@/engine/PlayRealm';+import { ProjectStore } from '@/project/ProjectStore';+import { dockApi } from '@/layout/dockApi';+import { Toasts } from '@/store/Toasts';// The editor shell: fixed menu + toolbar on top, dockable workspace in the// middle, status strip at the bottom.@@ -39,15 +43,31 @@ export function App() {return () => window.removeEventListener('keydown', onKey);}, []);- // Drive engine edit/play mode from the toolbar's play/pause state. Edit mode- // (the default) freezes gameplay systems so they don't fight scene edits; Stop- // rebuilds the World from the untouched edit model (model-authoritative). The- // selection holds stable source ids, so it survives the rebuild — no clear.+ // Play runs in an ISOLATED realm (the Game panel's iframe = the shipping+ // runtime), NOT by flipping the main edit World — so gameplay can never dirty+ // the scene and the Viewport stays a live Scene view (REARCH_EDITOR_REALM R2).+ // (The headless/automation path still drives the main World via+ // EditorControlSurface.setRunMode + step for deterministic capture.)const isPlaying = useEditorStore((s) => s.isPlaying);const isPaused = useEditorStore((s) => s.isPaused);useEffect(() => {- defaultSession.surface.setRunMode(isPlaying, isPaused);- }, [isPlaying, isPaused]);+ if (isPlaying) {+ const payload = ProjectStore.playPayload();+ if (!payload) {+ Toasts.push('Open a scene before playing', 'error');+ useEditorStore.getState().stop();+ return;+ }+ dockApi.openGame();+ PlayRealm.start(payload);+ } else {+ PlayRealm.stop();+ dockApi.closeGame();+ }+ }, [isPlaying]);+ useEffect(() => {+ if (isPlaying) PlayRealm.setPaused(isPaused);+ }, [isPaused, isPlaying]);// The editor opens on the launcher (project browser); the shell + engine mount// only once a project is opened. (Logic wiring lands with the recents IPC.)diff --git a/desktop/src/engine/PlayRealm.ts b/desktop/src/engine/PlayRealm.tsnew file mode 100644index 000000000..d238004b5--- /dev/null+++ b/desktop/src/engine/PlayRealm.ts@@ -0,0 +1,98 @@+/**+ * @file PlayRealm.ts — controller for the isolated play realm (REARCH_EDITOR_REALM+ * Phase R2). Owns a detached <iframe> (play.html) re-parented into the Game+ * panel (mirrors EngineHost's detached-canvas pattern), and the typed+ * postMessage protocol with it:+ * out → init {sceneData, assetManifest} · setPaused {paused}+ * in ← hello (mounted) · ready (running) · error {message}+ * Each Play loads a FRESH realm (own wasm + GL + World); Stop points the+ * iframe at about:blank, tearing the realm down. The edit World is never+ * touched, so there is nothing to restore.+ */+import { createStore } from 'zustand/vanilla';+import type { SceneData } from 'esengine';++export interface PlayPayload {+ sceneData: SceneData;+ assetManifest: Record<string, string>;+}++export interface PlayRealmSnapshot {+ playing: boolean;+ ready: boolean;+ error: string | null;+}++class PlayRealmImpl {+ private iframe: HTMLIFrameElement | null = null;+ private payload: PlayPayload | null = null;+ private epoch = 0;+ private readonly store = createStore<PlayRealmSnapshot>(() => ({ playing: false, ready: false, error: null }));++ subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);+ getSnapshot = (): PlayRealmSnapshot => this.store.getState();+ private set(patch: Partial<PlayRealmSnapshot>): void {+ this.store.setState({ ...this.store.getState(), ...patch });+ }++ private ensureIframe(): HTMLIFrameElement {+ if (!this.iframe) {+ const f = document.createElement('iframe');+ f.title = 'Game';+ f.style.cssText = 'display:block;width:100%;height:100%;border:0;background:#0e121b';+ window.addEventListener('message', this.onMessage);+ this.iframe = f;+ }+ return this.iframe;+ }++ /** Re-parent the realm iframe into the Game panel (kept alive across remounts). */+ attach(container: HTMLElement): void {+ container.appendChild(this.ensureIframe());+ }+ detach(): void {+ this.iframe?.parentElement?.removeChild(this.iframe);+ }++ /** Boot a fresh realm and play `payload` (init is posted on the realm's hello). */+ start(payload: PlayPayload): void {+ this.payload = payload;+ this.set({ playing: true, ready: false, error: null });+ this.ensureIframe().src = `/play.html?n=${++this.epoch}`;+ }++ /** Tear the realm down (releases its wasm + GL by navigating to a blank page). */+ stop(): void {+ this.payload = null;+ if (this.iframe) this.iframe.src = 'about:blank';+ this.set({ playing: false, ready: false, error: null });+ }++ setPaused(paused: boolean): void {+ this.post({ type: 'estella:play:setPaused', paused });+ }++ private post(message: Record<string, unknown>): void {+ this.iframe?.contentWindow?.postMessage(message, '*');+ }++ private onMessage = (e: MessageEvent): void => {+ if (!this.iframe || e.source !== this.iframe.contentWindow) return;+ const data = e.data as { type?: string; message?: string } | null;+ if (!data?.type) return;+ switch (data.type) {+ case 'estella:play:hello':+ // Realm mounted + listening — hand it the scene snapshot.+ if (this.payload) this.post({ type: 'estella:play:init', ...this.payload });+ break;+ case 'estella:play:ready':+ this.set({ ready: true });+ break;+ case 'estella:play:error':+ this.set({ error: data.message ?? 'play realm error' });+ break;+ }+ };+}++export const PlayRealm = new PlayRealmImpl();diff --git a/desktop/src/layout/DockLayout.tsx b/desktop/src/layout/DockLayout.tsxindex 00af19e0d..3c492127d 100644--- a/desktop/src/layout/DockLayout.tsx+++ b/desktop/src/layout/DockLayout.tsx@@ -5,6 +5,7 @@ import { Viewport } from '@/panels/Viewport';import { Details } from '@/panels/Details';import { ContentBrowser } from '@/panels/ContentBrowser';import { OutputLog } from '@/panels/OutputLog';+import { GamePanel } from '@/panels/GamePanel';import { dockApi } from '@/layout/dockApi';// Each dock panel is a thin wrapper so dockview owns mount/unmount.@@ -14,6 +15,8 @@ const components: Record<string, FC<IDockviewPanelProps>> = {details: () => <Details />,content: () => <ContentBrowser />,log: () => <OutputLog />,+ // The "Game" view (isolated play realm) — added on Play, removed on Stop.+ game: () => <GamePanel />,};// Bumped to v5 (tabbed docking): Viewport center, right column Outliner-over-diff --git a/desktop/src/layout/dockApi.ts b/desktop/src/layout/dockApi.tsindex 63d652d59..4fa8a7571 100644--- a/desktop/src/layout/dockApi.ts+++ b/desktop/src/layout/dockApi.ts@@ -18,6 +18,23 @@ export const dockApi = {reveal(id: string) {api?.getPanel(id)?.api.setActive();},+ /** Open (or reveal) the Game view as a tab beside the Viewport — used on Play. */+ openGame() {+ if (!api) return;+ if (!api.getPanel('game')) {+ api.addPanel({+ id: 'game',+ component: 'game',+ title: 'Game',+ position: api.getPanel('viewport') ? { referencePanel: 'viewport', direction: 'within' } : undefined,+ });+ }+ api.getPanel('game')?.api.setActive();+ },+ /** Close the Game view — used on Stop. */+ closeGame() {+ api?.getPanel('game')?.api.close();+ },/** Collapse a panel's group to its header / expand it back (click-to-toggle). */toggleCollapse(id: string, axis: 'width' | 'height') {const panel = api?.getPanel(id);diff --git a/desktop/src/panels/GamePanel.tsx b/desktop/src/panels/GamePanel.tsxnew file mode 100644index 000000000..e2076888d--- /dev/null+++ b/desktop/src/panels/GamePanel.tsx@@ -0,0 +1,32 @@+import { useEffect, useRef, useSyncExternalStore } from 'react';+import { PlayRealm } from '@/engine/PlayRealm';++// The "Game" dock panel: hosts the isolated play-realm iframe (PlayRealm owns the+// element + re-parents it here, so the realm survives panel remounts). The host+// div has NO React children — PlayRealm appends the iframe into it manually — so a+// status overlay is a separate absolutely-positioned sibling.+export function GamePanel() {+ const hostRef = useRef<HTMLDivElement>(null);+ const { playing, ready, error } = useSyncExternalStore(PlayRealm.subscribe, PlayRealm.getSnapshot);++ useEffect(() => {+ const el = hostRef.current;+ if (el) PlayRealm.attach(el);+ return () => PlayRealm.detach();+ }, []);++ const overlay = error+ ? `Play failed: ${error}`+ : !playing+ ? 'Press Play to run the game.'+ : !ready+ ? 'Starting…'+ : null;++ return (+ <div className="game-panel">+ <div className="game-panel__host" ref={hostRef} />+ {overlay && <div className={`game-panel__overlay${error ? ' error' : ''}`}>{overlay}</div>}+ </div>+ );+}diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 06d6ad5de..7eaeb9158 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -362,6 +362,28 @@ class ProjectStoreImpl {return uuid ? UUID_PREFIX + uuid : null;}+ /**+ * Assemble the isolated play-realm payload (REARCH_EDITOR_REALM Phase R): the+ * current scene as RAW (`@uuid:`) SceneData straight from the expanded model —+ * the runtime needs no prefab expansion and handles are realm-local, so we send+ * the lossless refs, not resolved handles — plus a uuid→url manifest the realm+ * fetches over `estella://`. Null if no scene is loaded.+ */+ playPayload(): { sceneData: SceneData; assetManifest: Record<string, string> } | null {+ const sceneData = SceneModel.serialize();+ if (!sceneData) return null;+ // The realm is same-origin with the editor (relative iframe src). A custom+ // scheme (app://) can't cross-fetch another (estella://), so under app://+ // (packaged) serve assets through the app:// project route; in dev (http+ // origin) estella:// is reachable (http may make CORS requests).+ const base = location.origin.startsWith('app:')+ ? `${location.origin}/__project__/`+ : 'estella://project/';+ const assetManifest: Record<string, string> = {};+ for (const [uuid, path] of this.uuidToPath) assetManifest[uuid] = base + path;+ return { sceneData, assetManifest };+ }+/** Display info for an asset ref (`@uuid:`), or null (none / unresolved). For* the inspector's asset control: the project-relative path + a leaf name. */assetInfo(ref: unknown): { path: string; name: string } | null {diff --git a/desktop/src/theme/viewport.css b/desktop/src/theme/viewport.cssindex 041ebf4c6..01584e5eb 100644--- a/desktop/src/theme/viewport.css+++ b/desktop/src/theme/viewport.css@@ -106,3 +106,19 @@}.vp-coord .ro strong { color: var(--text); }.vp-coord .hint { color: var(--text-mute); font-family: var(--sans); padding-left: 2px; }++/* Game view (isolated play realm iframe) — REARCH_EDITOR_REALM Phase R. */+.game-panel { position: relative; width: 100%; height: 100%; background: #0e121b; overflow: hidden; }+.game-panel__host { position: absolute; inset: 0; }+.game-panel__overlay {+ position: absolute;+ inset: 0;+ display: grid;+ place-items: center;+ padding: 16px;+ text-align: center;+ color: var(--text-mute);+ font-size: var(--fs-sm);+ pointer-events: none;+}+.game-panel__overlay.error { color: var(--error); }