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(aot): the shipped package is asked whether it is running its twins

esengine33278a14cf6d
diff --git a/.gitignore b/.gitignore
index d38aefc61..1de2c9361 100644
--- a/.gitignore
+++ b/.gitignore
@@ -163,3 +163,4 @@ native/ios/app.generated.yml
# The export pipeline bundles through a scratch dir inside its own tree (node
# resolution), and a crashed run leaves one behind for the source gates to judge.
pipeline/src/.build-*/
+.aot-verify/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aff67949b..6c6c3070c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -36,7 +36,11 @@ published separately; it ships inside the editor.
module, or rebuild the project.
Hosts embedding the runtime themselves can do the same through
- `App.useCompiledSystems` (`@experimental`).
+ `App.useCompiledSystems`, and `App.compiledSystems` reports which systems are
+ running compiled and how many twin calls have happened (both
+ `@experimental`). Installed and dispatched are separate questions: a module
+ can load and never be reached, and comparing results cannot tell, because the
+ closure a twin replaced computes the same answer.
- **A playable ad now fits the networks it is made for.** The single-file
transport inlined its engine as plain base64 — a +33% tax on a payload that is
diff --git a/package.json b/package.json
index af4c954d4..3c591ad87 100644
--- a/package.json
+++ b/package.json
@@ -29,6 +29,7 @@
"render-host": "node tools/render-host/build.mjs",
"verify:render": "node tools/verify-render.mjs",
"test": "vitest run --config vitest.engine.config.ts",
+ "verify:aot": "node pipeline/bin/estella.mjs export examples/ecs-basics --out .aot-verify && pnpm exec electron tools/launchers/headless-aot-verify.mjs .aot-verify",
"verify:cooked": "ESTELLA_COOK_FIXTURE=1 pnpm --filter @estella/pipeline exec vitest run tests/cooked-verify-fixture.test.ts && pnpm exec electron tools/launchers/headless-cooked-verify.mjs",
"verify:hotupdate": "ESTELLA_HOTUPDATE_FIXTURE=1 pnpm --filter @estella/pipeline exec vitest run tests/hotupdate-verify-fixture.test.ts && pnpm exec electron tools/launchers/headless-hotupdate-verify.mjs"
},
diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.ts
index 949aaa4c9..aa911b38f 100644
--- a/pipeline/src/runtime/gameHost.ts
+++ b/pipeline/src/runtime/gameHost.ts
@@ -138,6 +138,16 @@ async function boot(): Promise<void> {
compiledSystems(): number {
return app.compiledSystemCount;
},
+ /**
+ * Which systems this package is running compiled, and how many twin calls
+ * have happened. Installed and dispatched are separate questions, and a
+ * driver comparing positions can answer neither — the closure a twin
+ * replaced moves the entity to the same place.
+ */
+ compiled(): { installed: readonly string[]; calls: number } {
+ return app.compiledSystems;
+ },
+
/**
* Where things are, for a driver that has to play rather than just look.
* Capture answers "did it draw"; walking a route needs "am I there yet",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index bd3de97a9..b098eb3d7 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -539,6 +539,7 @@ addSystemSet: (set: SystemSet) => App
addSystemSetToSchedule: (schedule: Schedule, set: SystemSet) => App
addSystemToSchedule: (schedule: Schedule, system: SystemDef, options?: { runBefore?: string[]; runAfter?: string[]; runIf?: RunCondition; }) => App
compiledSystemCount: number
+compiledSystems: { readonly installed: readonly string[]; readonly calls: number; }
enableStats: () => App
getEntityCount: () => number
getFixedTimestep: () => number
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index f362137c8..768b5bbf5 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -539,6 +539,7 @@ addSystemSet: (set: SystemSet) => App
addSystemSetToSchedule: (schedule: Schedule, set: SystemSet) => App
addSystemToSchedule: (schedule: Schedule, system: SystemDef, options?: { runBefore?: string[]; runAfter?: string[]; runIf?: RunCondition; }) => App
compiledSystemCount: number
+compiledSystems: { readonly installed: readonly string[]; readonly calls: number; }
enableStats: () => App
getEntityCount: () => number
getFixedTimestep: () => number
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 87a323a0a..161a2bb07 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -534,6 +534,7 @@ addSystemSet: (set: SystemSet) => App
addSystemSetToSchedule: (schedule: Schedule, set: SystemSet) => App
addSystemToSchedule: (schedule: Schedule, system: SystemDef, options?: { runBefore?: string[]; runAfter?: string[]; runIf?: RunCondition; }) => App
compiledSystemCount: number
+compiledSystems: { readonly installed: readonly string[]; readonly calls: number; }
enableStats: () => App
getEntityCount: () => number
getFixedTimestep: () => number
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 012fd1c21..1ab62ed45 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -534,6 +534,7 @@ addSystemSet: (set: SystemSet) => App
addSystemSetToSchedule: (schedule: Schedule, set: SystemSet) => App
addSystemToSchedule: (schedule: Schedule, system: SystemDef, options?: { runBefore?: string[]; runAfter?: string[]; runIf?: RunCondition; }) => App
compiledSystemCount: number
+compiledSystems: { readonly installed: readonly string[]; readonly calls: number; }
enableStats: () => App
getEntityCount: () => number
getFixedTimestep: () => number
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 562118e06..e28602be8 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -534,6 +534,7 @@ addSystemSet: (set: SystemSet) => App
addSystemSetToSchedule: (schedule: Schedule, set: SystemSet) => App
addSystemToSchedule: (schedule: Schedule, system: SystemDef, options?: { runBefore?: string[]; runAfter?: string[]; runIf?: RunCondition; }) => App
compiledSystemCount: number
+compiledSystems: { readonly installed: readonly string[]; readonly calls: number; }
enableStats: () => App
getEntityCount: () => number
getFixedTimestep: () => number
diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.ts
index ec02f8493..7c3d97086 100644
--- a/sdk/src/app/app.ts
+++ b/sdk/src/app/app.ts
@@ -644,6 +644,21 @@ export class App {
/** Held until there is a runner to give them to: one is made on the first frame. */
private aot_: AotRuntime | null = null;
+ /**
+ * Which systems this App is running compiled, and how many twin calls have
+ * happened. `installed` without `calls` rising means the module loaded and
+ * nothing dispatched to it — which no differential can report, because the
+ * closure it replaced computes the same answer.
+ *
+ * @experimental
+ */
+ get compiledSystems(): { readonly installed: readonly string[]; readonly calls: number } {
+ return {
+ installed: this.aot_?.systems.names() ?? [],
+ calls: this.aot_?.systems.calls ?? 0,
+ };
+ }
+
// =========================================================================
// Configuration
// =========================================================================
diff --git a/sdk/src/ecs/aot/AotDispatch.ts b/sdk/src/ecs/aot/AotDispatch.ts
index 02deebc76..5339d735b 100644
--- a/sdk/src/ecs/aot/AotDispatch.ts
+++ b/sdk/src/ecs/aot/AotDispatch.ts
@@ -104,9 +104,10 @@ export class AotDispatch {
const resources = plan.resources.map((name) => this.runtime.addresses.resourceAt(name) ?? 0);
this.runtime.ctx.build(plan.scratch, plan.rowWords, plan.offsets, plan.counts, resources);
twin.call(this.runtime.ctx.address);
+ this.runtime.systems.noteCall();
for (const cmd of this.runtime.ctx.commands()) {
- // Only despawn is in the v1 record set (REARCH_AOT_ABI.md §2.3).
+ // Only despawn is in the v1 record set.
if (cmd.kind === CMD_DESPAWN) this.world.despawn(cmd.a as unknown as Entity);
}
this.markChanged_(plan);
diff --git a/sdk/src/ecs/aot/AotSystems.ts b/sdk/src/ecs/aot/AotSystems.ts
index dc38f9a47..1ac63532d 100644
--- a/sdk/src/ecs/aot/AotSystems.ts
+++ b/sdk/src/ecs/aot/AotSystems.ts
@@ -51,11 +51,31 @@ export interface AotTwin {
*/
export class AotSystems {
private readonly byName = new Map<string, AotTwin>();
+ private calls_ = 0;
get size(): number {
return this.byName.size;
}
+ /** The systems a module supplied twins for. Install is all-or-nothing. */
+ names(): readonly string[] {
+ return [...this.byName.keys()];
+ }
+
+ /**
+ * How many times a twin has been called. Installed is not the same question
+ * as ran: a differential cannot tell them apart, because the closure that
+ * would have run produces the same numbers.
+ */
+ get calls(): number {
+ return this.calls_;
+ }
+
+ /** Counted by the runner, which is the only thing that dispatches. */
+ noteCall(): void {
+ this.calls_++;
+ }
+
/**
* Take a built module, after checking what it baked in against what is here.
*
diff --git a/sdk/tests/aot-app.test.ts b/sdk/tests/aot-app.test.ts
index d9fbfdb5c..a41d5054f 100644
--- a/sdk/tests/aot-app.test.ts
+++ b/sdk/tests/aot-app.test.ts
@@ -106,6 +106,17 @@ describe('an App told to run its compiled twins', () => {
expect(alphas(app, Fade, entities)).toEqual(entities.map(() => FADE_PROBE_ALPHA));
});
+ it.skipIf(!EMCC)('and says which systems it runs compiled, and how often it dispatched', async () => {
+ const { app, Fade } = fadeApp();
+ expect(app.compiledSystems).toEqual({ installed: [], calls: 0 });
+ await app.useCompiledSystems({ host: new FakeEngine(), manifest: fadeManifest(), wasm: buildFadeModule(EMCC!) });
+ seed(app, Fade);
+ for (let f = 0; f < 3; f++) await app.tick(1 / 60);
+ // Installed is one question and dispatched is another: a module can load
+ // and never be reached, and the numbers would not say so.
+ expect(app.compiledSystems).toEqual({ installed: ['Fade'], calls: 3 });
+ });
+
it.skipIf(!EMCC)('refuses a module built for other shapes, and the App keeps interpreting', async () => {
const { app, Fade } = fadeApp();
await expect(app.useCompiledSystems({
diff --git a/tools/launchers/headless-aot-verify.mjs b/tools/launchers/headless-aot-verify.mjs
new file mode 100644
index 000000000..7b73dc3f2
--- /dev/null
+++ b/tools/launchers/headless-aot-verify.mjs
@@ -0,0 +1,99 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Drives a REAL exported package and asks whether it is running the
+ * systems it promised to compile.
+ *
+ * Every other AOT gate substitutes something: a synthetic project, a
+ * hand-written system, or a host built for the test. This one exports
+ * examples/ecs-basics through the CLI — the project that carries the
+ * corpus's only `@compiled` marker — serves the package, boots it, and
+ * reads the game host's own hook.
+ *
+ * It asks DISPATCHED, not installed. A module can load and never be
+ * reached, and no comparison of positions can tell: the closure a twin
+ * replaced moves the entity to the same place.
+ *
+ * pnpm exec electron tools/launchers/headless-aot-verify.mjs <packageDir>
+ */
+import { app, BrowserWindow } from 'electron';
+import http from 'node:http';
+import { readFile } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+
+const PACKAGE = path.resolve(process.argv[process.argv.length - 1]);
+const W = 256, H = 256;
+
+app.commandLine.appendSwitch('enable-unsafe-swiftshader');
+process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true';
+
+const MIME = {
+ '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
+ '.css': 'text/css', '.json': 'application/json', '.esscene': 'application/json',
+ '.wasm': 'application/wasm', '.png': 'image/png', '.ktx2': 'application/octet-stream',
+};
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+function serve(dir) {
+ const server = http.createServer(async (req, res) => {
+ try {
+ const rel = decodeURIComponent(new URL(req.url, 'http://x').pathname).replace(/^\/+/, '') || 'index.html';
+ const abs = path.join(dir, rel);
+ if (!abs.startsWith(dir)) { res.writeHead(403).end(); return; }
+ const bytes = await readFile(abs);
+ res.writeHead(200, { 'content-type': MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream' });
+ res.end(bytes);
+ } catch { res.writeHead(404).end('not found'); }
+ });
+ return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server)));
+}
+
+app.whenReady().then(async () => {
+ let server;
+ let failed = true;
+ const diag = [];
+ try {
+ if (!existsSync(path.join(PACKAGE, 'index.html'))) throw new Error(`no package at ${PACKAGE}`);
+ // The two files the export writes for this. Absent means the export did not
+ // compile anything, which makes everything below vacuous.
+ for (const f of ['systems.wasm', 'systems.json']) {
+ if (!existsSync(path.join(PACKAGE, f))) throw new Error(`the package carries no ${f}`);
+ }
+
+ server = await serve(PACKAGE);
+ const url = `http://127.0.0.1:${server.address().port}/index.html?headless=1`;
+ const win = new BrowserWindow({ show: false, width: W, height: H });
+ win.webContents.on('console-message', (_e, _l, m) => {
+ if (/error|fail|refus|exception|wasm/i.test(m)) diag.push(String(m).slice(0, 200));
+ });
+ await win.loadURL(url);
+
+ const exec = (code) => win.webContents.executeJavaScript(code, true);
+ let ready = false;
+ for (let i = 0; i < 150 && !ready; i++) {
+ ready = await exec('!!(window.__estellaCooked && window.__estellaCooked.compiled)').catch(() => false);
+ if (!ready) await sleep(100);
+ }
+ if (!ready) throw new Error('the game host hook never appeared (boot failed?)');
+ await sleep(1500);
+
+ const got = await exec('window.__estellaCooked.compiled()');
+ const installedOk = got.installed.includes('MoveSystem');
+ // Dispatched, and repeatedly: one call could be a startup pass.
+ const dispatchedOk = got.calls >= 10;
+ const ok = installedOk && dispatchedOk;
+ console.log(`\n[verify:aot] ${ok ? 'PASS' : 'FAIL'} — installed ${JSON.stringify(got.installed)}, ${got.calls} twin call(s)`);
+ console.log('DRIVE_RESULT ' + JSON.stringify({ ...got, installedOk, dispatchedOk, diag: diag.slice(0, 6) }));
+ failed = !ok;
+ } catch (e) {
+ console.log('\n[verify:aot] FAIL — ' + (e?.message ?? e));
+ console.log('DRIVE_RESULT ' + JSON.stringify({ error: String(e?.message ?? e), diag: diag.slice(0, 6) }));
+ failed = true;
+ } finally {
+ try { server?.close(); } catch { /* ignore */ }
+ // app.exit, not exitCode: Electron reports 0 whatever exitCode says.
+ app.exit(failed ? 1 : 0);
+ }
+});