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(render-host): the engine verifies its own renderer

esengine121ee8bbdca4
diff --git a/desktop/scripts/editor-mcp-host.mjs b/desktop/scripts/editor-mcp-host.mjs
index 63506d1c7..3eff01791 100644
--- a/desktop/scripts/editor-mcp-host.mjs
+++ b/desktop/scripts/editor-mcp-host.mjs
@@ -23,7 +23,7 @@ import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createExecEndpoint } from '../shared/execEndpoint.mjs';
-import { onRendererConsole } from './rendererConsole.mjs';
+import { onRendererConsole } from '../../tools/lib/rendererConsole.mjs';
const DIST = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'dist');
const TOKEN = process.env.ESTELLA_MCP_TOKEN;
diff --git a/desktop/scripts/engine-parity.mjs b/desktop/scripts/engine-parity.mjs
index 19e7934f2..21cbbab17 100644
--- a/desktop/scripts/engine-parity.mjs
+++ b/desktop/scripts/engine-parity.mjs
@@ -19,7 +19,7 @@ import os from 'node:os';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { onRendererConsole } from './rendererConsole.mjs';
+import { onRendererConsole } from '../../tools/lib/rendererConsole.mjs';
try {
os.setPriority(os.constants.priority.PRIORITY_BELOW_NORMAL);
diff --git a/desktop/scripts/headless-cooked-verify.mjs b/desktop/scripts/headless-cooked-verify.mjs
index 9a92e0aee..3285e4e2f 100644
--- a/desktop/scripts/headless-cooked-verify.mjs
+++ b/desktop/scripts/headless-cooked-verify.mjs
@@ -14,7 +14,7 @@ import http from 'node:http';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { onRendererConsole } from './rendererConsole.mjs';
+import { onRendererConsole } from '../../tools/lib/rendererConsole.mjs';
const COOKED = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '.cooked-verify');
const W = 256, H = 256;
diff --git a/desktop/scripts/headless-hotupdate-verify.mjs b/desktop/scripts/headless-hotupdate-verify.mjs
index 7d5f2a92d..923ee0d61 100644
--- a/desktop/scripts/headless-hotupdate-verify.mjs
+++ b/desktop/scripts/headless-hotupdate-verify.mjs
@@ -19,7 +19,7 @@ import http from 'node:http';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { onRendererConsole } from './rendererConsole.mjs';
+import { onRendererConsole } from '../../tools/lib/rendererConsole.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '.hotupdate-verify');
const BUILD = path.join(ROOT, 'build');
diff --git a/desktop/scripts/launch-export.mjs b/desktop/scripts/launch-export.mjs
index 1f10c90e6..1b878015a 100644
--- a/desktop/scripts/launch-export.mjs
+++ b/desktop/scripts/launch-export.mjs
@@ -39,7 +39,7 @@ import { readFile, writeFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { onRendererConsole } from './rendererConsole.mjs';
+import { onRendererConsole } from '../../tools/lib/rendererConsole.mjs';
import { inputScript } from './inputScript.mjs';
// Headless / GPU-less (CI) WebGL2 falls back to SwiftShader; harmless with a GPU.
diff --git a/desktop/scripts/launch-minigame.mjs b/desktop/scripts/launch-minigame.mjs
index 7f4f5e7d2..fde2bb393 100644
--- a/desktop/scripts/launch-minigame.mjs
+++ b/desktop/scripts/launch-minigame.mjs
@@ -23,7 +23,7 @@ import { readFile, writeFile } from 'node:fs/promises';
import { existsSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { onRendererConsole } from './rendererConsole.mjs';
+import { onRendererConsole } from '../../tools/lib/rendererConsole.mjs';
import { HOST_PAGE } from './minigameHost.mjs';
import { inputScript } from './inputScript.mjs';
diff --git a/desktop/scripts/play-through.mjs b/desktop/scripts/play-through.mjs
index 47ebfde36..ef8fe0b42 100644
--- a/desktop/scripts/play-through.mjs
+++ b/desktop/scripts/play-through.mjs
@@ -37,7 +37,7 @@ import http from 'node:http';
import { readFile, writeFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
-import { onRendererConsole } from './rendererConsole.mjs';
+import { onRendererConsole } from '../../tools/lib/rendererConsole.mjs';
app.commandLine.appendSwitch('force-color-profile', 'srgb');
diff --git a/desktop/scripts/webgpu-bringup.mjs b/desktop/scripts/webgpu-bringup.mjs
index 4dc2aa9f2..a8cdc70ca 100644
--- a/desktop/scripts/webgpu-bringup.mjs
+++ b/desktop/scripts/webgpu-bringup.mjs
@@ -20,7 +20,7 @@ import os from 'node:os';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { onRendererConsole } from './rendererConsole.mjs';
+import { onRendererConsole } from '../../tools/lib/rendererConsole.mjs';
try {
os.setPriority(os.constants.priority.PRIORITY_BELOW_NORMAL);
diff --git a/package.json b/package.json
index 56b099a17..93bf7a8f5 100644
--- a/package.json
+++ b/package.json
@@ -1,5 +1,5 @@
{
- "name": "esengine",
+ "name": "estella",
"version": "0.55.0",
"private": true,
"type": "module",
@@ -25,7 +25,9 @@
"prepare": "git config core.hooksPath .githooks || true",
"soak": "pnpm --filter ./sdk exec vitest run tests/soak",
"torture": "pnpm --filter ./sdk exec vitest run tests/torture",
- "gate": "node tools/check-release-gate.mjs --report"
+ "gate": "node tools/check-release-gate.mjs --report",
+ "render-host": "node tools/render-host/build.mjs",
+ "verify:render": "node tools/verify-render.mjs"
},
"dependencies": {
"chalk": "^5.3.0",
@@ -43,6 +45,8 @@
]
},
"devDependencies": {
+ "electron": "^42.4.1",
+ "esbuild": "^0.27.0",
"madge": "^8.0.0"
}
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a2efc2f02..cff447417 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -21,6 +21,12 @@ importers:
specifier: ^8.0.0
version: 8.2.0
devDependencies:
+ electron:
+ specifier: ^42.4.1
+ version: 42.4.1
+ esbuild:
+ specifier: ^0.27.0
+ version: 0.27.7
madge:
specifier: ^8.0.0
version: 8.0.0([email protected])
diff --git a/desktop/scripts/rendererConsole.mjs b/tools/lib/rendererConsole.mjs
similarity index 100%
rename from desktop/scripts/rendererConsole.mjs
rename to tools/lib/rendererConsole.mjs
diff --git a/tools/render-host/build.mjs b/tools/render-host/build.mjs
new file mode 100644
index 000000000..1f67584bd
--- /dev/null
+++ b/tools/render-host/build.mjs
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file build.mjs — bundles the engine's render host into build/render-host/.
+ *
+ * Self-contained on purpose: the host directory is what a runner serves, so the
+ * wasm glue is copied in beside the bundle rather than resolved out of the
+ * engine tree at request time. One root to serve, one thing to delete.
+ *
+ * node tools/render-host/build.mjs
+ */
+import { build } from 'esbuild';
+import { cp, mkdir, rm, access } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const ROOT = path.resolve(HERE, '..', '..');
+const OUT = path.join(ROOT, 'build', 'render-host');
+const WASM_SRC = path.join(ROOT, 'build', 'wasm', 'web');
+
+const exists = async (p) => access(p).then(() => true, () => false);
+
+if (!(await exists(path.join(ROOT, 'sdk', 'dist', 'index.js')))) {
+ console.error('render-host: the SDK is not built — run `pnpm --filter ./sdk build` first.');
+ process.exit(2);
+}
+if (!(await exists(path.join(WASM_SRC, 'esengine.wasm')))) {
+ console.error('render-host: the engine wasm is not built — run `node build-tools/cli.js build -t web` first.');
+ process.exit(2);
+}
+
+await rm(OUT, { recursive: true, force: true });
+await mkdir(OUT, { recursive: true });
+
+await build({
+ entryPoints: [path.join(HERE, 'host.ts')],
+ outfile: path.join(OUT, 'host.js'),
+ bundle: true,
+ format: 'esm',
+ target: 'es2022',
+ platform: 'browser',
+ sourcemap: true,
+ logLevel: 'info',
+ // The glue is fetched from the served origin at runtime (it is a sibling of
+ // the .wasm it locates), so it must not be resolved at bundle time.
+ external: ['/wasm/*'],
+ // The repo root's package.json is also named "esengine", so a bare specifier
+ // resolves to the root rather than to the SDK. Point at the built entries the
+ // SDK's own exports name.
+ alias: {
+ esengine: path.join(ROOT, 'sdk', 'dist', 'index.js'),
+ 'esengine/spine': path.join(ROOT, 'sdk', 'dist', 'spine', 'index.js'),
+ 'esengine/dragonbones': path.join(ROOT, 'sdk', 'dist', 'dragonbones', 'index.js'),
+ 'esengine/wasm': path.join(ROOT, 'sdk', 'dist', 'wasm.js'),
+ },
+});
+
+await cp(path.join(HERE, 'index.html'), path.join(OUT, 'index.html'));
+await cp(WASM_SRC, path.join(OUT, 'wasm'), { recursive: true });
+console.log(`render-host: built into ${path.relative(ROOT, OUT)}`);
diff --git a/tools/render-host/host.ts b/tools/render-host/host.ts
new file mode 100644
index 000000000..760634d81
--- /dev/null
+++ b/tools/render-host/host.ts
@@ -0,0 +1,509 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file host.ts — the engine's own headless render host.
+ *
+ * The pixel gates assert about the RENDERER, so their host is the engine's: an
+ * offscreen canvas, no UI, no self-driving loop, and frames advanced by hand so
+ * a capture is reproducible. Everything here is a call into the shipped SDK —
+ * there is no authoring model between the scene file and the World.
+ *
+ * It publishes `window.__estellaHeadless`, the same shape the editor's host
+ * does, so one runner drives either. Doors that only exist inside an editor
+ * (the reference grid, hit-testing, the editor eye, material/mesh preview
+ * renders) are absent rather than faked: a gate that needs one names the editor
+ * host, and asking for one here fails with which door and why.
+ */
+import {
+ createWebApp, setEditorMode, setPlayMode, Assets, acquireWebGPUDevice,
+ loadSceneData, Renderer, instantiatePrefab, writeFieldPath, Transform, Name,
+ getComponent, DeviceStatus, getDeviceStatus, getDeviceLostReport, recoverDevice,
+ finishDeviceRecovery, getContextLossGuardInfo, decodeImagePixels,
+} from 'esengine';
+import type { App, SceneData, PrefabData, RenderSurfaceSource } from 'esengine';
+import type { ESEngineModule } from 'esengine/wasm';
+import { loadSpineSceneEntities, SpinePlugin } from 'esengine/spine';
+import type { RuntimeAssetSource } from 'esengine/spine';
+import { loadDragonBonesSceneEntities, DragonBonesPlugin } from 'esengine/dragonbones';
+
+const UUID_PREFIX = '@uuid:';
+
+const params = new URLSearchParams(location.search);
+const width = Number(params.get('w')) || 1280;
+const height = Number(params.get('h')) || 720;
+const backend = params.get('backend') === 'webgpu' ? 'webgpu' : 'webgl2';
+const colorSpace = params.get('colorSpace') === 'linear' ? 'linear' : undefined;
+const seedParam = params.get('seed');
+const randomSeed = seedParam !== null && Number.isFinite(Number(seedParam)) ? Number(seedParam) : undefined;
+const depthLayers = Number(params.get('depthLayers')) || undefined;
+
+let app: App | null = null;
+let module: ESEngineModule | null = null;
+let canvas: HTMLCanvasElement | null = null;
+// A driver addresses entities by the id the SCENE FILE gives them, not by the
+// World entity loadSceneData minted for it — that is the id an authored gate can
+// write down. loadSceneData hands back exactly that mapping.
+let sceneRaw: SceneData | null = null;
+let sourceToEntity = new Map<number, number>();
+
+/** A door this host does not have. Naming it beats a silent no-op that renders a wrong frame. */
+function editorOnly(door: string): never {
+ throw new Error(
+ `${door} is an editor door — this is the engine's render host, which has no editor session. `
+ + 'Run the gate that needs it against the editor host (--host editor).',
+ );
+}
+
+async function boot(): Promise<void> {
+ canvas = document.createElement('canvas');
+ canvas.id = 'canvas';
+ canvas.width = width;
+ canvas.height = height;
+
+ const glueUrl = `${location.origin}/wasm/esengine.js`;
+ const { default: createModule } = (await import(/* @vite-ignore */ glueUrl)) as {
+ default: (options?: Record<string, unknown>) => Promise<ESEngineModule>;
+ };
+
+ const moduleArg: Record<string, unknown> = {
+ canvas,
+ locateFile: (p: string) => `/wasm/${p}`,
+ print: (t: string) => console.log('[wasm]', t),
+ printErr: (t: string) => console.warn('[wasm]', t),
+ };
+ if (backend === 'webgpu') {
+ // The device has to exist before the module instantiates — the wasm side
+ // reads it synchronously. The error listener is what makes an invalid
+ // draw visible; without one Dawn drops it in silence, which reads as a
+ // black pass with nothing wrong.
+ const gpu = await acquireWebGPUDevice('webgpu', (m: string) => console.error(m));
+ if (!gpu.device) throw new Error(`WebGPU is not available: ${gpu.reason}`);
+ console.info(`[engine] webgpu adapter: ${gpu.adapter ?? 'unreported'}`);
+ moduleArg.preinitializedWebGPUDevice = gpu.device;
+ // The swapchain glue resolves the canvas by selector, so it has to be
+ // connected, and a hidden window never presents for drawImage readback —
+ // the WebGPU capture takes the PAGE, which needs pixel-exact placement.
+ canvas.style.position = 'fixed';
+ canvas.style.left = '0';
+ canvas.style.top = '0';
+ canvas.style.width = `${width}px`;
+ canvas.style.height = `${height}px`;
+ }
+ document.body.appendChild(canvas);
+
+ module = await createModule(moduleArg);
+
+ let renderSurface: RenderSurfaceSource;
+ if (backend === 'webgpu') {
+ renderSurface = { kind: 'webgpu', canvasSelector: '#canvas', readback: true };
+ } else {
+ const gl = canvas.getContext('webgl2', {
+ alpha: false,
+ antialias: true,
+ depth: true,
+ stencil: true,
+ premultipliedAlpha: false,
+ // Nothing composites here, and a readback happens in a later task than
+ // the draw — without this the browser may discard the drawing buffer
+ // and every capture comes back black.
+ preserveDrawingBuffer: true,
+ }) as WebGL2RenderingContext | null;
+ if (!gl) throw new Error('WebGL2 is not available in this renderer.');
+ renderSurface = {
+ kind: 'gl-context',
+ handle: module.GL.registerContext(gl, { majorVersion: 2, minorVersion: 0, enableExtensionsByDefault: true }),
+ };
+ }
+
+ app = createWebApp(module, {
+ renderSurface,
+ colorSpace,
+ randomSeed,
+ depthLayers,
+ getViewportSize: () => ({ width: canvas!.width, height: canvas!.height }),
+ wasmBaseUrl: '/wasm',
+ });
+ app.enableStats();
+
+ // The fixtures are AUTHORING scenes, and authoring mode is what they were
+ // captured under: gameplay systems (particles, animation, physics, timeline)
+ // stay frozen so a capture is the same frame every time. ESTELLA_VERIFY_PLAY
+ // flips this per gate via setRunMode.
+ setEditorMode(true);
+ setPlayMode(false);
+}
+
+/**
+ * Fetch an `.esscene` and load it through the engine's own asset system — one
+ * asset-resolution path, the same `Assets` the shipped runtime uses. The
+ * manifest is a uuid→url map beside the scene; without one, refs blank to 0.
+ */
+async function loadScene(sceneUrl: string, manifestUrl?: string): Promise<number> {
+ if (!app) throw new Error('loadScene before boot');
+ const res = await fetch(sceneUrl);
+ if (!res.ok) throw new Error(`scene fetch failed: ${res.status} ${sceneUrl}`);
+ const raw = (await res.json()) as SceneData;
+
+ const uuidToUrl = await fetchManifest(manifestUrl);
+ const assets = app.getResource(Assets);
+ let resolved: SceneData = raw;
+ if (assets) {
+ assets.baseUrl = ''; // manifest urls are root-relative
+ assets.setAssetRefResolver((ref: string) =>
+ ref.startsWith(UUID_PREFIX) ? (uuidToUrl.get(ref.slice(UUID_PREFIX.length)) ?? null) : ref,
+ );
+ const result = await assets.preloadSceneAssets(raw);
+ resolved = JSON.parse(JSON.stringify(raw)) as SceneData; // resolveSceneAssetPaths mutates
+ assets.resolveSceneAssetPaths(resolved, result);
+ }
+
+ const map = loadSceneData(app.world, resolved as Parameters<typeof loadSceneData>[1]);
+ sceneRaw = raw;
+ sourceToEntity = map as unknown as Map<number, number>;
+ // Both skeletal runtimes render through side modules loaded separately from
+ // Assets, so their entities are bound after the World exists — through the
+ // SAME shared loaders the shipped runtime uses. BOTH, because a scene that
+ // carries one and a host that binds the other renders an empty frame and
+ // reports no error.
+ const toUrl = (ref: string) =>
+ ref.startsWith(UUID_PREFIX) ? (uuidToUrl.get(ref.slice(UUID_PREFIX.length)) ?? ref) : ref;
+ const entityMap = map as unknown as Map<number, number>;
+ await loadSpine(app, raw, entityMap, toUrl);
+ await loadDragonBones(app, raw, entityMap, toUrl);
+ return map.size;
+}
+
+async function fetchManifest(manifestUrl?: string): Promise<Map<string, string>> {
+ const out = new Map<string, string>();
+ if (!manifestUrl) return out;
+ try {
+ const res = await fetch(manifestUrl);
+ if (!res.ok) return out;
+ for (const [uuid, url] of Object.entries((await res.json()) as Record<string, string>)) out.set(uuid, url);
+ } catch {
+ // no manifest — refs blank to 0
+ }
+ return out;
+}
+
+async function loadSpine(
+ target: App, sceneData: SceneData, entityMap: Map<number, number>, toUrl: (ref: string) => string,
+): Promise<void> {
+ const spineManager = target.getPlugin(SpinePlugin)?.spineManager;
+ const wasm = target.wasmModule;
+ const registry = target.world.getCppRegistry();
+ if (!spineManager || !wasm || !registry) return;
+ try {
+ await loadSpineSceneEntities({
+ module: wasm, source: skeletalSource(toUrl, 'spine'), spineManager, sceneData, entityMap, registry,
+ });
+ } catch (err) {
+ console.warn('[engine] spine scene load failed', err);
+ }
+}
+
+/**
+ * The manager is acquired rather than read: the plugin fetches its wasm on first
+ * ask, so a host that never loads an armature never loads the module.
+ */
+async function loadDragonBones(
+ target: App, sceneData: SceneData, entityMap: Map<number, number>, toUrl: (ref: string) => string,
+): Promise<void> {
+ const wasm = target.wasmModule;
+ if (!wasm) return;
+ try {
+ const manager = await target.getPlugin(DragonBonesPlugin)?.acquire();
+ if (!manager) return;
+ await loadDragonBonesSceneEntities({
+ module: wasm, source: skeletalSource(toUrl, 'dragonbones'), manager, sceneData, entityMap,
+ });
+ } catch (err) {
+ console.warn('[engine] DragonBones scene load failed', err);
+ }
+}
+
+/**
+ * The asset source both skeletal loaders fetch over. Skeleton and atlas arrive as
+ * text/bytes; the atlas image decodes through the shared `decodeImagePixels`, the
+ * same path the shipped runtime takes. What differs between the two runtimes is
+ * how an atlas names its images, not how a host reaches a file — hence one source.
+ */
+function skeletalSource(toUrl: (ref: string) => string, label: string): RuntimeAssetSource {
+ const fetchOk = async (ref: string, kind: string): Promise<Response> => {
+ const r = await fetch(toUrl(ref));
+ if (!r.ok) throw new Error(`${label} ${kind} ${r.status}: ${ref}`);
+ return r;
+ };
+ return {
+ resolveRef: (ref) => toUrl(ref),
+ backend: {
+ resolveUrl: (ref) => toUrl(ref),
+ fetchText: async (ref) => (await fetchOk(ref, 'asset')).text(),
+ fetchBinary: async (ref) => (await fetchOk(ref, 'asset')).arrayBuffer(),
+ },
+ decodePixels: async (ref) => decodeImagePixels(await (await fetchOk(ref, 'texture')).blob()),
+ };
+}
+
+const api = {
+ loadScene,
+
+ resizeViewport(w: number, h: number): void {
+ if (!canvas) throw new Error('resizeViewport before boot');
+ canvas.width = w;
+ canvas.height = h;
+ },
+
+ /** Advances frames by hand — the per-frame work app.run()'s loop does. */
+ async step(framesIn: number | null = 1, dtIn: number | null = 1 / 60): Promise<{ world: string; frames: number; dt: number }> {
+ // An omitted argument arrives as null across the JSON hop, and a default
+ // parameter only answers to undefined. Normalise, and report what ran.
+ const frames = Number(framesIn) > 0 ? Math.floor(Number(framesIn)) : 1;
+ const dt = Number(dtIn) > 0 ? Number(dtIn) : 1 / 60;
+ for (let i = 0; i < frames; i++) await app?.tick(dt);
+ return { world: 'engine', frames, dt };
+ },
+
+ captureViewport(): { rgba: Uint8Array; width: number; height: number } {
+ if (!canvas) throw new Error('captureViewport before boot');
+ const w = canvas.width, h = canvas.height;
+ const gl = canvas.getContext('webgl2') as WebGL2RenderingContext | null;
+ if (gl) {
+ const rgba = new Uint8Array(w * h * 4);
+ gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, rgba);
+ return { rgba, width: w, height: h };
+ }
+ // WebGPU: read the presented frame back through a 2D copy.
+ const copy = document.createElement('canvas');
+ copy.width = w; copy.height = h;
+ const ctx = copy.getContext('2d');
+ if (!ctx) throw new Error('captureViewport: no 2d context for the WebGPU readback');
+ ctx.drawImage(canvas, 0, 0);
+ return { rgba: new Uint8Array(ctx.getImageData(0, 0, w, h).data.buffer), width: w, height: h };
+ },
+
+ getStats(): { entities: number; drawCalls: number } {
+ return {
+ entities: app?.world.entityCount() ?? 0,
+ drawCalls: (module as unknown as { renderer_getDrawCalls?(): number } | null)?.renderer_getDrawCalls?.() ?? 0,
+ };
+ },
+
+ /** Runs the gameplay systems the authoring mode freezes. */
+ setRunMode(playing: boolean): boolean {
+ setEditorMode(!playing);
+ setPlayMode(playing);
+ return false;
+ },
+
+ setYSortLayers(mask: number): void {
+ Renderer.setYSortLayers(mask >>> 0);
+ },
+
+ /** Moves an entity — the 2.5D and parallax gates drive the camera this way. */
+ setEntityXY(id: number, x: number, y: number): void {
+ const entity = requireEntity(id);
+ const t = app!.world.get(entity, Transform);
+ t.position.x = x;
+ t.position.y = y;
+ app!.world.set(entity, Transform, t);
+ },
+
+ /**
+ * Writes one component field by path, the engine's own write door. The
+ * declared field type is the editor's vocabulary for how its inspector
+ * renders a value; the World takes the value itself.
+ */
+ setField(id: number, component: string, key: string, _type: string, value: unknown): void {
+ const entity = requireEntity(id);
+ const comp = getComponent(component);
+ if (!comp) throw new Error(`setField: no component named "${component}"`);
+ const data = app!.world.get(entity, comp) as Record<string, unknown>;
+ writeFieldPath(data, key, coerceToShape(readFieldPath(data, key), value));
+ app!.world.set(entity, comp, data);
+ },
+
+ getEntity(id: number): { id: number; name: string; components: string[] } | null {
+ const node = sceneRaw?.entities?.find((e) => e.id === id);
+ if (!node) return null;
+ return { id, name: node.name, components: (node.components ?? []).map((c) => c.type) };
+ },
+
+ /**
+ * The scene's entity hierarchy, as the FILE declares it. The editor's version
+ * of this reads its authoring model; here the file is the model, which is the
+ * same tree for anything this host loads (it never edits one).
+ */
+ getSceneTree(): Array<{ id: number; name: string; children: unknown[] }> {
+ const nodes = sceneRaw?.entities ?? [];
+ const byId = new Map(nodes.map((e) => [e.id, e]));
+ const build = (id: number): { id: number; name: string; children: unknown[] } => {
+ const n = byId.get(id);
+ return { id, name: n?.name ?? '', children: (n?.children ?? []).map(build) };
+ };
+ return nodes.filter((e) => e.parent === null || e.parent === undefined).map((e) => build(e.id));
+ },
+
+ // Editor doors, absent by design.
+ setGrid: () => editorOnly('set_grid'),
+ pick: () => editorOnly('pick'),
+ useEditorView: () => editorOnly('use_editor_view'),
+ setViewOrbit: () => editorOnly('set_view_orbit'),
+ setViewPerspective: () => editorOnly('set_view_perspective'),
+ renderSceneMaterialPreview: () => editorOnly('render_scene_material_preview'),
+ renderSceneMeshPreview: () => editorOnly('render_scene_mesh_preview'),
+};
+
+/** Reads `path` ("a.b.c") out of `obj`, or undefined at the first missing hop. */
+function readFieldPath(obj: unknown, path: string): unknown {
+ let at: unknown = obj;
+ for (const key of path.split('.')) {
+ if (at === null || typeof at !== 'object') return undefined;
+ at = (at as Record<string, unknown>)[key];
+ }
+ return at;
+}
+
+/**
+ * A vector field is written down as an array — `[16, 0]` says more about a gate's
+ * intent than `{"x":16,"y":0}` and is what the authored gates carry. The World
+ * takes the struct, so widen against the value already there rather than against
+ * a list of component shapes this host would then have to keep current.
+ */
+function coerceToShape(current: unknown, value: unknown): unknown {
+ if (!Array.isArray(value)) return value;
+ if (current === null || typeof current !== 'object' || Array.isArray(current)) return value;
+ const keys = Object.keys(current as Record<string, unknown>);
+ if (keys.length !== value.length) return value;
+ return Object.fromEntries(keys.map((k, i) => [k, value[i]]));
+}
+
+function requireEntity(id: number): number {
+ const entity = sourceToEntity.get(Number(id));
+ if (entity === undefined) throw new Error(`the scene has no entity with id ${id}`);
+ return entity;
+}
+
+// Held from before a loss: getExtension on an already-lost context is not
+// required to hand the object back, and restoreContext has to be called on the
+// same one that took the context away.
+let cachedLoseExt: { loseContext(): void; restoreContext(): void } | null = null;
+function loseContextExtension() {
+ if (cachedLoseExt) return cachedLoseExt;
+ const gl = canvas?.getContext('webgl2') as WebGL2RenderingContext | null;
+ cachedLoseExt = gl?.getExtension('WEBGL_lose_context') ?? null;
+ return cachedLoseExt;
+}
+
+declare global {
+ interface Window {
+ __estellaHeadless?: unknown;
+ }
+}
+
+window.__estellaHeadless = {
+ ready: boot(),
+ api,
+ device: {
+ status: () => getDeviceStatus(),
+ report: () => getDeviceLostReport(),
+ recover: () => recoverDevice(),
+ finishRecovery: () => finishDeviceRecovery(),
+ recoverFull: async () => (await app?.getResource(Assets)?.recoverFromDeviceLoss()) ?? false,
+ // Which textures did not come back, not how many: a failing recovery
+ // needs the list, and a number cannot give it.
+ awaiting: () => (app?.getResource(Assets)?.texturesAwaitingReupload() ?? [])
+ .map((t: { handle: number; path: string }) => `${t.handle}|${t.path}`),
+ // Emscripten's GL tables hold wrappers minted against the dead context;
+ // counting them says whether a rebuild refilled them or merely added to
+ // the stale ones.
+ glTables: () => {
+ const GL = (module as unknown as { GL?: Record<string, unknown> } | null)?.GL;
+ const count = (n: string): number => {
+ const t = GL?.[n] as unknown[] | undefined;
+ if (!t) return -1;
+ let live = 0;
+ for (const e of t) if (e) live++;
+ return live;
+ };
+ return {
+ programs: count('programs'), shaders: count('shaders'), buffers: count('buffers'),
+ textures: count('textures'), vaos: count('vaos'), framebuffers: count('framebuffers'),
+ };
+ },
+ guard: () => getContextLossGuardInfo(),
+ contextLost: () => {
+ const gl = canvas?.getContext('webgl2') as WebGL2RenderingContext | null;
+ return gl ? gl.isContextLost() : null;
+ },
+ lose: () => {
+ const ext = loseContextExtension();
+ if (ext) {
+ ext.loseContext();
+ return true;
+ }
+ // WebGPU has no lose-context extension. Destroying the device is the
+ // one loss a page can cause, and it reaches the engine as any other
+ // would. The device IN USE, not the one booted with: after a recovery
+ // those differ, and destroying the dead one again is not a loss.
+ const m = module as unknown as {
+ currentWebGPUDevice?: { destroy?(): void };
+ preinitializedWebGPUDevice?: { destroy?(): void };
+ } | null;
+ const gpu = m?.currentWebGPUDevice ?? m?.preinitializedWebGPUDevice;
+ if (!gpu?.destroy) return false;
+ gpu.destroy();
+ return true;
+ },
+ restore: () => {
+ const ext = loseContextExtension();
+ if (!ext) return false;
+ ext.restoreContext();
+ return true;
+ },
+ },
+ // Nothing about the geometry changes — same entity, same vertices, the other
+ // path — so the frame afterwards has to be the same frame.
+ makeMeshesResident: () => {
+ const m = module as unknown as { mesh2d_makeAllResident?(registry: unknown): number } | null;
+ const registry = app?.world.getCppRegistry();
+ if (!m?.mesh2d_makeAllResident || !registry) return 0;
+ return m.mesh2d_makeAllResident(registry);
+ },
+ // Through the asset layer, not a side door: the file goes through the same
+ // load() every other asset type does, so what this proves is the format
+ // reaching the screen rather than a decoder wired straight to the engine.
+ loadMeshAsset: async (path: string) => {
+ const assets = app?.getResource(Assets);
+ const m = module as unknown as { mesh2d_setMeshAll?(registry: unknown, handle: number): number } | null;
+ const registry = app?.world.getCppRegistry();
+ if (!assets || !m?.mesh2d_setMeshAll || !registry) return 0;
+ const mesh = await assets.load<{ handle: number }>('mesh', path);
+ if (!mesh?.handle) return 0;
+ return m.mesh2d_setMeshAll(registry, mesh.handle);
+ },
+ loadMaterialAsset: async (path: string) => {
+ const assets = app?.getResource(Assets);
+ const m = module as unknown as { mesh2d_setMaterialAll?(registry: unknown, id: number): number } | null;
+ const registry = app?.world.getCppRegistry();
+ if (!assets || !m?.mesh2d_setMaterialAll || !registry) return 0;
+ const material = await assets.load<{ handle: number }>('material', path);
+ if (!material?.handle) return 0;
+ return m.mesh2d_setMaterialAll(registry, material.handle);
+ },
+ // A prefab brings its own asset refs, so this hands the file to the engine's
+ // own instantiation and asserts nothing about what it names: the claim is
+ // about an import's products, not a scene written to match them.
+ loadPrefabAsset: async (path: string) => {
+ const assets = app?.getResource(Assets);
+ if (!assets || !app) return 0;
+ const prefab = await assets.loadPrefab(path);
+ const result = await instantiatePrefab(app.world, prefab.data as PrefabData, { assets });
+ return result.entities.size;
+ },
+};
+
+// Referenced so an unused-import check sees it; DeviceStatus is the vocabulary a
+// driver compares status() against.
+export const DEVICE_STATUS_VOCAB = DeviceStatus;
+export const NAME_COMPONENT = Name;
diff --git a/tools/render-host/index.html b/tools/render-host/index.html
new file mode 100644
index 000000000..7585edce9
--- /dev/null
+++ b/tools/render-host/index.html
@@ -0,0 +1,19 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <!-- Mirrors the CSP a shipped page runs under (embind needs 'unsafe-eval'),
+ so a render that fails here for a CSP reason fails there too. -->
+ <meta
+ http-equiv="Content-Security-Policy"
+ content="default-src 'self'; script-src 'self' 'unsafe-eval' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' ws:; worker-src 'self' blob:;"
+ />
+ <title>Estella Render Host</title>
+ <style>
+ html, body { margin: 0; padding: 0; background: #000; }
+ </style>
+ </head>
+ <body>
+ <script type="module" src="./host.js"></script>
+ </body>
+</html>
diff --git a/desktop/scripts/headless-verify.mjs b/tools/render-host/run.mjs
similarity index 96%
rename from desktop/scripts/headless-verify.mjs
rename to tools/render-host/run.mjs
index c8d0a6399..60444402a 100644
--- a/desktop/scripts/headless-verify.mjs
+++ b/tools/render-host/run.mjs
@@ -31,8 +31,8 @@ import os from 'node:os';
import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { onRendererConsole } from './rendererConsole.mjs';
-import { serveHost } from '../../tools/lib/staticServer.mjs';
+import { onRendererConsole } from '../lib/rendererConsole.mjs';
+import { serveHost } from '../lib/staticServer.mjs';
// SwiftShader rasterizes on the CPU; run the whole electron tree below normal
// priority (child processes inherit the class) so a verify never starves the
@@ -41,7 +41,23 @@ try {
os.setPriority(os.constants.priority.PRIORITY_BELOW_NORMAL);
} catch { /* not fatal — some sandboxes forbid it */ }
-const DIST = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'dist');
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+// Two hosts answer the same driving surface. The engine's is the default — a
+// gate about the renderer should not need an editor to run. The editor's keeps
+// the handful whose subject IS an editor door (the reference grid, hit-testing,
+// the editor eye, preview renders).
+const HOSTS = {
+ engine: { dist: path.join(ROOT, 'build', 'render-host'), page: 'index.html' },
+ editor: { dist: path.join(ROOT, 'desktop', 'dist'), page: 'headless.html' },
+};
+const HOST = process.env.ESTELLA_VERIFY_HOST ?? 'engine';
+if (!HOSTS[HOST]) {
+ console.error(`verify: unknown host "${HOST}" (have: ${Object.keys(HOSTS).join(', ')})`);
+ process.exit(2);
+}
+const DIST = HOSTS[HOST].dist;
+const PAGE = HOSTS[HOST].page;
const SCENE = process.env.ESTELLA_VERIFY_SCENE ?? '/scenes/sprite-rendering.esscene';
const MANIFEST = process.env.ESTELLA_VERIFY_MANIFEST ?? '/scenes/sprite-rendering.textures.json';
@@ -145,7 +161,7 @@ app.whenReady().then(async () => {
let server;
try {
server = await serveHost(DIST);
- const url = `http://127.0.0.1:${server.address().port}/headless.html?w=${W}&h=${H}&backend=${BACKEND}${COLORSPACE ? `&colorSpace=${COLORSPACE}` : ''}${DEPTH_LAYERS ? `&depthLayers=${DEPTH_LAYERS}` : ''}${SEED ? `&seed=${SEED}` : ''}`;
+ const url = `http://127.0.0.1:${server.address().port}/${PAGE}?w=${W}&h=${H}&backend=${BACKEND}${COLORSPACE ? `&colorSpace=${COLORSPACE}` : ''}${DEPTH_LAYERS ? `&depthLayers=${DEPTH_LAYERS}` : ''}${SEED ? `&seed=${SEED}` : ''}`;
// useContentSize: the capture rectangle must be the page area, not the
// outer frame (the same trap the parity runner documents).
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index f1928809b..97b7c8454 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -45,13 +45,13 @@ export const SCENE_WATCHDOG_MS = { webgl2: 45_000, webgpu: 120_000 };
export const SCENES = [
{ id: "sprite-default", tier: "pr", webgpu: true, env: { } },
// Editor grid on/off pixel diff — guards the custom-draw reflected material path (drawMeshWithMaterial + MaterialConstants UBO).
- { id: "editor-grid", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_GRID: "64", ESTELLA_VERIFY_STEPS: "3" } },
+ { id: "editor-grid", tier: "pr", host: "editor", webgpu: true, env: { ESTELLA_VERIFY_GRID: "64", ESTELLA_VERIFY_STEPS: "3" } },
// The same grid from straight above a 3D view. It stands on the ground there, so it fills the frame; the 2D plane would be edge-on and light one band.
- { id: "editor-grid-3d", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-instanced.esscene", ESTELLA_VERIFY_GRID: "64", ESTELLA_VERIFY_PERSPECTIVE: "1", ESTELLA_VERIFY_ORBIT: "0,90", ESTELLA_VERIFY_STEPS: "3" } },
+ { id: "editor-grid-3d", tier: "pr", host: "editor", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-instanced.esscene", ESTELLA_VERIFY_GRID: "64", ESTELLA_VERIFY_PERSPECTIVE: "1", ESTELLA_VERIFY_ORBIT: "0,90", ESTELLA_VERIFY_STEPS: "3" } },
// The same 3D view head-on. A plane within ~6 degrees of edge-on hands over to the
// plane the eye most faces, which head-on is the 2D plane — so the grid covers the
// frame instead of collapsing to the one stroke an edge-on plane draws.
- { id: "editor-grid-head-on", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-instanced.esscene", ESTELLA_VERIFY_GRID: "64", ESTELLA_VERIFY_PERSPECTIVE: "1", ESTELLA_VERIFY_ORBIT: "0,0", ESTELLA_VERIFY_STEPS: "3" } },
+ { id: "editor-grid-head-on", tier: "pr", host: "editor", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-instanced.esscene", ESTELLA_VERIFY_GRID: "64", ESTELLA_VERIFY_PERSPECTIVE: "1", ESTELLA_VERIFY_ORBIT: "0,0", ESTELLA_VERIFY_STEPS: "3" } },
{ id: "mesh2d", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh2d.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh2d.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.30,\"y\":0.556,\"rgb\":[255,0,0],\"tol\":40},{\"x\":0.70,\"y\":0.556,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.30,\"y\":0.40,\"rgb\":[255,0,0],\"tol\":40}]" } },
{ id: "parallax-shape", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/parallax-shape.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/parallax-shape.textures.json", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.25,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":40}]" } },
{ id: "tilemap-flip", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/tilemap-flip.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/tilemap-flip.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.40,\"y\":0.36,\"rgb\":[255,0,0]},{\"x\":0.60,\"y\":0.36,\"rgb\":[0,255,0]},{\"x\":0.40,\"y\":0.58,\"rgb\":[0,0,255]},{\"x\":0.60,\"y\":0.58,\"rgb\":[255,255,0]}]" } },
@@ -233,7 +233,7 @@ export const SCENES = [
{ id: "material-builtin-lit", tier: "nightly", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-builtin-lit.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mat-builtin-lit.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":30}]" } },
{ id: "material-dissolve", tier: "nightly", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-dissolve.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mat-dissolve.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":30}]" } },
{ id: "material-graph", tier: "nightly", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-graph.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mat-graph.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":40}]" } },
- { id: "material-preview", tier: "pr", webgpu: { ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":40}]" }, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-tint.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mat-tint.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_PREVIEW: "{\"w\":64,\"h\":64,\"rgb\":[255,0,0],\"tol\":45}" } },
+ { id: "material-preview", tier: "pr", host: "editor", webgpu: { ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":40}]" }, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-tint.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mat-tint.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_PREVIEW: "{\"w\":64,\"h\":64,\"rgb\":[255,0,0],\"tol\":45}" } },
{ id: "tilemap-hex", tier: "nightly", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/tilemap-hex.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/tilemap-hex.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "6", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.40,\"y\":0.40,\"rgb\":[255,0,0]},{\"x\":0.60,\"y\":0.40,\"rgb\":[0,255,0]},{\"x\":0.50,\"y\":0.55,\"rgb\":[0,0,255]},{\"x\":0.70,\"y\":0.55,\"rgb\":[255,255,0]}]" } },
{ id: "postprocess-lut", tier: "nightly", webgpu: true, env: { 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}]" } },
// mesh2d's scene and assertions, with its geometry frozen onto the GPU mid-run.
@@ -280,7 +280,7 @@ export const SCENES = [
// A thumbnail of the geometry itself, offscreen through the viewport's own
// path. What it adds over a material ball is the FRAMING: the gate asks for a
// clear border (nothing escaped) and an outer eighth reached (nothing shrank).
- { id: "mesh-preview", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_MESH_PREVIEW: "{\"w\":128,\"h\":128}", ESTELLA_VERIFY_SCENE: "/scenes/mesh-lit.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh-lit.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4" } },
+ { id: "mesh-preview", tier: "pr", host: "editor", webgpu: true, env: { ESTELLA_VERIFY_MESH_PREVIEW: "{\"w\":128,\"h\":128}", ESTELLA_VERIFY_SCENE: "/scenes/mesh-lit.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh-lit.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4" } },
// A SCENE camera that looks from somewhere else. Two sprites on the camera's
// own axis project to ONE point for a 2D camera; pitched 20 deg they land at
// 0.329 and 0.158 down the frame — arithmetic — and the centre is empty.
@@ -289,15 +289,15 @@ export const SCENES = [
// live loader + re-projection. The quad covers the gap between the scene's own
// two triangles, so the frame says which geometry is drawn — and the hit test
// lands 120 world units out, where only the mesh's own box reaches.
- { id: "mesh-assign", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SET_FIELD: "{\"entity\":1,\"component\":\"Mesh2D\",\"key\":\"mesh\",\"value\":\"/scenes/textured-quad.esmesh\"}", ESTELLA_VERIFY_PICK: "{\"x\":0.7,\"y\":0.3833,\"entity\":1}", ESTELLA_VERIFY_SCENE: "/scenes/mesh2d.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh2d.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[255,255,255],\"tol\":40},{\"x\":0.30,\"y\":0.556,\"rgb\":[255,255,255],\"tol\":40}]" } },
+ { id: "mesh-assign", tier: "pr", host: "editor", webgpu: true, env: { ESTELLA_VERIFY_SET_FIELD: "{\"entity\":1,\"component\":\"Mesh2D\",\"key\":\"mesh\",\"value\":\"/scenes/textured-quad.esmesh\"}", ESTELLA_VERIFY_PICK: "{\"x\":0.7,\"y\":0.3833,\"entity\":1}", ESTELLA_VERIFY_SCENE: "/scenes/mesh2d.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh2d.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[255,255,255],\"tol\":40},{\"x\":0.30,\"y\":0.556,\"rgb\":[255,255,255],\"tol\":40}]" } },
// The editor's eye turned 60° about Y. Where the triangles land is arithmetic:
// centres at x = ±120 project to 0.40 / 0.60, with 0.30 empty. The hit test at
// the new place proves screen→world followed the turn.
- { id: "view-orbit", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_ORBIT: "60,0", ESTELLA_VERIFY_PICK: "{\"x\":0.40,\"y\":0.556,\"entity\":1}", ESTELLA_VERIFY_SCENE: "/scenes/mesh2d.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh2d.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.40,\"y\":0.556,\"rgb\":[255,0,0],\"tol\":40},{\"x\":0.60,\"y\":0.556,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.30,\"y\":0.556,\"rgb\":[0,0,0],\"tol\":30}]" } },
+ { id: "view-orbit", tier: "pr", host: "editor", webgpu: true, env: { ESTELLA_VERIFY_ORBIT: "60,0", ESTELLA_VERIFY_PICK: "{\"x\":0.40,\"y\":0.556,\"entity\":1}", ESTELLA_VERIFY_SCENE: "/scenes/mesh2d.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mesh2d.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.40,\"y\":0.556,\"rgb\":[255,0,0],\"tol\":40},{\"x\":0.60,\"y\":0.556,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.30,\"y\":0.556,\"rgb\":[0,0,0],\"tol\":30}]" } },
// Two blended quads side by side in X at the SAME world z, the far one submitted
// last, seen from an eye turned -60° about Y. Equal world z ties, and the tie puts
// the FAR quad on top; only a viewer-measured depth puts the near (green) one there.
- { id: "sort-view-depth", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_ORBIT: "-60,0", ESTELLA_VERIFY_SCENE: "/scenes/sort-view-depth.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/sort-view-depth.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.30,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.70,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":40}]" } },
+ { id: "sort-view-depth", tier: "pr", host: "editor", webgpu: true, env: { ESTELLA_VERIFY_ORBIT: "-60,0", ESTELLA_VERIFY_SCENE: "/scenes/sort-view-depth.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/sort-view-depth.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "4", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.30,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.70,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":40}]" } },
// A sprite at z = +1 under an ortho camera at z = 0: inside the symmetric box the
// engine builds, and below 0 of what WebGPU keeps. Both backends draw it only while
// updateCameraConstants converts the projection into the clip volume each one has.
diff --git a/tools/verify-render.mjs b/tools/verify-render.mjs
index 9cc99cc7c..ec70bf375 100644
--- a/tools/verify-render.mjs
+++ b/tools/verify-render.mjs
@@ -12,6 +12,7 @@
* node tools/verify-render.mjs --tier nightly --only spine,video
*/
import path from 'node:path';
+import { existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { TIERS, SCENES, scenesAtTier, SCENE_WATCHDOG_MS } from './renderScenes.mjs';
import { retryOnDeadGpu, deadGpuVerdict } from './lib/deadGpu.mjs';
@@ -28,6 +29,10 @@ const flag = (n, d) => {
};
const TIER = flag('tier', 'pr');
+// Which host's scenes to run. The engine's gates stand on their own, so a
+// checkout without the editor submodule runs `--host engine` and is not quietly
+// short a hundred checks — it says which list it took.
+const HOST_FILTER = flag('host', '');
const ONLY = flag('only', '');
const BACKEND = flag('backend', 'webgl2');
const BUDGET = flag('budget', '');
@@ -50,6 +55,10 @@ if (!TIERS.includes(TIER)) {
process.exit(2);
}
+if (HOST_FILTER && !['engine', 'editor'].includes(HOST_FILTER)) {
+ console.error(`verify-render: unknown host "${HOST_FILTER}" (have: engine, editor)`);
+ process.exit(2);
+}
if (!['webgl2', 'webgpu'].includes(BACKEND)) {
console.error(`verify-render: unknown backend "${BACKEND}" (have: webgl2, webgpu)`);
process.exit(2);
@@ -77,6 +86,9 @@ const selected = only
: scenesAtTier(TIER).filter((s) => (BACKEND === 'webgpu' ? Boolean(s.webgpu) : true));
const scenes = selected.map((s) => ({
id: s.id,
+ // Which host answers this scene's driving surface. The engine's is the
+ // default; a scene names the editor's only when its SUBJECT is an editor door.
+ host: s.host ?? 'engine',
env: BACKEND === 'webgpu'
? {
...s.env,
@@ -89,35 +101,63 @@ const scenes = selected.map((s) => ({
}
: s.env,
}));
-// The copy this run will actually serve: --no-build leaves desktop/dist as it
-// stands, so a freshly built public/ one it never copies is evidence about a
-// binary no scene below is judging.
-requireCurrentEngine(ROOT, path.join(DESKTOP, NO_BUILD ? 'dist' : 'public', 'wasm'));
-console.log(`render ${only ? `${scenes.length} named scene(s)` : `${TIER}: ${scenes.length} scene(s)`} on ${BACKEND}`);
+const hosted = HOST_FILTER ? scenes.filter((s) => s.host === HOST_FILTER) : scenes;
+if (HOST_FILTER) {
+ const dropped = scenes.length - hosted.length;
+ if (dropped) console.log(` not on this host: ${dropped} scene(s)`);
+ scenes.length = 0;
+ scenes.push(...hosted);
+}
+const hostsUsed = new Set(scenes.map((s) => s.host));
+console.log(`render ${only ? `${scenes.length} named scene(s)` : `${TIER}: ${scenes.length} scene(s)`} on ${BACKEND}`
+ + ` (host: ${[...hostsUsed].sort().join(' + ')})`);
-if (!NO_BUILD) {
- const built = runTool('pnpm', ['exec', 'vite', 'build'], { cwd: DESKTOP, encoding: 'utf8' });
- if (built.status !== 0) {
- console.error(`verify-render: vite build failed\n${(built.stderr || built.stdout || '').slice(-800)}`);
- process.exit(1);
+// Build each host this run needs, then check the wasm it will actually SERVE:
+// --no-build leaves a host's output as it stands, and a freshly built public/
+// copy it never staged is evidence about a binary no scene below is judging.
+if (hostsUsed.has('engine')) {
+ if (!NO_BUILD) {
+ const built = runTool('node', ['tools/render-host/build.mjs'], { cwd: ROOT, encoding: 'utf8' });
+ if (built.status !== 0) {
+ console.error(`verify-render: render-host build failed\n${(built.stderr || built.stdout || '').slice(-800)}`);
+ process.exit(1);
+ }
+ }
+ requireCurrentEngine(ROOT, path.join(ROOT, 'build', 'render-host', 'wasm'));
+}
+if (hostsUsed.has('editor')) {
+ if (!existsSync(DESKTOP)) {
+ console.error('verify-render: these scenes name the editor host, which is not checked out'
+ + ' (desktop/ is an optional submodule).');
+ process.exit(2);
+ }
+ if (!NO_BUILD) {
+ const built = runTool('pnpm', ['exec', 'vite', 'build'], { cwd: DESKTOP, encoding: 'utf8' });
+ if (built.status !== 0) {
+ console.error(`verify-render: vite build failed\n${(built.stderr || built.stdout || '').slice(-800)}`);
+ process.exit(1);
+ }
}
+ requireCurrentEngine(ROOT, path.join(DESKTOP, NO_BUILD ? 'dist' : 'public', 'wasm'));
}
const seconds = (ms) => `${(ms / 1000).toFixed(1)}s`;
function runScene(scene) {
+ const RUNNER = 'tools/render-host/run.mjs';
const args = XVFB
- ? ['-a', 'pnpm', 'exec', 'electron', 'scripts/headless-verify.mjs']
- : ['exec', 'electron', 'scripts/headless-verify.mjs'];
+ ? ['-a', 'pnpm', 'exec', 'electron', RUNNER]
+ : ['exec', 'electron', RUNNER];
const at = Date.now();
const r = runTool(XVFB ? 'xvfb-run' : 'pnpm', args, {
- cwd: DESKTOP,
+ cwd: ROOT,
encoding: 'utf8',
timeout: WATCHDOG_MS + LAUNCH_MARGIN_MS,
env: {
...process.env,
ELECTRON_DISABLE_SANDBOX: '1',
ESTELLA_VERIFY_TIMEOUT_MS: String(WATCHDOG_MS),
+ ESTELLA_VERIFY_HOST: scene.host,
...scene.env,
},
});