Skip to content

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.

feat(editor): multiplayer play preview — listen server + N client realms

esengine55ab69677869
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx
index 171573f47..cf44cd772 100644
--- a/desktop/src/App.tsx
+++ b/desktop/src/App.tsx
@@ -16,7 +16,7 @@ import { BuildDialog } from '@/components/BuildDialog';
import { SettingsDialog } from '@/components/SettingsDialog';
import { useEditorStore } from '@/store/editorStore';
import { commands } from '@/commands';
-import { PlayRealm } from '@/engine/PlayRealm';
+import { PlayRealms } from '@/engine/PlayRealm';
import { PlayInspect } from '@/engine/PlayInspect';
import { TimelinePreview } from '@/engine/TimelinePreview';
import { TimelineRecorder } from '@/timeline/TimelineRecorder';
@@ -96,22 +96,26 @@ export function App() {
useEditorStore.getState().stop();
return;
}
- void PlayRealm.start(payload);
+ const players = useEditorStore.getState().playPlayers;
+ void PlayRealms.startSession(payload, players);
PlayInspect.start(); // poll the running game for live inspect/debug
useEditorStore.getState().setInspectWorld('game'); // flip Outliner/Details to the live game
// 'window' → a Game dock tab; 'viewport' → the Viewport mounts it (PIE).
if (useEditorStore.getState().playTarget === 'window') dockApi.openGame();
+ // Client players each get their own Game tab beside player 1.
+ if (players > 1) dockApi.openGameClients(PlayRealms.clients.map((c) => c.id));
} else {
- PlayRealm.stop();
+ PlayRealms.stopSession();
PlayInspect.stop();
useEditorStore.getState().setInspectWorld('editor');
dockApi.closeGame();
+ dockApi.closeGameClients();
// Not on mount/launcher — there is no project to stage yet.
- if (!useEditorStore.getState().showLauncher) idle(() => PlayRealm.prewarm());
+ if (!useEditorStore.getState().showLauncher) idle(() => PlayRealms.prewarm());
}
}, [isPlaying]);
useEffect(() => {
- if (isPlaying) PlayRealm.setPaused(isPaused);
+ if (isPlaying) PlayRealms.setPaused(isPaused);
}, [isPaused, isPlaying]);
// The editor opens on the launcher (project browser); the shell + engine mount
@@ -119,7 +123,7 @@ export function App() {
const showLauncher = useEditorStore((s) => s.showLauncher);
// Prewarm the play realm as soon as a project opens.
useEffect(() => {
- if (!showLauncher) idle(() => PlayRealm.prewarm());
+ if (!showLauncher) idle(() => PlayRealms.prewarm());
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [showLauncher]);
const buildOpen = useEditorStore((s) => s.buildOpen);
diff --git a/desktop/src/engine/PlayRealm.ts b/desktop/src/engine/PlayRealm.ts
index e994bc73a..242f34f8d 100644
--- a/desktop/src/engine/PlayRealm.ts
+++ b/desktop/src/engine/PlayRealm.ts
@@ -1,15 +1,21 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file PlayRealm.ts — controller for the isolated play realm.
- * 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}
+ * @file PlayRealm.ts — controller for the isolated play realm(s).
+ * A realm instance owns a detached <iframe> (play.html) re-parented into
+ * a Game panel (mirrors EngineHost's detached-canvas pattern), and the
+ * typed postMessage protocol with it:
+ * out → init {sceneData, assetManifest[, net + transferred ports]} · setPaused
* 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.
+ *
+ * Multiplayer preview (PlayRealms.startSession with players > 1): the
+ * primary realm boots as the listen server (authority + player 1) and
+ * each extra realm boots as a client, wired by MessageChannel ports the
+ * editor transfers with init — the same NetSession/NetTransport seam a
+ * shipped game uses over sockets.
*/
import { createStore } from 'zustand/vanilla';
import type { SubsystemStatus } from 'esengine';
@@ -25,12 +31,15 @@ export interface PlayRealmSnapshot {
error: string | null;
}
-class PlayRealmImpl {
+export class PlayRealmInstance {
private iframe: HTMLIFrameElement | null = null;
private payload: PlayPayload | null = null;
+ private netPorts: MessagePort[] | null = null;
private epoch = 0;
private readonly store = createStore<PlayRealmSnapshot>(() => ({ playing: false, ready: false, error: null }));
+ constructor(readonly id: number) {}
+
subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);
getSnapshot = (): PlayRealmSnapshot => this.store.getState();
private set(patch: Partial<PlayRealmSnapshot>): void {
@@ -40,7 +49,7 @@ class PlayRealmImpl {
private ensureIframe(): HTMLIFrameElement {
if (!this.iframe) {
const f = document.createElement('iframe');
- f.title = 'Game';
+ f.title = this.id === 0 ? 'Game' : `Game P${this.id + 1}`;
f.style.cssText = 'display:block;width:100%;height:100%;border:0;background:#0e121b';
window.addEventListener('message', this.onMessage);
this.iframe = f;
@@ -48,7 +57,7 @@ class PlayRealmImpl {
return this.iframe;
}
- /** Re-parent the realm iframe into the Game panel (kept alive across remounts). */
+ /** Re-parent the realm iframe into a Game panel (kept alive across remounts). */
attach(container: HTMLElement): void {
container.appendChild(this.ensureIframe());
}
@@ -73,15 +82,12 @@ class PlayRealmImpl {
* `.esengine/play/` (host + SDK + wasm + project bundle) and loads it from the
* project's `estella://` origin, so the host + the project bundle share one
* esengine instance (custom components/systems run) and all assets are
- * same-origin. Init is posted on the realm's `hello`.
+ * same-origin. Init is posted on the realm's `hello`; `netPorts` (multiplayer
+ * MessageChannel ends) transfer with it.
*/
- /** Stage the realm ahead of time so Play's prepare hits warm stamps. */
- prewarm(): void {
- window.estella.project.preparePlayRealm().catch(() => {});
- }
-
- async start(payload: PlayPayload): Promise<void> {
+ async start(payload: PlayPayload, netPorts?: MessagePort[]): Promise<void> {
this.payload = payload;
+ this.netPorts = netPorts ?? null;
this.set({ playing: true, ready: false, error: null });
const frame = this.ensureIframe();
frame.style.visibility = 'hidden';
@@ -100,6 +106,7 @@ class PlayRealmImpl {
/** Tear the realm down (releases its wasm + GL by navigating to a blank page). */
stop(): void {
this.payload = null;
+ this.netPorts = null;
if (this.iframe) {
this.iframe.style.visibility = 'hidden';
this.iframe.src = 'about:blank';
@@ -107,6 +114,15 @@ class PlayRealmImpl {
this.set({ playing: false, ready: false, error: null });
}
+ /** Full teardown for a session-scoped (client) realm: stop + drop the iframe
+ * and the window listener. The instance is not reusable afterwards. */
+ destroy(): void {
+ this.stop();
+ window.removeEventListener('message', this.onMessage);
+ this.detach();
+ this.iframe = null;
+ }
+
setPaused(paused: boolean): void {
this.post({ type: 'estella:play:setPaused', paused });
}
@@ -170,8 +186,8 @@ class PlayRealmImpl {
this.post({ type: 'estella:play:setField', entityId, comp, key, value });
}
- private post(message: PlayOutbound): void {
- this.iframe?.contentWindow?.postMessage(message, '*');
+ private post(message: PlayOutbound, transfer?: Transferable[]): void {
+ this.iframe?.contentWindow?.postMessage(message, '*', transfer);
}
private onMessage = (e: MessageEvent): void => {
@@ -188,14 +204,17 @@ class PlayRealmImpl {
this.set({ error: mismatch });
break;
}
- if (this.payload) this.post({ type: 'estella:play:init', ...this.payload });
+ if (this.payload) {
+ const ports = this.netPorts ?? undefined;
+ this.post({ type: 'estella:play:init', ...this.payload, netPorts: ports }, ports);
+ }
break;
}
case 'estella:play:log':
// The running game's console/wasm output, forwarded from the realm iframe so
// it lands in the editor's Output Log (it runs in a separate JS realm, so the
// parent's console patch never sees it).
- LogStore.push(data.level ?? 'info', 'Play', data.line ?? '');
+ LogStore.push(data.level ?? 'info', this.id === 0 ? 'Play' : `Play P${this.id + 1}`, data.line ?? '');
break;
case 'estella:play:ready':
this.set({ ready: true });
@@ -203,8 +222,9 @@ class PlayRealmImpl {
// Hand the running game keyboard focus so it's playable immediately — the
// realm's InputPlugin listens on the iframe's own document, which receives
// key events only while the iframe is focused. Without this the user has to
- // click the game first and WASD/arrows do nothing until they do.
- this.focusGame();
+ // click the game first and WASD/arrows do nothing until they do. In a
+ // multiplayer session only player 1 grabs focus (last-ready would steal it).
+ if (this.id === 0) this.focusGame();
break;
case 'estella:play:error':
this.set({ error: data.message ?? 'play realm error' });
@@ -221,4 +241,103 @@ class PlayRealmImpl {
};
}
-export const PlayRealm = new PlayRealmImpl();
+/**
+ * The session controller. Single-player keeps the primary realm's exact old
+ * behavior; `players > 1` boots primary as the listen server plus N-1 client
+ * realms wired by MessageChannel ports. Client realms are session-scoped:
+ * created on start, destroyed on stop.
+ */
+export interface PlaySessionSnapshot {
+ /** Bumps on every session start/stop — client panels re-attach on it (a
+ * multiplayer reload replaces the realm instances behind the same panel). */
+ epoch: number;
+ clientIds: number[];
+}
+
+class PlayRealmsManager {
+ readonly primary = new PlayRealmInstance(0);
+ private clients_: PlayRealmInstance[] = [];
+ private lastPayload_: PlayPayload | null = null;
+ private lastPlayers_ = 1;
+ private readonly session = createStore<PlaySessionSnapshot>(() => ({ epoch: 0, clientIds: [] }));
+
+ subscribeSession = (fn: () => void): (() => void) => this.session.subscribe(fn);
+ getSessionSnapshot = (): PlaySessionSnapshot => this.session.getState();
+ private bumpSession(): void {
+ this.session.setState({
+ epoch: this.session.getState().epoch + 1,
+ clientIds: this.clients_.map((c) => c.id),
+ });
+ }
+
+ get clients(): readonly PlayRealmInstance[] {
+ return this.clients_;
+ }
+
+ /** A live realm by id (0 = primary), or null. */
+ get(id: number): PlayRealmInstance | null {
+ if (id === 0) return this.primary;
+ return this.clients_.find((c) => c.id === id) ?? null;
+ }
+
+ /** Stage the realm ahead of time so Play's prepare hits warm stamps. */
+ prewarm(): void {
+ window.estella.project.preparePlayRealm().catch(() => {});
+ }
+
+ async startSession(payload: PlayPayload, players = 1): Promise<void> {
+ this.lastPayload_ = payload;
+ this.lastPlayers_ = players;
+ if (players <= 1) {
+ await this.primary.start(payload);
+ return;
+ }
+ // One MessageChannel per client; ports queue until both realms attach, so
+ // boot order is free.
+ const channels = Array.from({ length: players - 1 }, () => new MessageChannel());
+ const started = this.primary.start(
+ { ...payload, net: { role: 'server', player: 1 } },
+ channels.map((c) => c.port1),
+ );
+ this.clients_ = channels.map((c, i) => {
+ const realm = new PlayRealmInstance(i + 1);
+ void realm.start({ ...payload, net: { role: 'client', player: i + 2 } }, [c.port2]);
+ return realm;
+ });
+ this.bumpSession();
+ await started;
+ }
+
+ stopSession(): void {
+ this.primary.stop();
+ for (const c of this.clients_) c.destroy();
+ this.clients_ = [];
+ this.bumpSession();
+ }
+
+ setPaused(paused: boolean): void {
+ this.primary.setPaused(paused);
+ for (const c of this.clients_) c.setPaused(paused);
+ }
+
+ /** Project-code reload. Single realm hot-reloads in place; a multiplayer
+ * session restarts whole (its MessageChannel ports were consumed by the live
+ * NetSessions — fresh realms need fresh ports). */
+ reload(): void {
+ if (this.clients_.length === 0) {
+ this.primary.reload();
+ return;
+ }
+ const payload = this.lastPayload_;
+ const players = this.lastPlayers_;
+ if (!payload) return;
+ this.stopSession();
+ void this.startSession(payload, players);
+ }
+}
+
+export const PlayRealms = new PlayRealmsManager();
+
+/** The primary realm — the single-player surface every existing consumer
+ * (inspect, profiler, subsystems, viewport PIE) talks to. */
+export const PlayRealm = PlayRealms.primary;
diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.ts
index ad876da13..dd38d4683 100644
--- a/desktop/src/engine/playProtocol.ts
+++ b/desktop/src/engine/playProtocol.ts
@@ -18,7 +18,7 @@ import type { SceneData, PhysicsPluginConfig } from 'esengine';
* compares it against its own and refuses a mismatch (P1) rather than failing
* obscurely on a shape it doesn't understand. Bump on any incompatible message change.
*/
-export const PLAY_PROTOCOL_VERSION = 1;
+export const PLAY_PROTOCOL_VERSION = 2;
/**
* The handshake check: `null` if the realm's reported protocol version is compatible
@@ -36,6 +36,19 @@ export function playProtocolMismatch(realmVersion: number | undefined): string |
/** Matches LogStore's LogLevel; redeclared here to keep the contract editor-dep-free. */
export type PlayLogLevel = 'info' | 'warn' | 'error';
+/**
+ * The realm's role in a multiplayer preview session. The server realm is the
+ * listen host (authority + player 1); each client realm connects over a
+ * MessageChannel port the editor transfers alongside `init` (`netPorts` on the
+ * message — ports only cross realms via the postMessage transfer list, so they
+ * ride the message itself, not this payload).
+ */
+export interface PlayNetConfig {
+ role: 'server' | 'client';
+ /** 1-based player number, for window titles/diagnostics. */
+ player: number;
+}
+
/** The scene + project config handed to a fresh realm on boot. */
export interface PlayPayload {
sceneData: SceneData;
@@ -44,6 +57,8 @@ export interface PlayPayload {
physicsEnabled?: boolean;
/** Project physics world config (gravity, solver, collision matrix) — forwarded. */
physicsConfig?: PhysicsPluginConfig;
+ /** Multiplayer preview role; absent = a plain single-player session. */
+ net?: PlayNetConfig;
}
/** A live inspect snapshot: a shallow entity tree (Outliner) + the selected entity's
@@ -72,9 +87,10 @@ export interface PlayStatsReply {
vramBytes: number;
}
-/** editor → realm. Discriminated by `type`. */
+/** editor → realm. Discriminated by `type`. `init` may carry transferred
+ * MessagePorts in `netPorts` (server: one per client; client: exactly one). */
export type PlayOutbound =
- | ({ type: 'estella:play:init' } & PlayPayload)
+ | ({ type: 'estella:play:init'; netPorts?: MessagePort[] } & PlayPayload)
| { type: 'estella:play:setPaused'; paused: boolean }
| { type: 'estella:play:reload' }
| { type: 'estella:play:query'; kind: PlayQueryKind; reqId: number; selectedId?: number | null }
diff --git a/desktop/src/layout/DockLayout.tsx b/desktop/src/layout/DockLayout.tsx
index 1c0e542c5..061ced5d6 100644
--- a/desktop/src/layout/DockLayout.tsx
+++ b/desktop/src/layout/DockLayout.tsx
@@ -13,7 +13,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 { GamePanel, GameClientPanel } from '@/panels/GamePanel';
import { Sequencer } from '@/panels/Sequencer';
import { TilesetEditor } from '@/panels/TilesetEditor';
import { TilemapPainter } from '@/panels/TilemapPainter';
@@ -47,6 +47,11 @@ const components: Record<string, FC<IDockviewPanelProps>> = {
profiler: () => <ErrorBoundary label="profiler"><ProfilerPanel /></ErrorBoundary>,
// The "Game" view (isolated play realm) — added on Play, removed on Stop.
game: () => panel('game', <GamePanel />),
+ // Multiplayer client realms ("Game P2..N") — session-scoped, keyed by realmId.
+ gameClient: (props) => {
+ const realmId = Number((props.params as { realmId?: number } | undefined)?.realmId ?? 0);
+ return panel(`game-client-${realmId}`, <GameClientPanel realmId={realmId} />);
+ },
};
// Bumped to v6 (document-area editors): Viewport center, right column Outliner-
diff --git a/desktop/src/layout/Toolbar.tsx b/desktop/src/layout/Toolbar.tsx
index 9ccac9fd9..0ace2e700 100644
--- a/desktop/src/layout/Toolbar.tsx
+++ b/desktop/src/layout/Toolbar.tsx
@@ -73,6 +73,8 @@ export function Toolbar() {
// command registry so menu, toolbar, and keyboard share one implementation.
const playTarget = useEditorStore((s) => s.playTarget);
const setPlayTarget = useEditorStore((s) => s.setPlayTarget);
+ const playPlayers = useEditorStore((s) => s.playPlayers);
+ const setPlayPlayers = useEditorStore((s) => s.setPlayPlayers);
const [modeMenu, setModeMenu] = useState<{ x: number; y: number } | null>(null);
const { tool, snapping, showGrid, showGizmos, isPlaying, isPaused, togglePause, stop } =
useEditorStore();
@@ -171,6 +173,13 @@ export function Toolbar() {
items={[
{ label: 'Play In Viewport', checked: playTarget === 'viewport', onClick: () => setPlayTarget('viewport') },
{ label: 'Play In New Window', checked: playTarget === 'window', onClick: () => setPlayTarget('window') },
+ { sep: true },
+ // Multiplayer preview: 1 = plain play; N>1 boots a listen-server realm
+ // (player 1) + N-1 client realms wired by in-editor replication.
+ { label: 'Single Player', checked: playPlayers <= 1, onClick: () => setPlayPlayers(1) },
+ { label: '2 Players (Listen Server)', checked: playPlayers === 2, onClick: () => setPlayPlayers(2) },
+ { label: '3 Players (Listen Server)', checked: playPlayers === 3, onClick: () => setPlayPlayers(3) },
+ { label: '4 Players (Listen Server)', checked: playPlayers === 4, onClick: () => setPlayPlayers(4) },
]}
/>
)}
diff --git a/desktop/src/layout/dockApi.ts b/desktop/src/layout/dockApi.ts
index 4212a31b0..155e953ef 100644
--- a/desktop/src/layout/dockApi.ts
+++ b/desktop/src/layout/dockApi.ts
@@ -95,6 +95,31 @@ export const dockApi = {
closeGame() {
api?.getPanel('game')?.api.close();
},
+ /** Open the multiplayer client views ("Game P2..N") beside the primary Game
+ * view — used on multiplayer Play. Splits right so players sit side by side. */
+ openGameClients(realmIds: number[]) {
+ if (!api) return;
+ for (const realmId of realmIds) {
+ const id = `game-client-${realmId}`;
+ if (!api.getPanel(id)) {
+ const anchor = api.getPanel('game') ?? api.getPanel('viewport');
+ api.addPanel({
+ id,
+ component: 'gameClient',
+ title: `Game P${realmId + 1}`,
+ params: { realmId },
+ position: anchor ? { referencePanel: anchor.id, direction: 'right' } : undefined,
+ });
+ }
+ }
+ },
+ /** Close every multiplayer client view — used on Stop. */
+ closeGameClients() {
+ if (!api) return;
+ for (const p of api.panels.filter((p) => p.id.startsWith('game-client-'))) {
+ p.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.tsx
index 045313012..97ce96049 100644
--- a/desktop/src/panels/GamePanel.tsx
+++ b/desktop/src/panels/GamePanel.tsx
@@ -1,16 +1,27 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { useEffect, useRef, useSyncExternalStore } from 'react';
-import { PlayRealm } from '@/engine/PlayRealm';
+import { PlayRealm, PlayRealms } from '@/engine/PlayRealm';
import { useEditorStore } from '@/store/editorStore';
-// The "Game" dock panel: hosts the isolated play-realm iframe (PlayRealm owns the
+// The "Game" dock panel: hosts the isolated play-realm iframe (the realm 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
+// div has NO React children — the realm appends the iframe into it manually — so a
// status overlay is a separate absolutely-positioned sibling.
+
+function overlayFor(snap: { playing: boolean; ready: boolean; error: string | null }): string | null {
+ return snap.error
+ ? `Play failed: ${snap.error}`
+ : !snap.playing
+ ? 'Press Play to run the game.'
+ : !snap.ready
+ ? 'Starting…'
+ : null;
+}
+
export function GamePanel() {
const hostRef = useRef<HTMLDivElement>(null);
- const { playing, ready, error } = useSyncExternalStore(PlayRealm.subscribe, PlayRealm.getSnapshot);
+ const snap = useSyncExternalStore(PlayRealm.subscribe, PlayRealm.getSnapshot);
const playTarget = useEditorStore((s) => s.playTarget);
// Only host the realm iframe in 'window' mode — in 'viewport' mode the Viewport
@@ -23,18 +34,44 @@ export function GamePanel() {
};
}, [playTarget]);
- const overlay = error
- ? `Play failed: ${error}`
- : !playing
- ? 'Press Play to run the game.'
- : !ready
- ? 'Starting…'
- : null;
+ const overlay = overlayFor(snap);
+ return (
+ <div className="game-panel">
+ <div className="game-panel__host" ref={hostRef} />
+ {overlay && <div className={`game-panel__overlay${snap.error ? ' error' : ''}`}>{overlay}</div>}
+ </div>
+ );
+}
+
+const NO_SNAPSHOT = (): null => null;
+
+/** A multiplayer client realm's panel ("Game P2..N"). The realm instance is
+ * session-scoped, so the panel re-attaches whenever the session epoch bumps —
+ * a code reload restarts the whole session with fresh instances behind the
+ * same panel. */
+export function GameClientPanel({ realmId }: { realmId: number }) {
+ const hostRef = useRef<HTMLDivElement>(null);
+ const session = useSyncExternalStore(PlayRealms.subscribeSession, PlayRealms.getSessionSnapshot);
+ const realm = PlayRealms.get(realmId);
+
+ useEffect(() => {
+ const el = hostRef.current;
+ const live = PlayRealms.get(realmId);
+ if (el && live) live.attach(el);
+ return () => live?.detach();
+ }, [realmId, session.epoch]);
+
+ // A missing realm (stale restored layout, stopped session) renders idle.
+ const snap = useSyncExternalStore(
+ realm ? realm.subscribe : PlayRealms.subscribeSession,
+ realm ? realm.getSnapshot : NO_SNAPSHOT,
+ );
+ const overlay = snap ? overlayFor(snap) : 'No multiplayer session.';
return (
<div className="game-panel">
<div className="game-panel__host" ref={hostRef} />
- {overlay && <div className={`game-panel__overlay${error ? ' error' : ''}`}>{overlay}</div>}
+ {overlay && <div className={`game-panel__overlay${snap?.error ? ' error' : ''}`}>{overlay}</div>}
</div>
);
}
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index 144c2825e..a5639b7b1 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -14,7 +14,7 @@
* Everything is same-origin estella:// (host, sdk, bundle, wasm, assets),
* sidestepping the custom-scheme cross-fetch ban.
*/
-import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, getComponent, clearUserComponents, getUserComponentFingerprint, probeRegistrations } from 'esengine';
+import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, getComponent, clearUserComponents, getUserComponentFingerprint, probeRegistrations, Net, MessagePortTransport } from 'esengine';
import type { App, ESEngineModule, SceneData } from 'esengine';
import { PLAY_PROTOCOL_VERSION } from './engine/playProtocol';
import type { PlayOutbound, PlayInbound } from './engine/playProtocol';
@@ -200,6 +200,26 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
(window as unknown as { __estellaPlay?: unknown }).__estellaPlay = { app };
}
+/**
+ * Wire this realm's replication role. The ports arrived transferred with
+ * `init`; a MessagePort queues until both ends attach, so the server and
+ * client realms may boot in any order — the client's `connect` handshake
+ * simply resolves once the server side comes up.
+ */
+async function wireNet(msg: InitMessage): Promise<void> {
+ if (!msg.net || !app) return;
+ const session = app.getResource(Net);
+ const ports = msg.netPorts ?? [];
+ if (msg.net.role === 'server') {
+ const server = session.startServer();
+ for (const port of ports) server.attachConnection(new MessagePortTransport(port));
+ console.log(`[play] listen server up (player ${msg.net.player}, ${ports.length} client port(s))`);
+ } else if (ports[0]) {
+ await session.connect(new MessagePortTransport(ports[0]));
+ console.log(`[play] connected as player ${msg.net.player}`);
+ }
+}
+
async function boot(msg: InitMessage): Promise<void> {
if (booted) return;
booted = true;
@@ -215,6 +235,7 @@ async function boot(msg: InitMessage): Promise<void> {
}
await ensureEngine();
await buildAppAndRun(msg);
+ await wireNet(msg);
post({ type: 'estella:play:ready' });
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
@@ -260,6 +281,13 @@ async function tryHotSwapReload(): Promise<boolean> {
async function reload(): Promise<void> {
if (!booted || !engineModule || !lastInit) return;
+ // A multiplayer session can't hot-rebuild one realm: its MessageChannel ports
+ // were consumed by the live NetSession. The editor restarts the whole session
+ // instead; this guard is defense against a stray reload message.
+ if (lastInit.net) {
+ console.warn('[play] code reload in a multiplayer session needs a session restart');
+ return;
+ }
try {
// Fast path (RC10 P3): if only system logic changed (component schemas unchanged),
// hot-swap the function bodies and keep the live World — runtime state survives. Any
diff --git a/desktop/src/project/fsWatch.ts b/desktop/src/project/fsWatch.ts
index dcf38b9a5..79c2dcf64 100644
--- a/desktop/src/project/fsWatch.ts
+++ b/desktop/src/project/fsWatch.ts
@@ -9,7 +9,7 @@
* refresh the asset registry + Content Browser, not just the editor's own ops.
*/
import { ProjectStore } from './ProjectStore';
-import { PlayRealm } from '../engine/PlayRealm';
+import { PlayRealm, PlayRealms } from '../engine/PlayRealm';
const listeners = new Set<() => void>();
let version = 0;
@@ -51,7 +51,7 @@ async function rebuildScriptsAndReloadPlay(): Promise<void> {
console.warn('[fsWatch] project script rebuild failed; keeping running realm', res.errors);
return;
}
- PlayRealm.reload();
+ PlayRealms.reload();
} catch (e) {
console.warn('[fsWatch] project script rebuild threw', e);
}
diff --git a/desktop/src/store/editorStore.ts b/desktop/src/store/editorStore.ts
index 841f4e336..ffd545845 100644
--- a/desktop/src/store/editorStore.ts
+++ b/desktop/src/store/editorStore.ts
@@ -21,6 +21,10 @@ interface EditorState {
// Where Play runs: in the Viewport (UE5 PIE, default) or a separate Game tab.
playTarget: 'viewport' | 'window';
setPlayTarget: (t: 'viewport' | 'window') => void;
+ // Multiplayer preview: how many players the next Play session boots (1 = plain
+ // single realm; N>1 = a listen-server realm + N-1 client realms, replicated).
+ playPlayers: number;
+ setPlayPlayers: (n: number) => void;
// Which world the Outliner/Details inspect: the edit scene or the live game
// (UE5 world picker). Auto-flips to 'game' on Play, 'editor' on Stop.
inspectWorld: 'editor' | 'game';
@@ -100,6 +104,12 @@ export const useEditorStore = create<EditorState>((set) => ({
if (typeof localStorage !== 'undefined') localStorage.setItem('estella.playTarget', playTarget);
set({ playTarget });
},
+ playPlayers:
+ (typeof localStorage !== 'undefined' ? Number(localStorage.getItem('estella.playPlayers')) : 0) || 1,
+ setPlayPlayers: (playPlayers) => {
+ if (typeof localStorage !== 'undefined') localStorage.setItem('estella.playPlayers', String(playPlayers));
+ set({ playPlayers });
+ },
inspectWorld: 'editor',
setInspectWorld: (inspectWorld) => set({ inspectWorld }),