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.

54.4 KB
Raw Blame
// 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 need an editor SESSION —
 * hit-testing over the authoring model, the asset previews it 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. The editor EYE and its
 * reference grid are not among them: both are SDK resources, so the host that
 * verifies the renderer verifies them too.
 */
import {
    createWebApp, setEditorMode, setPlayMode, Assets, acquireWebGPUDevice,
    loadSceneData, discoverSceneAssets, Renderer, instantiatePrefab, writeFieldPath, Transform, Name,
    getComponent, DeviceStatus, getDeviceStatus, getDeviceLostReport, recoverDevice,
    getContextLossGuardInfo, decodeImagePixels, captureFramePixels, captureFrame, replayDraw, BatchBreak,
    RenderTexture, Camera, Sprite, Time,
    Children, MeshRenderer, RuntimeOnly, CompositeBatch, CompositeBatchingRes, StaticBatchingRes,
    HttpBackend, initRuntime, createRuntimeSceneConfig, WorldStreaming, worldResidencyReport,
    cutWorld, registryEntityFields, stableEntityId, persistentEntityRows,
    planarReflectionStatus,
    EditorViewLighting, EditorViewShading, EditorView, EditorGrid, installEditorGrid, editorViewHalfHeight, setEditorViewHalfHeight,
    ProfileRecorder, AnimatorController, Timeline, onDeviceRestored, Schedule, defineSystem,
    textureImportSettingsFrom, shadersCompiled, warmShaders, defineSkyEffect,
} from 'esengine';
import type { App, SceneData, SceneEntityData, 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 requestedTransform = params.get('outputTransform');
const outputTransform = requestedTransform === 'aces' || requestedTransform === 'neutral' ? requestedTransform : undefined;
const msaaSamples = Number(params.get('msaa')) || undefined;
/** The opaque scene drawn twice, depth alone first: the quality levels turn it on, and this host has none. */
const depthPrepass = params.get('prepass') === '1';
const seedParam = params.get('seed');
const randomSeed = seedParam !== null && Number.isFinite(Number(seedParam)) ? Number(seedParam) : undefined;
const depthLayers = Number(params.get('depthLayers')) || undefined;
// `runtime`: images decode to pixels and upload through the engine, as a shipped
// game and Play do, instead of through this page's WebGL context.
const runtimeTextures = params.get('textures') === 'runtime';
// The project's render-resolution policy (RenderResolution). Passed with the fit
// OFF, so the camera keeps its authored orthoSize and the frame differs by the
// policy alone — which is what a gate about the policy has to isolate.
const renderPolicy = Number(params.get('renderResolution')) || undefined;
const screenFit = renderPolicy === undefined ? undefined : {
    designWidth: width, designHeight: height,
    scaleMode: -1, matchWidthOrHeight: 0.5, renderPolicy,
};

let app: App | null = null;
let profiler: ProfileRecorder | 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>();
let streamedSource: RuntimeAssetSource | null = null;

/** 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).',
    );
}

// The host's own sky, for the custom-sky gate: blue above the horizon and red below, so which half lit a surface reads
// off its colour and a panorama read upside down swaps them.
defineSkyEffect({
    type: 'verifySky',
    label: 'Verify Sky',
    glsl: `vec3 skyRadiance(vec3 dir, vec3 sun, vec3 sunColor, float env) {
    return dir.y >= 0.0 ? vec3(0.1, 0.2, 0.9) : vec3(0.8, 0.15, 0.05);
}`,
    wgsl: `fn skyRadiance(dir : vec3f, sun : vec3f, sunColor : vec3f, env : f32) -> vec3f {
    return select(vec3f(0.8, 0.15, 0.05), vec3f(0.1, 0.2, 0.9), dir.y >= 0.0);
}`,
});

// A sky with a known formula, for the oracle scenes (tools/oracle/sky.mjs): a gradient from a warm horizon to a blue zenith by the
// height of the view direction, and the sun's colour in a narrow lobe round the sun, so that what a pixel shows is a sum a test can write.
defineSkyEffect({
    type: 'oracleSky',
    label: 'Oracle Sky',
    glsl: `vec3 skyRadiance(vec3 dir, vec3 sun, vec3 sunColor, float env) {
    float t = clamp(dir.y * 0.5 + 0.5, 0.0, 1.0);
    return mix(vec3(0.6, 0.3, 0.1), vec3(0.1, 0.3, 0.8), t) + sunColor * pow(max(dot(dir, sun), 0.0), 64.0) * 0.5;
}`,
    wgsl: `fn skyRadiance(dir : vec3f, sun : vec3f, sunColor : vec3f, env : f32) -> vec3f {
    let t = clamp(dir.y * 0.5 + 0.5, 0.0, 1.0);
    return mix(vec3f(0.6, 0.3, 0.1), vec3f(0.1, 0.3, 0.8), t) + sunColor * pow(max(dot(dir, sun), 0.0), 64.0) * 0.5;
}`,
});

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), and the error listener is what makes an invalid
        // draw visible — without one Dawn drops it in silence.
        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);
    }
    // WebGL2 leaves the canvas OUT of the document: the readback comes from the
    // engine, not the page, so attaching it only gives the compositor work.

    module = await createModule(moduleArg);
    // A device that has a compute stage, told it has none: the fragment version of an effect that has both is the one that draws, so the two
    // can be compared on one backend, pixel for pixel.
    if (params.get('noCompute') === '1') (module as unknown as { postprocess_supportsCompute?: () => boolean }).postprocess_supportsCompute = () => false;

    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,
        outputTransform,
        msaaSamples,
        randomSeed,
        depthLayers,
        screenFit,
        getViewportSize: () => ({ width: canvas!.width, height: canvas!.height }),
        wasmBaseUrl: '/wasm',
    });
    app.enableStats();
    // The editor's engine asks for edge buffers before its assets load; so does this host.
    module.renderer_setMeshEdgeBuffers?.(true);
    if (depthPrepass) module.renderer_setDepthPrepass?.(true);
    if (runtimeTextures) {
        app.getResource(Assets).getTextureLoader().setPixelDecoder(async (path) => {
            const res = await fetch(path);
            if (!res.ok) throw new Error(`texture ${res.status}: ${path}`);
            return decodeImagePixels(await res.blob());
        });
    }

    // The fixtures are AUTHORING scenes and were captured in authoring mode, where
    // gameplay systems stay frozen so a capture is the same frame every time.
    // ESTELLA_VERIFY_PLAY flips this per gate via setRunMode.
    setEditorMode(true);
    setPlayMode(false);

    // The reference grid is SDK code drawn through an SDK resource, so the engine's
    // own host can verify it. It stays dark until a gate asks: the renderer self-
    // gates on EditorGrid.enabled and EditorView.active, and this host leaves both off.
    installEditorGrid(app);
}

/**
 * @brief What a scale gate copies, so a frame's SIZE is a parameter and not a file.
 *
 * @details `copies` of the scene's content on a centred `cols`-wide grid, `spacing`
 *          apart in world units. Ten thousand entities as a file would be a megabyte
 *          of JSON in every clone, for a pure function of one fixture and a count.
 */
interface ReplicateSpec {
    copies: number;
    cols: number;
    spacing: [number, number];
    /** Component types or entity names that are the frame's FURNITURE, not its content. */
    keep?: string[];
}

/** What looks at the content or receives it. Ten thousand cameras, lights or
 *  ground planes measures a frame no game draws. */
const FURNITURE = ['Camera', 'Light'];

/** Adds a world offset to an entity's authored Transform position. */
function offsetPosition(entity: SceneEntityData, dx: number, dy: number): void {
    const transform = (entity.components ?? []).find((c) => c.type === 'Transform');
    if (!transform) return;
    const pos = (transform.data.position ?? {}) as { x?: number; y?: number; z?: number };
    transform.data.position = { x: (pos.x ?? 0) + dx, y: (pos.y ?? 0) + dy, z: pos.z ?? 0 };
}

/**
 * @brief Lays `spec.copies` copies of the scene's content out on a grid.
 *
 * @details EVERY copy is placed, the first included: leaving the authored entity where
 *          it was puts one copy off the lattice. Ids offset by a whole id-span per copy,
 *          so parent/children remap by arithmetic and copy 0 offsets by zero — which is
 *          what keeps the scene file's own ids addressable by a driver.
 */
function replicateScene(scene: SceneData, spec: ReplicateSpec): SceneData {
    const copies = Math.max(1, Math.floor(spec.copies));
    const cols = Math.max(1, Math.floor(spec.cols));
    const [spacingX, spacingY] = spec.spacing;
    const keep = new Set(spec.keep ?? FURNITURE);

    const byId = new Map<number, SceneEntityData>();
    for (const e of scene.entities) byId.set(e.id, e);

    const fixed: SceneEntityData[] = [];
    const template: SceneEntityData[] = [];
    const collect = (e: SceneEntityData): void => {
        template.push(e);
        for (const child of e.children ?? []) {
            const node = byId.get(child);
            if (node) collect(node);
        }
    };
    for (const e of scene.entities) {
        if (e.parent !== null && e.parent !== undefined) continue;
        if (keep.has(e.name) || (e.components ?? []).some((c) => keep.has(c.type))) fixed.push(e);
        else collect(e);
    }
    if (!template.length) {
        throw new Error('replicate: every root is furniture — the scene has no content to copy');
    }

    let maxId = 0;
    for (const e of scene.entities) maxId = Math.max(maxId, e.id);
    const span = maxId + 1;
    const rows = Math.ceil(copies / cols);

    const entities: SceneEntityData[] = fixed.slice();
    for (let k = 0; k < copies; k++) {
        const dx = ((k % cols) - (cols - 1) / 2) * spacingX;
        const dy = (Math.floor(k / cols) - (rows - 1) / 2) * spacingY;
        const offset = k * span;
        for (const source of template) {
            const clone = JSON.parse(JSON.stringify(source)) as SceneEntityData;
            clone.id = source.id + offset;
            clone.parent = source.parent === null || source.parent === undefined
                ? null : source.parent + offset;
            clone.children = (source.children ?? []).map((c) => c + offset);
            if (clone.parent === null) offsetPosition(clone, dx, dy);
            entities.push(clone);
        }
    }
    return { ...scene, entities };
}

/**
 * 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.
 *
 * `replicate` scales the fetched scene up before it reaches the World — what a
 * cost gate asserts against. Assets resolve on the ORIGINAL document, so ten
 * thousand copies of one sprite preload one texture.
 */
async function loadScene(
    sceneUrl: string, manifestUrl?: string, replicate?: ReplicateSpec | null,
): Promise<SceneLoadReport> {
    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;
    let missing: string[] = [];
    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,
        );
        assets.setTextureImportSettingsResolver(importSettingsFromMeta(uuidToUrl));
        const result = await assets.preloadSceneAssets(raw);
        missing = result.missing.map((m) => m.ref);
        resolved = JSON.parse(JSON.stringify(raw)) as SceneData; // resolveSceneAssetPaths mutates
        assets.resolveSceneAssetPaths(resolved, result);
    }

    // Skeletal binding below walks the ORIGINAL document, so only copy 0 of a
    // skeleton binds. Cost fixtures have none.
    if (replicate) resolved = replicateScene(resolved, replicate);

    const map = loadSceneData(app.world, resolved as Parameters<typeof loadSceneData>[1]);
    sceneRaw = raw;
    sourceToEntity = map as unknown as Map<number, number>;
    // Both skeletal runtimes load outside Assets, so they bind after the World
    // exists. BOTH: a scene carrying one against 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 { entities: map.size, missing };
}

/**
 * What a scene load leaves behind. `missing` names every ref the preload could not
 * turn into an asset: a frame drawn without one is not the frame the scene declares.
 */
interface SceneLoadReport {
    entities: number;
    missing: string[];
}

/**
 * A texture's import settings, read from the `.meta` beside it as the editor and an
 * export read them; without it every texture loaded as sRGB colour. Synchronous
 * because the loader asks synchronously, and this is a test host.
 */
function importSettingsFromMeta(uuidToUrl: Map<string, string>) {
    const cache = new Map<string, ReturnType<typeof textureImportSettingsFrom>>();
    return (ref: string) => {
        const url = ref.startsWith(UUID_PREFIX) ? uuidToUrl.get(ref.slice(UUID_PREFIX.length)) : ref;
        if (!url) return undefined;
        if (!cache.has(url)) {
            let settings: ReturnType<typeof textureImportSettingsFrom>;
            try {
                const xhr = new XMLHttpRequest();
                xhr.open('GET', `${url}.meta`, false);
                xhr.send();
                if (xhr.status === 200) {
                    settings = textureImportSettingsFrom(
                        (JSON.parse(xhr.responseText) as { importer?: Record<string, unknown> }).importer);
                }
            } catch { /* no meta: the loader's defaults */ }
            cache.set(url, settings);
        }
        return cache.get(url);
    };
}

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> {
    if (discoverSceneAssets(sceneData).dragonBones.length === 0) return;
    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,
    idleRenderFrames(count: number) {
        if (!module) throw new Error('idleRenderFrames before boot');
        for (let i = 0; i < count; i++) {
            module.renderer_beginFrame(i / 60);
            module.renderer_endFrame?.();
        }
    },
    planarReflectionStatus(id: number, cameraId?: number) {
        if (!app) throw new Error('planarReflectionStatus before boot');
        return planarReflectionStatus(app, requireEntity(id), cameraId === undefined ? 0 : requireEntity(cameraId));
    },

    resizeViewport(w: number, h: number): void {
        if (!canvas) throw new Error('resizeViewport before boot');
        canvas.width = w;
        canvas.height = h;
    },

    /** Boot the same partition and scene transactions used by cooked games and editor Play. */
    async loadStreamedWorld(scene: SceneData, name: string) {
        if (!app || !module || streamedSource) throw new Error('loadStreamedWorld requires a fresh host');
        const cut = cutWorld(scene, name, { entityFieldsOf: registryEntityFields() });
        if (!cut || cut.errors.length > 0) throw new Error(`Cannot partition world: ${cut?.errors.join('; ')}`);
        streamedSource = {
            backend: new HttpBackend({ baseUrl: '' }),
            decodePixels: async path => {
                const response = await fetch(path);
                if (!response.ok) throw new Error(`Texture fetch failed: ${response.status} ${path}`);
                return decodeImagePixels(await response.blob());
            },
        };
        await initRuntime({ app, module, source: streamedSource, firstScene: name,
            scenes: [{ name, data: cut.persistent }], worlds: [cut.manifest], cellDocuments: cut.documents });
        sourceToEntity = new Map(app.world.getAllEntities().flatMap(entity => {
            const id = stableEntityId(app!, entity);
            return id === undefined ? [] : [[id, entity] as [number, number]];
        }));
        return cut.manifest;
    },

    /** Replace the cell manifest while retaining the persistent scene and its sources. */
    async replaceStreamedWorld(scene: SceneData, name: string) {
        if (!app || !streamedSource) throw new Error('No streamed world is running');
        const streamer = app.getResource(WorldStreaming);
        const cut = cutWorld(scene, name, { entityFieldsOf: registryEntityFields() });
        if (!cut || cut.errors.length > 0 || !streamer.manifest) throw new Error('Cannot partition replacement world');
        cut.manifest.scene = streamer.manifest.scene;
        await streamer.loadManifest(cut.manifest, cell => {
            const config = createRuntimeSceneConfig(cell.name, cut.documents.get(cell.name),
                { app: app!, module, source: streamedSource! }, cell.path);
            config.externalEntities = () => persistentEntityRows(app!, cut.manifest);
            config.onPhase = (phase, ms) => streamer.recordPhase(cell.name, phase, ms);
            return config;
        });
        return cut.manifest;
    },

    clearWorldResidency: () => app!.getResource(WorldStreaming).clear(),

    worldResidencySnapshot() {
        return { ...worldResidencyReport(app!), assets: app!.getResource(Assets).sizes(),
            entities: app!.world.entityCount(), names: app!.world.getAllEntities().map(entity => app!.world.tryGet(entity, Name)?.value) };
    },

    /** 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 };
    },

    /** Waits for submitted shader variants without advancing the simulation clock. */
    waitForShaders: () => shadersCompiled(module),

    async warm(timeoutMs = 60000): Promise<{ frames: number; ms: number; pending: number; timedOut: boolean }> {
        if (!app) throw new Error('warm: no scene loaded');
        return warmShaders(app, { timeoutMs });
    },

    /** Uploads the native row-major placement records used by foliage and composite batches. */
    setMeshPlacements(id: number, values: number[]): void {
        if (!module?.meshInstances_set || values.length % 16 !== 0 || values.some(v => !Number.isFinite(v))) {
            throw new Error('setMeshPlacements: expected finite sixteen-float native records');
        }
        const entity = requireEntity(id);
        const instances = getComponent('MeshInstances');
        if (!instances) throw new Error('setMeshPlacements: MeshInstances is unavailable');
        if (!app!.world.has(entity, instances)) app!.world.insert(entity, instances, {});
        const data = new Float32Array(values);
        const ptr = module._malloc(Math.max(4, data.byteLength));
        if (!ptr) throw new Error('setMeshPlacements: allocation failed');
        try {
            new Float32Array(module.HEAPU8.buffer, ptr, data.length).set(data);
            module.meshInstances_set(app!.world.getCppRegistry()!, entity, ptr, values.length / 16);
        } finally {
            module._free(ptr);
        }
    },

    /**
     * The frame as the ENGINE holds it, whichever backend drew it. captureViewport
     * reads the page instead, which on WebGPU is a compositor copy — blank in a
     * hidden window. Null when the surface was not configured for readback, which
     * has to be decided before anything is drawn.
     */
    async captureViewportPixels(): Promise<{ rgba: Uint8Array; width: number; height: number } | null> {
        if (!canvas || !module) return null;
        return captureFramePixels(module, canvas.width, canvas.height, async () => { await api.step(1, 1 / 60); });
    },

    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,
        };
    },

    /**
     * The frame debugger's own claims, on this backend: a capture's reasons, and
     * how many pixels a replay through the first and through the last draw of a
     * pass paint. Painted is counted by alpha, which the replay clears to zero.
     */
    async frameDebug(): Promise<{
        draws: number; passes: number; breaks: Record<string, number>;
        first: number; last: number; differ: number | null; matches: boolean;
    } | null> {
        if (!module) return null;
        const next = async () => { await api.step(1, 1 / 60); };
        const cap = await captureFrame(module, next);
        if (!cap) return null;
        const breaks: Record<string, number> = {};
        for (const d of cap.drawCalls) {
            const name = BatchBreak[d.breakReason];
            breaks[name] = (breaks[name] ?? 0) + 1;
        }
        const pass = cap.drawCalls.filter((d) => d.pass === cap.drawCalls[0].pass);
        const a = await replayDraw(module, pass[0].index, next);
        const b = await replayDraw(module, pass[pass.length - 1].index, next);
        if (!a || !b) return null;
        const painted = (px: Uint8ClampedArray) => { let n = 0; for (let i = 3; i < px.length; i += 4) if (px[i] > 0) n++; return n; };
        let changed = 0;
        for (let i = 0; i < a.image.data.length; i += 4) {
            if (Math.abs(a.image.data[i] - b.image.data[i]) + Math.abs(a.image.data[i + 3] - b.image.data[i + 3]) > 16) changed++;
        }
        // A pass of one draw has no earlier draw to differ from.
        const differ = pass.length > 1 ? changed : null;
        return {
            draws: cap.drawCalls.length, passes: cap.passCount, breaks,
            first: painted(a.image.data), last: painted(b.image.data), differ,
            matches: a.matchesCapture && b.matchesCapture,
        };
    },

    /** Engages the engine's per-frame scopes and counters. Off by default, and
     *  asked for only by a gate that measures what a frame COST — the scopes are
     *  timed work the frames a pixel assertion looks at should not carry. */
    setCpuProfiling(on: boolean): void {
        module?.engine_setCpuProfiling?.(on);
    },

    /** The counters (ES_PROFILE_COUNTER) of the last completed frame. Empty until
     *  setCpuProfiling engages them, and empty for a counter that frame never set
     *  — an absent name is "this frame did none of that", not zero. */
    getCounters(): Record<string, number> {
        try {
            return JSON.parse(module?.engine_getCounters?.() ?? '{}') as Record<string, number>;
        } catch {
            return {};
        }
    },

    /** The GPU's time for a whole frame as a shipped game reads it — the number dynamic resolution steers by. -1 until
     *  the device has answered, and late in the same way as the scopes below. */
    getGpuTimeMs(): number {
        return module?.renderer_getGpuTimeMs?.() ?? -1;
    },

    /** What the GPU spent on the newest frame the device has answered for: `graph` and `pass/<name>`. The answer comes
     *  a few frames late and, on a browser, between tasks — a caller steps, waits, and asks again. */
    getGpuScopes(): Record<string, number> {
        try {
            return JSON.parse(module?.engine_getGpuScopes?.() ?? '{}') as Record<string, number>;
        } catch {
            return {};
        }
    },

    /** Records whole frames — TS system ms beside the engine's own C++ scope ms,
     *  which is the only pairing that says what SHARE of a frame is script.
     *  ProfileRecorder.start() engages both sides; engaging one reads as an
     *  engine that costs nothing rather than one that was not measured. */
    startProfile(): void {
        if (!app) throw new Error('startProfile: no app — load a scene first');
        profiler ??= new ProfileRecorder(app);
        profiler.start();
    },

    /** The frames recorded since startProfile, then stops recording. */
    takeProfile(): unknown {
        if (!profiler) return { frames: [] };
        const capture = profiler.take();
        profiler.stop();
        return capture;
    },

    /** 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.
     * @p z is optional so a flat caller keeps whatever depth the scene gave it.
     */
    setEntityXY(id: number, x: number, y: number, z?: number): void {
        const entity = requireEntity(id);
        const t = app!.world.get(entity, Transform);
        t.position.x = x;
        t.position.y = y;
        if (z !== undefined) t.position.z = z;
        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);
    },

    /** Adds or removes the real component so lifecycle checks use the shipped plugin. */
    setComponent(id: number, component: string, data: Record<string, unknown> | null): void {
        const entity = requireEntity(id);
        const definition = getComponent(component);
        if (!definition) throw new Error(`setComponent: no component named "${component}"`);
        if (data === null) app!.world.remove(entity, definition);
        else app!.world.insert(entity, definition, data);
    },

    setParent(id: number, parent: number): void {
        app!.world.setParent(requireEntity(id), requireEntity(parent));
    },

    refreshComposite(id: number): void {
        app!.getResource(CompositeBatchingRes).refresh(requireEntity(id));
    },

    compositeBatchReport(id: number) {
        const world = app!.world, root = requireEntity(id);
        const state = app!.getResource(CompositeBatchingRes);
        const children = world.tryGet(root, Children)?.entities ?? [];
        return {
            report: state.report(root), counts: { ...state.counts }, busy: state.busy_,
            component: world.tryGet(root, CompositeBatch),
            visibleParts: children.filter(entity => !world.has(entity, RuntimeOnly) && world.tryGet(entity, MeshRenderer)?.enabled).length,
            holders: children.filter(entity => world.has(entity, RuntimeOnly)).map(entity => ({
                name: world.tryGet(entity, Name)?.value, mesh: world.tryGet(entity, MeshRenderer)?.mesh,
                castShadows: world.tryGet(entity, MeshRenderer)?.castShadows,
            })),
        };
    },

    staticBatchReport() {
        const report = app!.getResource(StaticBatchingRes).report();
        return { refused: Array.from(report.refused), groups: report.groups.map(group => ({ ...group,
            partCount: group.parts.length,
            holderCastShadows: app!.world.tryGet(group.entity, MeshRenderer)?.castShadows,
            partCastShadows: group.parts.map(entity => app!.world.tryGet(entity, MeshRenderer)?.castShadows),
        })) };
    },

    /**
     * Writes one animator parameter, the door gameplay uses. Not setField: a
     * parameter is not a component field, it is per-entity state the controller
     * keeps, and a crossfade gate has no other way to make a transition fire.
     */
    setAnimatorParam(id: number, param: string, value: number | boolean): void {
        const entity = requireEntity(id);
        const ctrl = app!.getResource(AnimatorController);
        if (typeof value === 'boolean') ctrl.setBool(entity, param, value);
        else ctrl.setFloat(entity, param, value);
    },

    /**
     * What the animator on this entity actually resolved to. A crossfade gate
     * that only reads pixels cannot tell "the graph did not move" from "the
     * controller never loaded", and those want different fixes.
     */
    animatorReport(id: number): {
        controller: string; state: string; controllerLoaded: boolean;
        timelineDriver: boolean; clips: Record<string, boolean>;
    } {
        const entity = requireEntity(id);
        const def = getComponent('Animator');
        if (!def) throw new Error('animatorReport: this build has no Animator component');
        const data = app!.world.get(entity, def) as { controller: string; currentState: string };
        const ctrl = app!.getResource(AnimatorController);
        const graph = ctrl.getController(data.controller);
        const timeline = app!.getResource(Timeline);
        const clips: Record<string, boolean> = {};
        for (const state of graph?.states ?? []) {
            const clip = (state.motion as { clip?: string } | undefined)?.clip;
            if (clip) clips[clip] = !!timeline.getAsset(clip);
        }
        return {
            controller: data.controller,
            state: data.currentState,
            controllerLoaded: !!graph,
            timelineDriver: ctrl.hasMotionDriver('timeline'),
            clips,
        };
    },

    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));
    },

    /**
     * The editor's eye, which is an SDK resource and not an editor session: the
     * camera plugin inserts `EditorView` into every App, and `installEditorGrid`
     * draws through it. Seeded from the scene's own camera on the way on, as the
     * editor's door does, so a gate frames what the scene frames.
     */
    useEditorView(on: boolean): void {
        if (!app) throw new Error('use_editor_view before boot');
        const view = app.getResource(EditorView);
        if (on) seedEditorViewFromScene();
        view.active = on;
    },

    /** Turn the eye: yaw about world +Y, pitch above the ground, in degrees. */
    setViewOrbit(yaw: number, pitch: number): void {
        if (!app) throw new Error('set_view_orbit before boot');
        const view = app.getResource(EditorView);
        view.yaw = Number(yaw) || 0;
        view.pitch = Number(pitch) || 0;
    },

    /** Look at the scene as a 3D one, keeping the framing: the two projections
     *  zoom with different fields, so flipping the flag alone jumps the zoom. */
    setViewPerspective(on: boolean): void {
        if (!app) throw new Error('set_view_perspective before boot');
        const view = app.getResource(EditorView);
        if (view.perspective === on) return;
        const seen = editorViewHalfHeight(view);
        view.perspective = on;
        setEditorViewHalfHeight(view, seen);
    },

    /** The editor view's own lighting and exposure — view state, never part of the
     *  scene. Pass nothing to return to the game's own settings. The eye the frame
     *  is drawn through has to be the editor's, so this wakes it if it is asleep. */
    setViewLighting(spec?: Record<string, unknown>): void {
        if (!app) throw new Error('set_view_lighting before boot');
        const view = app.getResource(EditorView);
        if (!view.active) { seedEditorViewFromScene(); view.active = true; }
        const lighting = app.getResource(EditorViewLighting);
        if (!spec) { lighting.mode = 'scene'; lighting.exposure = 0; return; }
        Object.assign(lighting, spec);
    },

    /** How the editor view shades its meshes: 'shaded', 'clay' or 'albedo'. View state,
     *  like the lighting above, so it wakes the editor eye the frame is drawn through. */
    setViewShading(mode: 'shaded' | 'clay' | 'albedo'): void {
        if (!app) throw new Error('set_view_shading before boot');
        const view = app.getResource(EditorView);
        if (!view.active) { seedEditorViewFromScene(); view.active = true; }
        app.getResource(EditorViewShading).mode = mode;
    },

    /** Colour one skinned scene entity by how much a joint moves its vertices (null stops). */
    setSkinWeights(id: number | null, joint = 0): void {
        if (!app) throw new Error('set_skin_weights before boot');
        const view = app.getResource(EditorView);
        if (!view.active) { seedEditorViewFromScene(); view.active = true; }
        app.getResource(EditorViewShading).weights = id === null ? null : { entity: requireEntity(id) as number, joint };
    },

    /** The reference grid. Enabling seeds and activates the eye it draws through,
     *  because this host boots with that eye inactive. */
    setGrid(enabled: boolean, spacing?: number): void {
        if (!app) throw new Error('set_grid before boot');
        if (enabled) {
            seedEditorViewFromScene();
            app.getResource(EditorView).active = true;
        }
        const grid = app.getResource(EditorGrid);
        grid.enabled = enabled;
        if (spacing != null && Number(spacing) > 0) grid.spacing = Number(spacing);
    },

    // Editor doors, absent by design: these need an editor SESSION (a hit test
    // over the authoring model, the asset previews it renders), not a resource.
    pick: () => editorOnly('pick'),
    renderSceneMaterialPreview: () => editorOnly('render_scene_material_preview'),
    renderSceneMeshPreview: () => editorOnly('render_scene_mesh_preview'),
};

/**
 * Point the editor eye where the scene's own camera looks, at the extent it sees.
 * Not the camera's z: that is where its EYE stands, and adopting it as a focus
 * would put everything the camera frames behind the editor's own.
 */
function seedEditorViewFromScene(): void {
    if (!app) return;
    const view = app.getResource(EditorView);
    for (const e of app.world.getAllEntities()) {
        const cam = app.world.get(e, Camera) as { isActive?: boolean; orthoSize?: number } | undefined;
        if (!cam?.isActive) continue;
        const t = app.world.get(e, Transform) as { position?: { x: number; y: number } } | undefined;
        view.x = t?.position?.x ?? 0;
        view.y = t?.position?.y ?? 0;
        view.z = 0;
        if (cam.orthoSize) setEditorViewHalfHeight(view, cam.orthoSize);
        return;
    }
}

/** 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,
    clock: {
        state: () => ({ ...app!.getResource(Time), paused: app!.isPaused(), renderElapsed: app!.pipeline!.frameElapsed }),
        pause: (on: boolean) => app!.setPaused(on),
        scale: (value: number) => {
            if (!Number.isFinite(value) || value < 0) throw new Error('Clock scale must be finite and non-negative');
            app!.getResource(Time).scale = value;
        },
        step: (dt = 1 / 60) => app!.stepFrames(1, dt),
    },
    device: {
        status: () => getDeviceStatus(),
        report: () => getDeviceLostReport(),
        recover: () => recoverDevice(),
        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; content: number; path: string }) => `${t.handle}|${t.content}|${t.path}`),
        // Identity and realization apart, which a frame cannot show: a recovery
        // that minted fresh handles draws exactly like one that put the geometry
        // back behind the handles the world already points at.
        meshes: () => app?.getResource(Assets)?.meshRealizations() ?? [],
        // Readiness, which the device generation does not answer: whether the
        // programs that were ready before still are.
        programEpoch: () => (module as unknown as
            { renderer_programEpoch?(): number } | null)?.renderer_programEpoch?.() ?? -1,
        deviceGen: () => (module as unknown as
            { renderer_deviceGeneration?(): number } | null)?.renderer_deviceGeneration?.() ?? -1,
        meshesOwed: () => app?.getResource(Assets)?.meshesAwaitingRematerialization() ?? [],
        // 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. The device IN USE, not the one booted
            // with — after a recovery those differ.
            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 { meshRenderer_makeAllResident?(registry: unknown): number } | null;
        const registry = app?.world.getCppRegistry();
        if (!m?.meshRenderer_makeAllResident || !registry) return 0;
        return m.meshRenderer_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 { meshRenderer_setMeshAll?(registry: unknown, handle: number): number } | null;
        const registry = app?.world.getCppRegistry();
        if (!assets || !m?.meshRenderer_setMeshAll || !registry) return 0;
        const mesh = await assets.load<{ handle: number }>('mesh', path);
        if (!mesh?.handle) return 0;
        return m.meshRenderer_setMeshAll(registry, mesh.handle);
    },
    /**
     * Point a camera at an offscreen target and show that target on a sprite.
     * The whole claim in one hop: what the first camera drew has to arrive as the
     * second camera's texture, so the probe reads a colour that only exists
     * because a camera rendered somewhere other than the screen.
     */
    renderToTexture: (spec: {
        camera: number; sprite: number; width: number; height: number;
        /** Draw the target ONCE and stop, the way a game bakes a minimap. Only the
         *  deviceRestored event and RenderTexture.contentLost can bring it back. */
        once?: boolean;
    }) => {
        if (!app) return null;
        // By the order the scene lists them: a loaded entity's handle carries a
        // generation, so the ids in a scene file are not the World's.
        const loaded = [...app.world.getAllEntities()];
        const camEntity = loaded[spec.camera];
        const spriteEntity = loaded[spec.sprite];
        if (camEntity === undefined || spriteEntity === undefined) return { error: 'entity index out of range' };

        const rt = RenderTexture.create({ width: spec.width, height: spec.height, depth: true });
        const cam = app.world.get(camEntity, Camera) as { renderTarget: number };
        cam.renderTarget = rt._handle;
        app.world.insert(camEntity, Camera, cam as never);
        const sprite = app.world.get(spriteEntity, Sprite) as { texture: number };
        sprite.texture = rt.texture;
        app.world.insert(spriteEntity, Sprite, sprite as never);
        if (spec.once) {
            // What a game with baked content does: draw for a couple of frames,
            // then stop — and draw again when it is told the device came back.
            let framesLeft = 2;
            // Turned OFF, not re-pointed: a camera whose target is 0 draws to the
            // screen, which is not what "stopped baking" means.
            const bake = (on: boolean): void => {
                const c = app!.world.get(camEntity, Camera) as { renderTarget: number; isActive: boolean };
                c.renderTarget = rt._handle;
                c.isActive = on;
                app!.world.insert(camEntity, Camera, c as never);
            };
            app.addSystemToSchedule(Schedule.Last, defineSystem([], () => {
                if (framesLeft > 0 && --framesLeft === 0) {
                    bake(false);
                    RenderTexture.contentDrawn(rt);
                }
            }, { name: 'RenderTargetBakeStop' }));
            onDeviceRestored(() => {
                if (!RenderTexture.contentLost(rt)) return;
                bake(true);
                framesLeft = 2;
            });
        }
        return {
            target: rt._handle,
            texture: rt.texture,
            appliedTarget: (app.world.get(camEntity, Camera) as { renderTarget: number }).renderTarget,
            appliedTexture: (app.world.get(spriteEntity, Sprite) as { texture: number }).texture,
        };
    },
    loadMaterialAsset: async (path: string) => {
        const assets = app?.getResource(Assets);
        const m = module as unknown as { meshRenderer_setMaterialAll?(registry: unknown, id: number): number } | null;
        const registry = app?.world.getCppRegistry();
        if (!assets || !m?.meshRenderer_setMaterialAll || !registry) return 0;
        const material = await assets.load<{ handle: number }>('material', path);
        if (!material?.handle) return 0;
        return m.meshRenderer_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;