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): in-place hot-reload of gameplay logic in the play realm

esenginef1b3e73a2037
diff --git a/desktop/src/engine/PlayRealm.ts b/desktop/src/engine/PlayRealm.ts
index 2748f789a..8b8fd8cc1 100644
--- a/desktop/src/engine/PlayRealm.ts
+++ b/desktop/src/engine/PlayRealm.ts
@@ -100,6 +100,16 @@ class PlayRealmImpl {
this.post({ type: 'estella:play:setPaused', paused });
}
+ /** 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
+ * session is live and ready; `ready` flips back on the realm's `ready` reply. */
+ reload(): void {
+ if (!this.iframe?.contentWindow || !this.store.getState().ready) return;
+ this.set({ ready: false });
+ this.post({ type: 'estella:play:reload' });
+ }
+
// — Live introspection bridge (UE5-PIE Details): query/mutate the running World —
private reqSeq = 0;
private readonly pending = new Map<number, (data: unknown) => void>();
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index d1f53923a..0d814d7ae 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, serializeScene, getComponent } from 'esengine';
+import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, serializeScene, getComponent, clearUserComponents } from 'esengine';
import type { App, ESEngineModule, SceneData } from 'esengine';
interface InitMessage {
@@ -38,12 +38,76 @@ window.addEventListener('resize', resize);
resize();
let app: App | null = null;
+let engineModule: ESEngineModule | null = null;
+let glHandle = 0;
+/** The init snapshot of the current play session, replayed on hot-reload: a code
+ * edit restarts the level from where Play began (CODE reloads; the scene is the
+ * play-start snapshot, not a fresh editor scene). */
+let lastInit: InitMessage | null = null;
let booted = false;
+let reloadSeq = 0;
const post = (m: Record<string, unknown>) => parent.postMessage(m, '*');
+/** Create the wasm module + GL context ONCE; both persist across hot-reloads —
+ * re-instantiating wasm and re-creating GL is the expensive part a reload skips. */
+async function ensureEngine(): Promise<void> {
+ if (engineModule) return;
+ const { default: createModule } = (await import(/* @vite-ignore */ `${wasmBase}esengine.js`)) as {
+ default: (options?: Record<string, unknown>) => Promise<ESEngineModule>;
+ };
+ const module = await createModule({
+ canvas,
+ locateFile: (p: string) => `${wasmBase}${p}`,
+ print: (t: string) => console.log('[wasm]', t),
+ printErr: (t: string) => console.warn('[wasm]', t),
+ });
+
+ const gl = canvas.getContext('webgl2', {
+ alpha: false,
+ antialias: true,
+ depth: true,
+ stencil: true,
+ premultipliedAlpha: false,
+ }) as WebGL2RenderingContext | null;
+ if (!gl) throw new Error('WebGL2 is not available in this realm.');
+ glHandle = module.GL.registerContext(gl, { majorVersion: 2, minorVersion: 0, enableExtensionsByDefault: true });
+ engineModule = module;
+}
+
+/** Build a fresh App on the (preserved) module + GL and run `msg`'s scene. The
+ * caller imports the project bundle BEFORE this, so its components/systems are
+ * already in the registry initPlayRealmRuntime drains. createWebApp's
+ * initRendererWithContext early-returns once the renderer is live, so the GL +
+ * EstellaContext are reused, not rebuilt — only the App + a fresh ECS Registry
+ * are new. */
+async function buildAppAndRun(msg: InitMessage): Promise<void> {
+ const module = engineModule!;
+ app = createWebApp(module, {
+ glContextHandle: glHandle,
+ getViewportSize: () => ({ width: canvas.width, height: canvas.height }),
+ wasmBaseUrl: wasmBase.replace(/\/$/, ''), // SDK appends "/<file>" — no trailing slash
+ });
+ setEditorMode(false);
+ setPlayMode(true);
+
+ await initPlayRealmRuntime({
+ app,
+ module,
+ canvas,
+ sceneData: msg.sceneData,
+ assetManifest: msg.assetManifest,
+ // physics.wasm is served next to esengine.wasm; load it on demand.
+ wasmBaseUrl: wasmBase.replace(/\/$/, ''),
+ physicsEnabled: msg.physicsEnabled,
+ physicsGravity: msg.physicsGravity,
+ enableStats: true, // editor profiler: per-phase / per-system frame timing
+ });
+}
+
async function boot(msg: InitMessage): Promise<void> {
if (booted) return;
booted = true;
+ lastInit = msg;
try {
// Register the project's own components/systems FIRST (side-effect import; its
// `import 'esengine'` resolves through the import map to the shared instance).
@@ -53,47 +117,8 @@ async function boot(msg: InitMessage): Promise<void> {
} catch {
/* no project bundle — builtin components/systems only */
}
-
- const { default: createModule } = (await import(/* @vite-ignore */ `${wasmBase}esengine.js`)) as {
- default: (options?: Record<string, unknown>) => Promise<ESEngineModule>;
- };
- const module = await createModule({
- canvas,
- locateFile: (p: string) => `${wasmBase}${p}`,
- print: (t: string) => console.log('[wasm]', t),
- printErr: (t: string) => console.warn('[wasm]', t),
- });
-
- const gl = canvas.getContext('webgl2', {
- alpha: false,
- antialias: true,
- depth: true,
- stencil: true,
- premultipliedAlpha: false,
- }) as WebGL2RenderingContext | null;
- if (!gl) throw new Error('WebGL2 is not available in this realm.');
- const glHandle = module.GL.registerContext(gl, { majorVersion: 2, minorVersion: 0, enableExtensionsByDefault: true });
-
- app = createWebApp(module, {
- glContextHandle: glHandle,
- getViewportSize: () => ({ width: canvas.width, height: canvas.height }),
- wasmBaseUrl: wasmBase.replace(/\/$/, ''), // SDK appends "/<file>" — no trailing slash
- });
- setEditorMode(false);
- setPlayMode(true);
-
- await initPlayRealmRuntime({
- app,
- module,
- canvas,
- sceneData: msg.sceneData,
- assetManifest: msg.assetManifest,
- // physics.wasm is served next to esengine.wasm; load it on demand.
- wasmBaseUrl: wasmBase.replace(/\/$/, ''),
- physicsEnabled: msg.physicsEnabled,
- physicsGravity: msg.physicsGravity,
- enableStats: true, // editor profiler: per-phase / per-system frame timing
- });
+ await ensureEngine();
+ await buildAppAndRun(msg);
post({ type: 'estella:play:ready' });
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
@@ -106,6 +131,40 @@ async function boot(msg: InitMessage): Promise<void> {
}
}
+/**
+ * Hot-reload the project's code in place — no wasm re-instantiation, no GL rebuild.
+ * Tears the App down keeping the renderer alive (`quit({keepRenderer})` — a full
+ * quit destroys the WebGL context), frees the old C++ Registry (disconnect only
+ * drops the JS ref), clears the per-context user components so a component-schema
+ * edit re-registers fresh (builtins are global and untouched), re-imports the
+ * rebuilt bundle (cache-busted), then rebuilds the App from the play-start
+ * snapshot. ~100ms vs a full realm reboot.
+ */
+async function reload(): Promise<void> {
+ if (!booted || !engineModule || !lastInit) return;
+ try {
+ if (app) {
+ const oldRegistry = app.world.getCppRegistry();
+ app.quit({ keepRenderer: true });
+ // Free the wasm Registry so each reload doesn't leak one onto the heap.
+ try { (oldRegistry as { delete?: () => void } | null)?.delete?.(); } catch { /* already freed */ }
+ app = null;
+ }
+ clearUserComponents();
+ try {
+ await import(/* @vite-ignore */ `${bundleUrl}?v=${++reloadSeq}`);
+ } catch {
+ /* no project bundle — builtin-only */
+ }
+ await buildAppAndRun(lastInit);
+ post({ type: 'estella:play:ready' });
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ console.error('[play] reload failed', err);
+ post({ type: 'estella:play:error', message });
+ }
+}
+
/** Apply a (possibly dotted, e.g. "position.x") key to a cloned component data. */
function applyKey(target: Record<string, unknown>, key: string, value: unknown): void {
const parts = key.split('.');
@@ -139,6 +198,9 @@ window.addEventListener('message', (e: MessageEvent) => {
case 'estella:play:setPaused':
app?.setPaused(!!data.paused);
break;
+ case 'estella:play:reload':
+ void reload();
+ break;
case 'estella:play:query':
// Live introspection for the editor's "Game" inspect mode (UE5 PIE Details).
if (data.kind === 'snapshot') {
diff --git a/desktop/src/project/fsWatch.ts b/desktop/src/project/fsWatch.ts
index 3adb158eb..a52ffa91e 100644
--- a/desktop/src/project/fsWatch.ts
+++ b/desktop/src/project/fsWatch.ts
@@ -9,6 +9,7 @@
* refresh the asset registry + Content Browser, not just the editor's own ops.
*/
import { ProjectStore } from './ProjectStore';
+import { PlayRealm } from '../engine/PlayRealm';
const listeners = new Set<() => void>();
let version = 0;
@@ -31,11 +32,30 @@ export const fsRefresh = {
let inited = false;
let debounce: ReturnType<typeof setTimeout> | null = null;
let schemaDebounce: ReturnType<typeof setTimeout> | null = null;
+let scriptsDebounce: ReturnType<typeof setTimeout> | null = null;
// A project source module under src/ — a change here can alter a project
// component's field schema, so the inspector must re-extract (esbuild, ~100ms).
const isSourceModule = (p: string): boolean => /(^|[\\/])src[\\/].*\.(t|j)sx?$/.test(p);
+// A gameplay-logic edit while Play is live → rebuild the project bundle and
+// hot-reload the running realm in place (keeps wasm/GL/assets; ~100ms). A build
+// error keeps the realm on the last-good bundle rather than reloading a broken one.
+async function rebuildScriptsAndReloadPlay(): Promise<void> {
+ const buildScripts = window.estella?.project?.buildScripts;
+ if (!buildScripts) return;
+ try {
+ const res = await buildScripts();
+ if (!res.ok) {
+ console.warn('[fsWatch] project script rebuild failed; keeping running realm', res.errors);
+ return;
+ }
+ PlayRealm.reload();
+ } catch (e) {
+ console.warn('[fsWatch] project script rebuild threw', e);
+ }
+}
+
/** Subscribe to the main-process project watcher (call once at startup). */
export function initFsWatch(): void {
if (inited || !window.estella?.fs?.onChange) return;
@@ -53,6 +73,13 @@ export function initFsWatch(): void {
if (paths.some(isSourceModule)) {
if (schemaDebounce) clearTimeout(schemaDebounce);
schemaDebounce = setTimeout(() => void ProjectStore.refreshUserSchemas(), 250);
+
+ // Live gameplay-logic hot-reload — only while playing, so editing without
+ // Play is unaffected. Separate window: a bundle rebuild + in-place reload.
+ if (PlayRealm.getSnapshot().playing) {
+ if (scriptsDebounce) clearTimeout(scriptsDebounce);
+ scriptsDebounce = setTimeout(() => void rebuildScriptsAndReloadPlay(), 250);
+ }
}
});
}
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index 1c1d52606..f2f67e1eb 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -559,7 +559,7 @@ export class App {
requestAnimationFrame(this.mainLoop);
};
- quit(): void {
+ quit(options?: { keepRenderer?: boolean }): void {
this.running_ = false;
for (let i = this.installed_plugins_.length - 1; i >= 0; i--) {
@@ -586,13 +586,17 @@ export class App {
this.pipeline_ = null;
this.runner_ = null;
// Tear down the C++ engine context too: previously quit() only cleared
- // JS state and dropped the
- // module reference, so the EstellaContext was never shut down — it
- // leaked its GPU subsystems + WebGL context, and a later init silently
- // reused the stale (still-"initialized") singleton. shutdownRenderer is
- // null-safe (no-op if no renderer was initialized, e.g. headless).
- this.module_?.shutdownRenderer?.();
- this.module_ = null;
+ // JS state and dropped the module reference, so the EstellaContext was
+ // never shut down — it leaked its GPU subsystems + WebGL context, and a
+ // later init silently reused the stale (still-"initialized") singleton.
+ // shutdownRenderer is null-safe (no-op if no renderer was initialized).
+ // `keepRenderer` skips it: hot-reload rebuilds the App but reuses the live
+ // module + GL + renderer (EstellaContext::shutdown destroys the WebGL
+ // context), so only a full quit tears the renderer down.
+ if (!options?.keepRenderer) {
+ this.module_?.shutdownRenderer?.();
+ this.module_ = null;
+ }
}
// =========================================================================