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): census the edit realm across Play/Stop, GL objects included

esengine8b56fd064bcf
diff --git a/desktop/package.json b/desktop/package.json
index 0ecb79a7b..00669d246 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -68,7 +68,8 @@
"verify:render:trail": "vite build && ESTELLA_VERIFY_PLAY=1 ESTELLA_VERIFY_SCENE=/scenes/trail.esscene ESTELLA_VERIFY_MANIFEST=/scenes/trail.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_TRAIL='{\"from\":[-200,0],\"to\":[200,0],\"steps\":20}' ESTELLA_VERIFY_EXPECT='[{\"x\":0.80,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":50},{\"x\":0.5,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":50},{\"x\":0.25,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":60},{\"x\":0.5,\"y\":0.15,\"rgb\":[0,0,0],\"tol\":30}]' electron scripts/headless-verify.mjs",
"verify:render:postprocess:lut": "vite build && ESTELLA_VERIFY_PLAY=1 ESTELLA_VERIFY_SCENE=/scenes/lut-grade.esscene ESTELLA_VERIFY_MANIFEST=/scenes/lut-grade.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=10 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.292,\\\"y\\\":0.5,\\\"rgb\\\":[0,0,255],\\\"tol\\\":40},{\\\"x\\\":0.708,\\\"y\\\":0.5,\\\"rgb\\\":[255,0,0],\\\"tol\\\":40}]\" electron scripts/headless-verify.mjs",
"verify:render:depth": "vite build && ESTELLA_VERIFY_SCENE=/scenes/depth-layers.esscene ESTELLA_VERIFY_MANIFEST=/scenes/depth-layers.textures.json ESTELLA_VERIFY_DEPTH_LAYERS=6 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.573,\\\"y\\\":0.5,\\\"rgb\\\":[255,0,0],\\\"tol\\\":60}]\" electron scripts/headless-verify.mjs",
- "verify:render:depth:off": "vite build && ESTELLA_VERIFY_SCENE=/scenes/depth-layers.esscene ESTELLA_VERIFY_MANIFEST=/scenes/depth-layers.textures.json ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.573,\\\"y\\\":0.5,\\\"rgb\\\":[0,0,255],\\\"tol\\\":60}]\" electron scripts/headless-verify.mjs"
+ "verify:render:depth:off": "vite build && ESTELLA_VERIFY_SCENE=/scenes/depth-layers.esscene ESTELLA_VERIFY_MANIFEST=/scenes/depth-layers.textures.json ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.573,\\\"y\\\":0.5,\\\"rgb\\\":[0,0,255],\\\"tol\\\":60}]\" electron scripts/headless-verify.mjs",
+ "verify:soak": "vite build && node scripts/editor-checks/run.mjs soak"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.115.0",
diff --git a/desktop/scripts/editor-checks/soak.mjs b/desktop/scripts/editor-checks/soak.mjs
new file mode 100644
index 000000000..b0b39746f
--- /dev/null
+++ b/desktop/scripts/editor-checks/soak.mjs
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file soak — Play, Stop, reload, repeat, and demand the editor gives it back.
+ *
+ * The headless soak (sdk/tests/soak) churns entities and prefabs, and cannot
+ * reach the half that actually ends a session: there is no GL context in Node,
+ * so no textures, no shader programs, no render targets. Those are what the
+ * complaint is about — Play/Stop forty times and the editor crawls; hot-reload
+ * a shader all afternoon and the GPU is holding 1.8 GB.
+ *
+ * So this drives the REAL editor and censuses the EDIT realm between cycles.
+ * The edit realm is the right subject: the play realm is an out-of-process frame
+ * that Stop destroys, taking its counters with it, while this window and its GL
+ * context live for the whole session and are where a leak accumulates.
+ *
+ * SOAK_CYCLES=50 node scripts/editor-checks/run.mjs soak
+ */
+import path from 'node:path';
+import { cp } from 'node:fs/promises';
+import { makeProject, checker, DESKTOP } from '../lib/editorDriver.mjs';
+import { analyzeCensusSeries, formatCensusReport } from '../lib/censusJudge.mjs';
+
+const EXAMPLE = path.resolve(DESKTOP, '..', 'examples', 'sprite-rendering');
+const CYCLES = Number(process.env.SOAK_CYCLES ?? 12);
+
+export const name = 'soak';
+export const describes = 'Play/Stop and hot reload return every conserved counter, GL objects included';
+
+/** One census, as the judge wants it. */
+async function census(ed) {
+ const raw = await ed.json('resource_census', {}, 60000);
+ return {
+ atMs: 0,
+ entries: new Map((raw?.entries ?? []).map((e) => [e.key, e])),
+ failedProbes: raw?.failedProbes ?? [],
+ };
+}
+
+export async function run(ed) {
+ const root = await makeProject({});
+ await cp(EXAMPLE, root, { recursive: true });
+ const check = checker();
+
+ await ed.open(root, 'assets/scenes/main.esscene');
+
+ const first = await census(ed);
+ if (!check(first.entries.size > 0, 'resource_census came back empty — nothing was measured')) {
+ return check.failures;
+ }
+ // The GL counters are the reason this check exists at all. Absent means the
+ // engine build predates them or no device booted; either way the run below
+ // would pass while watching none of what it claims to watch.
+ const glKeys = [...first.entries.keys()].filter((k) => k.startsWith('render.gl.'));
+ if (!check(glKeys.length > 0, `no render.gl.* counters — GL was not measured (saw: ${[...first.entries.keys()].join(', ')})`)) {
+ return check.failures;
+ }
+ check(first.failedProbes.length === 0, `probes failed: ${first.failedProbes.join('; ')}`);
+
+ const samples = [];
+ for (let cycle = 0; cycle < CYCLES; cycle++) {
+ await ed.call('toggle_play', {}, 120000);
+ let ready = false;
+ for (let i = 0; i < 40 && !ready; i++) {
+ ready = (await ed.json('get_play_state', {}))?.ready === true;
+ if (!ready) await ed.sleep(250);
+ }
+ if (!check(ready, `cycle ${cycle}: the play realm never reported ready`)) return check.failures;
+ await ed.call('step', { frames: 10, dt: 1 / 60 }, 60000);
+
+ await ed.call('toggle_play', {}, 120000);
+ let stopped = false;
+ for (let i = 0; i < 40 && !stopped; i++) {
+ stopped = (await ed.json('get_play_state', {}))?.playing === false;
+ if (!stopped) await ed.sleep(250);
+ }
+ if (!check(stopped, `cycle ${cycle}: play never stopped`)) return check.failures;
+
+ // A rescan every cycle: the path that releases a GL texture before uploading
+ // its replacement. Whether it re-uploaded is not assumed — render.gl.textures
+ // is in the census, so a rescan that did nothing shows as a flat line.
+ await ed.call('refresh_assets', {}, 60000);
+ await ed.call('step', { frames: 4, dt: 1 / 60 }, 60000);
+
+ samples.push(await census(ed));
+ }
+
+ const report = analyzeCensusSeries(samples, { projectCycles: 10_000 });
+ if (process.env.SOAK_REPORT) console.log(formatCensusReport(report));
+ check(report.failedProbes.length === 0, `probes stopped answering: ${report.failedProbes.join('; ')}`);
+ for (const leak of report.leaks) check(false, `${leak.key} — ${leak.reason}`);
+ if (report.leaks.length > 0) console.error(formatCensusReport(report));
+
+ return check.failures;
+}
diff --git a/desktop/scripts/lib/censusJudge.mjs b/desktop/scripts/lib/censusJudge.mjs
new file mode 100644
index 000000000..568acc3d5
--- /dev/null
+++ b/desktop/scripts/lib/censusJudge.mjs
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file censusJudge — the engine's own census judge, reachable from a script.
+ *
+ * Re-export, not a reimplementation. The tiers, the confidence bound and the
+ * staircase rule are subtle enough that a second copy here would drift from the
+ * one the headless soak uses, and then the two suites would disagree about what
+ * a leak is — which is worse than having only one of them.
+ */
+export { analyzeCensusSeries, formatCensusReport, formatCensusDiff, diffCensus } from 'esengine';
diff --git a/desktop/shared/toolCatalog.mjs b/desktop/shared/toolCatalog.mjs
index 708a9040d..88000b6e4 100644
--- a/desktop/shared/toolCatalog.mjs
+++ b/desktop/shared/toolCatalog.mjs
@@ -207,6 +207,11 @@ export const TOOLS = [
{ name: 'get_stats',
description: 'Live counts: entity count + last frame draw calls (cheap render evidence).',
schema: obj({}), method: 'getStats', args: () => [] },
+ { name: 'resource_census',
+ description: 'How many of everything the EDITOR realm is holding right now: entities, GL buffers/textures/programs, listeners, asset refs, physics bodies, both heaps. '
+ + 'Take one before a Play/Stop (or a hot reload, or a scene load) and one after: every counter tagged `conserved` must come back to the same number. '
+ + 'This is the door for "the editor got slower after an hour" — the question no screenshot answers.',
+ schema: obj({}), method: 'census', args: () => [], root: 'editor' },
{ name: 'get_subsystems',
description: 'Lifecycle + liveness of every engine subsystem (physics, audio, …): phase and activity.',
schema: obj({}), method: 'getSubsystems', args: () => [] },
diff --git a/desktop/src/engine/EngineHost.ts b/desktop/src/engine/EngineHost.ts
index b5862f734..d40bea332 100644
--- a/desktop/src/engine/EngineHost.ts
+++ b/desktop/src/engine/EngineHost.ts
@@ -104,6 +104,10 @@ class EngineHostImpl {
getResource<T>(resource: ResourceDef<T>): T | undefined {
return this.app_?.getResource(resource);
}
+ /** The edit realm's App, for whole-app diagnostics (the resource census). */
+ get app(): App | null {
+ return this.app_;
+ }
/** Cap the edit-realm engine loop (0 = uncapped). Survives reboot. */
setTargetFrameRate(fps: number): void {
this.targetFps_ = fps;
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index 5da7e37dd..30153923b 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -50,7 +50,7 @@ import { EditorControlSurface } from './engine/EditorSession';
import { runContributedTool } from './plugins/agentTools';
import { SceneModel } from './engine/SceneModel';
import { EngineHost } from './engine/EngineHost';
-import { Particle, getComponent } from 'esengine';
+import { Particle, getComponent, takeCensus } from 'esengine';
import { actionNames, actionParams, conditionNames } from '@/ai/actionCatalog';
import { applyFxPreview, initFxPreviewEditRestart } from './engine/fxPreview';
import { commands } from './commands/registry';
@@ -314,6 +314,16 @@ function buildEditorAutomation(): unknown {
tickEngine: async (n: number, dt = 1 / 60) => {
for (let i = 0; i < n; i++) await EngineHost.tick(dt);
},
+ /**
+ * How many of everything the EDIT realm holds — entities, GL objects,
+ * listeners, both heaps. This realm is where a Play/Stop leak lands: the play
+ * realm is an OOPIF that Stop destroys, taking its counters with it. A list,
+ * not a Map, so it survives the probe's JSON round trip.
+ */
+ census: () => {
+ const c = takeCensus({ app: EngineHost.app ?? undefined });
+ return { entries: [...c.entries.values()], failedProbes: c.failedProbes };
+ },
/** Live particle count of a SOURCE entity's emitter (edit-preview probes). */
particleAlive: (id: number) => {
const rt = SceneModel.runtimeFor(id);
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index 405e103cd..b4efcfeeb 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, Net, MessagePortTransport, Assets, Ads, createMockAdProvider, Leaderboard, createLocalLeaderboard, registerPackagedSideModules, Input, inputEventCallbacks, isEntityVisible, setEntityVisible, hasVisibility } from 'esengine';
+import { createWebApp, setEditorMode, setPlayMode, initPlayRealmRuntime, getComponent, clearUserComponents, getUserComponentFingerprint, probeRegistrations, Net, MessagePortTransport, Assets, Ads, createMockAdProvider, Leaderboard, createLocalLeaderboard, registerPackagedSideModules, Input, inputEventCallbacks, isEntityVisible, setEntityVisible, hasVisibility, takeCensus } from 'esengine';
import type { App, ESEngineModule, SceneData } from 'esengine';
import { PLAY_PROTOCOL_VERSION } from './engine/playProtocol';
import type { PlayOutbound, PlayInbound, LiveVisibility } from './engine/playProtocol';
@@ -458,6 +458,20 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
touchMove: (id: number, x: number, y: number) => injected.onTouchMove?.(id, x, y),
touchEnd: (id: number) => injected.onTouchEnd?.(id),
},
+ /**
+ * How many of everything is alive right now, as a plain object.
+ *
+ * This realm is behind an out-of-process frame, so a probe is the only way in
+ * from outside. Entries are flattened because a Map does not survive the JSON
+ * round trip. For leaks that OUTLIVE Stop, census the edit realm instead.
+ */
+ census: () => {
+ const c = takeCensus({ app: app ?? undefined });
+ return {
+ entries: [...c.entries.values()],
+ failedProbes: c.failedProbes,
+ };
+ },
};
startFrameHeartbeat();