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): project-open loading screen; prewarm the play realm engine
yhh7a9c21ee438e
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex 049f0c431..e49feef84 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -11,6 +11,8 @@ import '@/engine/EditorSession'; // side effect: constructs defaultSession → wimport { Launcher } from '@/launcher/Launcher';import { Toaster } from '@/components/Toaster';import { ConfirmHost } from '@/components/ConfirmHost';+import { LoadingScreen } from '@/components/LoadingScreen';+import { LoadGate } from '@/store/loadGate';import { Perf } from '@/components/Perf';import { PerfRealmBridge } from '@/components/PerfRealmBridge';import { BuildDialog } from '@/components/BuildDialog';@@ -185,9 +187,32 @@ export function App() {// 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.)const showLauncher = useEditorStore((s) => s.showLauncher);- // Prewarm the play realm as soon as a project opens.+ // Project-open loading gate (Unreal-style): overlay the mounting editor while+ // the editor engine boots AND the play realm prewarms its engine, so entering+ // the editor and the FIRST Play are both smooth. Everything heavy is warmed up+ // front; the overlay clears when every task is done.useEffect(() => {- if (!showLauncher) idle(() => PlayRealms.prewarm());+ if (showLauncher) return;+ LoadGate.begin([+ { key: 'engine', label: t('load.engine') },+ { key: 'playRealm', label: t('load.playRealm') },+ ]);+ let cancelled = false;+ const safety = setTimeout(() => LoadGate.close(), 20000); // never trap the user behind the overlay+ const engineReady = new Promise<void>((resolve) => {+ if (EngineHost.getSnapshot().status === 'ready') return resolve();+ const un = EngineHost.subscribe(() => {+ if (EngineHost.getSnapshot().status === 'ready') { un(); resolve(); }+ });+ });+ void engineReady+ .then(() => { if (!cancelled) LoadGate.done('engine'); })+ // Engine ready ⇒ the viewport is mounted ⇒ the persistent play host is+ // attached, so the realm can boot its engine now (no scene, off-screen).+ .then(() => (cancelled ? undefined : PlayRealms.prewarm()))+ .then(() => { if (!cancelled) LoadGate.done('playRealm'); })+ .finally(() => clearTimeout(safety));+ return () => { cancelled = true; clearTimeout(safety); LoadGate.close(); };// eslint-disable-next-line react-hooks/exhaustive-deps}, [showLauncher]);const buildOpen = useEditorStore((s) => s.buildOpen);@@ -211,6 +236,7 @@ export function App() {{tilemapPickerOpen && <TilemapPickerDialog />}<Toaster /><ConfirmHost />+ <LoadingScreen /></div>);}diff --git a/desktop/src/components/LoadingScreen.tsx b/desktop/src/components/LoadingScreen.tsxnew file mode 100644index 000000000..058c84f17--- /dev/null+++ b/desktop/src/components/LoadingScreen.tsx@@ -0,0 +1,29 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { useSyncExternalStore } from 'react';+import { LoadGate } from '@/store/loadGate';++// Full-screen project-open loading overlay (Unreal-style): shown over the mounting+// editor while prewarm tasks run, so the editor and the first Play are both warm+// once it clears. Task labels are supplied by the orchestrator (already localized).+export function LoadingScreen() {+ const { active, tasks } = useSyncExternalStore(LoadGate.subscribe, LoadGate.getSnapshot);+ if (!active) return null;+ return (+ <div className="loadscreen" role="status" aria-live="polite">+ <div className="loadscreen__panel">+ <svg className="loadscreen__mark" viewBox="0 0 24 24" aria-hidden="true">+ <path d="M12 2 L14 10 L22 12 L14 14 L12 22 L10 14 L2 12 L10 10 Z" />+ </svg>+ <div className="loadscreen__tasks">+ {tasks.map((task) => (+ <div key={task.key} className={`loadscreen__task${task.done ? ' is-done' : ''}`}>+ <span className="loadscreen__spinner" aria-hidden="true" />+ <span className="loadscreen__label">{task.label}</span>+ </div>+ ))}+ </div>+ </div>+ </div>+ );+}diff --git a/desktop/src/engine/PlayRealm.ts b/desktop/src/engine/PlayRealm.tsindex ce5b23dba..a7f9105d6 100644--- a/desktop/src/engine/PlayRealm.ts+++ b/desktop/src/engine/PlayRealm.ts@@ -42,6 +42,7 @@ export class PlayRealmInstance {// so a re-Play hands over the new scene instead of cold-booting a fresh iframe// (single-player primary only; multiplayer + play-in-window cold-boot as before).private warm = false;+ private warmedResolve: (() => void) | null = null;private readonly store = createStore<PlayRealmSnapshot>(() => ({ playing: false, ready: false, error: null }));constructor(readonly id: number) {}@@ -165,6 +166,27 @@ export class PlayRealmInstance {this.post({ type: 'estella:play:setPaused', paused });}+ /** Idle prewarm: mount + boot the realm's engine (wasm + GL, NO scene) in the+ * persistent iframe so the FIRST Play is a warm scene load, not a cold engine+ * bring-up. Resolves when the engine is up (or on a timeout / if it can't warm+ * yet). Best-effort: any failure just leaves the first Play cold. */+ async prewarm(): Promise<void> {+ if (this.id !== 0 || this.warm || this.store.getState().playing) return;+ const realm = await window.estella.project.preparePlayRealm().catch(() => null);+ if (!realm?.ok || this.warm || this.store.getState().playing) return;+ const frame = this.ensureIframe();+ // Must be in the DOM to load; the viewport attaches it as the persistent play+ // host. Not attached yet ⇒ skip — a later prewarm tick warms it.+ if (!frame.isConnected) return;+ frame.style.visibility = 'hidden';+ frame.src = `estella://project/${realm.hostPath}?n=${++this.epoch}`;+ // hello (no payload) → we post 'warm' → host boots engine → 'warmed' resolves this.+ await new Promise<void>((resolve) => {+ this.warmedResolve = resolve;+ setTimeout(resolve, 10000); // never block the loading gate forever+ });+ }+/** Hot-reload the running realm's project code in place: the realm re-imports* the rebuilt bundle and rebuilds its World on the live wasm + GL + assets* (fast restart from the play-start snapshot), no iframe reboot. No-op unless a@@ -243,7 +265,10 @@ export class PlayRealmInstance {break;}if (this.id === 0) bootProfiler.mark('iframe + host bundle load (→hello)');- this.postInit();+ // A real start() set the payload → play it; a prewarm navigate left it null+ // → boot the engine only (no scene) so the first Play is warm.+ if (this.payload) this.postInit();+ else this.post({ type: 'estella:play:warm' });break;}case 'estella:play:log':@@ -272,6 +297,13 @@ export class PlayRealmInstance {// multiplayer session only player 1 grabs focus (last-ready would steal it).if (this.id === 0) this.focusGame();break;+ case 'estella:play:warmed':+ // Idle prewarm finished: the engine is up with no scene, so the first+ // Play is a warm scene load. Resolve any awaiting prewarm() (loading gate).+ if (this.id === 0 && !this.netPorts) this.warm = true;+ this.warmedResolve?.();+ this.warmedResolve = null;+ break;case 'estella:play:error':this.set({ error: data.message ?? t('proj.playRealmError') });break;@@ -326,9 +358,11 @@ class PlayRealmsManager {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(() => {});+ /** Prewarm the primary realm's engine ahead of Play (idle / project-open loading+ * gate): boots its wasm + GL with no scene so the first Play is a warm scene+ * load. Resolves when warm (or on timeout). Best-effort. */+ prewarm(): Promise<void> {+ return this.primary.prewarm();}async startSession(payload: PlayPayload, players = 1): Promise<void> {diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.tsindex e83d9e564..ba45a1844 100644--- a/desktop/src/engine/playProtocol.ts+++ b/desktop/src/engine/playProtocol.ts@@ -97,6 +97,9 @@ export interface PlayStatsReply {* MessagePorts in `netPorts` (server: one per client; client: exactly one). */export type PlayOutbound =| ({ type: 'estella:play:init'; netPorts?: MessagePort[] } & PlayPayload)+ // Boot the realm's wasm + GL WITHOUT a scene (idle prewarm), so the first Play+ // is a warm scene load, not a cold engine bring-up. Replied with `warmed`.+ | { type: 'estella:play:warm' }| { type: 'estella:play:setPaused'; paused: boolean }| { type: 'estella:play:reload' }| { type: 'estella:play:query'; kind: PlayQueryKind; reqId: number; selectedId?: number | null }@@ -105,6 +108,8 @@ export type PlayOutbound =/** realm → editor. Discriminated by `type`. */export type PlayInbound =| { type: 'estella:play:hello'; protocolVersion: number }+ // The realm's engine is up (reply to `warm`) — the editor's first Play will be warm.+ | { type: 'estella:play:warmed' }// `phases` (optional) carries the realm's own boot sub-timing (bundle import,// wasm instantiate, scene+asset load) so the editor can fold it into the Play// profile — the realm runs in a separate JS realm and can't share the profiler.diff --git a/desktop/src/i18n/messages/layout.ts b/desktop/src/i18n/messages/layout.tsindex c352a4679..a762376aa 100644--- a/desktop/src/i18n/messages/layout.ts+++ b/desktop/src/i18n/messages/layout.ts@@ -80,6 +80,8 @@ export const layoutMessages = defineMessages({'layout.mods.running': { en: 'running', zh: '运行中' },'layout.mods.idle': { en: 'idle', zh: '空闲' },'layout.mods.ready': { en: 'ready', zh: '就绪' },+ 'load.engine': { en: 'Loading engine…', zh: '加载引擎…' },+ 'load.playRealm': { en: 'Preparing play realm…', zh: '预热运行环境…' },// — Window controls —'layout.minimize': { en: 'Minimize', zh: '最小化' },diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.tsindex e6fbdf94a..69ad10038 100644--- a/desktop/src/playHost.ts+++ b/desktop/src/playHost.ts@@ -284,6 +284,24 @@ async function warmRebuild(msg: InitMessage): Promise<void> {}}+/** Bring up the project bundle + wasm + GL WITHOUT a scene (idle prewarm). A+ * later `init` then only pays the scene load — the first Play is warm too.+ * ensureEngine is idempotent, so a subsequent boot()/warmRebuild is a no-op here. */+async function warm(): Promise<void> {+ try {+ try {+ await import(/* @vite-ignore */ bundleUrl);+ } catch {+ /* no project bundle — builtin-only */+ }+ await ensureEngine();+ post({ type: 'estella:play:warmed' });+ } catch (err) {+ // Prewarm is best-effort: a failure just means the first Play cold-boots.+ console.warn('[play] prewarm failed', err);+ }+}+async function boot(msg: InitMessage): Promise<void> {lastInit = msg;// Warm re-Play: wasm + GL are already alive from a prior Play, so rebuild the@@ -432,6 +450,9 @@ window.addEventListener('message', (e: MessageEvent) => {case 'estella:play:init':void boot(e.data as InitMessage);break;+ case 'estella:play:warm':+ void warm();+ break;case 'estella:play:setPaused':app?.setPaused(!!data.paused);break;diff --git a/desktop/src/store/loadGate.ts b/desktop/src/store/loadGate.tsnew file mode 100644index 000000000..ac4492416--- /dev/null+++ b/desktop/src/store/loadGate.ts@@ -0,0 +1,47 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The project-open load gate: a small store of the prewarm tasks the+ * editor waits on before it's fully interactive (the editor engine boot,+ * the play-realm engine prewarm, …). A LoadingScreen overlays the editor+ * while any task is pending, so everything heavy is warmed up front —+ * entering the editor and the FIRST Play are both smooth (Unreal-style).+ */+import { createStore } from 'zustand/vanilla';++export interface LoadTask {+ key: string;+ label: string;+ done: boolean;+}++interface LoadGateState {+ active: boolean;+ tasks: readonly LoadTask[];+}++class LoadGateImpl {+ private readonly store = createStore<LoadGateState>(() => ({ active: false, tasks: [] }));++ subscribe = (fn: () => void): (() => void) => this.store.subscribe(fn);+ getSnapshot = (): LoadGateState => this.store.getState();++ /** Open the gate with the prewarm tasks to wait on (all start pending). */+ begin(tasks: ReadonlyArray<{ key: string; label: string }>): void {+ this.store.setState({ active: true, tasks: tasks.map((t) => ({ ...t, done: false })) });+ }++ /** Mark a task complete; the gate closes once every task is done. */+ done(key: string): void {+ const tasks = this.store.getState().tasks.map((t) => (t.key === key ? { ...t, done: true } : t));+ this.store.setState({ tasks, active: tasks.some((t) => !t.done) });+ }++ /** Force the gate shut — the editor must never be stuck behind it (timeout / abort). */+ close(): void {+ this.store.setState({ active: false });+ }+}++/** Shared singleton — one load gate at a time (a project open is a single sequence). */+export const LoadGate = new LoadGateImpl();diff --git a/desktop/src/theme/app.css b/desktop/src/theme/app.cssindex 2ea0c4498..972ed63c4 100644--- a/desktop/src/theme/app.css+++ b/desktop/src/theme/app.css@@ -716,3 +716,51 @@ body.thumb-capture .viewport__play-stop {transform: translateY(0);}}++/* Project-open loading overlay (LoadingScreen): an Unreal-style splash over the+ mounting editor while prewarm tasks run (editor engine + play realm). Covers+ the shell at a high z so a half-mounted editor never flashes through; the gate+ store clears `active` when every task is done and the overlay unmounts. */+.loadscreen {+ position: fixed;+ inset: 0;+ z-index: 1000;+ display: grid;+ place-items: center;+ background: var(--srf-0);+ animation: loadscreen-in 140ms ease;+}+.loadscreen__panel { display: flex; flex-direction: column; align-items: center; gap: 26px; }+.loadscreen__mark {+ width: 54px;+ height: 54px;+ fill: var(--run);+ animation: loadscreen-pulse 1.7s ease-in-out infinite;+}+.loadscreen__tasks { display: flex; flex-direction: column; gap: 11px; min-width: 200px; }+.loadscreen__task {+ display: flex;+ align-items: center;+ gap: 10px;+ color: var(--text-dim);+ font-size: 13px;+ transition: color 220ms ease;+}+.loadscreen__task.is-done { color: var(--text); }+.loadscreen__spinner {+ flex: none;+ width: 14px;+ height: 14px;+ border-radius: 50%;+ border: 2px solid var(--border);+ border-top-color: var(--run);+ animation: loadscreen-spin 720ms linear infinite;+}+.loadscreen__task.is-done .loadscreen__spinner {+ border-color: var(--run);+ background: var(--run);+ animation: none;+}+@keyframes loadscreen-spin { to { transform: rotate(360deg); } }+@keyframes loadscreen-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }+@keyframes loadscreen-in { from { opacity: 0; } to { opacity: 1; } }