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(renderer): readying a prepared cell is a shipped capability, judging it is not

esenginec6c3083e18b4
diff --git a/bench/residency/readiness.mjs b/bench/residency/readiness.mjs
index 2073fc09b..db530743d 100644
--- a/bench/residency/readiness.mjs
+++ b/bench/residency/readiness.mjs
@@ -151,6 +151,8 @@ function drive(name, options) {
return readings;
}
+const digestOf = (r) => `${r.digestHi.toString(16)}${r.digestLo.toString(16).padStart(8, '0')}`;
+
const keySet = (r) => {
const keys = [];
for (let i = 0; i < 32; i++) {
@@ -184,15 +186,20 @@ function main() {
runs.set(name, r);
const doc = r.get('document');
const live = r.get('entities');
- const docKeys = keySet(doc);
const liveKeys = keySet(live);
- console.log(` ${name}: document {${docKeys.join(', ')}} in ${doc.ms.toFixed(2)} ms`
+ console.log(` ${name}: document ${digestOf(doc)} in ${doc.ms.toFixed(2)} ms`
+ ` (${doc.compiles} compile(s), ${doc.materialAsks} material ask(s));`
- + ` entities {${liveKeys.join(', ')}} in ${live.ms.toFixed(2)} ms`
+ + ` entities {${liveKeys.join(', ')}} ${digestOf(live)} in ${live.ms.toFixed(2)} ms`
+ ` (${live.compiles} compile(s), ${live.materialAsks} material ask(s))`);
- check(doc.keysLo === live.keysLo && doc.keysHi === live.keysHi,
+ // The digest, not the key set: production returns no keys — naming the
+ // variants is the oracle's job — and the digest is the stronger claim
+ // anyway, covering material programs the key set is silent about.
+ check(doc.digestLo === live.digestLo && doc.digestHi === live.digestHi,
`${name}: what the prepared cell knows equals what its entities ask for`,
- `{${docKeys.join(', ')}} against {${liveKeys.join(', ')}}`);
+ `${digestOf(doc)} against ${digestOf(live)}`);
+ check(doc.claimValid === 1,
+ `${name}: and the readying produced a claim — nothing moved underneath it`,
+ `claimValid=${doc.claimValid}`);
// The entity pass runs second, so what it still builds is what the
// document did not know about — and this is non-vacuous only if the
// document pass built something at all.
@@ -202,12 +209,6 @@ function main() {
check(live.compiles === 0,
`${name}: and readying from the document left nothing for them to compile`,
`${live.compiles} late compile(s)`);
- // The stamp, both halves: derived twice by different routes over the same
- // content, it has to name the same requirement set under the same epoch.
- check(doc.digestLo === live.digestLo && doc.digestHi === live.digestHi,
- `${name}: the requirement digest is the same from the document and the entities`,
- `${doc.digestHi.toString(16)}${doc.digestLo.toString(16)}`
- + ` against ${live.digestHi.toString(16)}${live.digestLo.toString(16)}`);
check(doc.programEpoch === live.programEpoch,
`${name}: and both were taken under the same program epoch`,
`${doc.programEpoch} against ${live.programEpoch}`);
@@ -219,9 +220,9 @@ function main() {
if (name === 'plain') {
// nothing fixture-specific: this one exists to be compared against.
} else if (name === 'shadow') {
- check(docKeys.some((k) => (k & 16) !== 0),
+ check(liveKeys.some((k) => (k & 16) !== 0),
'shadow: the depth-pass variant is a requirement, not a possibility',
- `keys {${docKeys.join(', ')}} — bit 16 is depthOnly`);
+ `keys {${liveKeys.join(', ')}} — bit 16 is depthOnly`);
} else {
check(doc.materialAsks > 0 && doc.materialAsks === live.materialAsks,
'material: the material-owned path is enumerated, and the same both ways',
@@ -234,8 +235,10 @@ function main() {
// The claim `keys` alone cannot make: same geometry, same stock variants, one
// shaded by a material. A digest blind to that path would call the two
// worlds identical and let a stamp from one vouch for the other.
- const plain = runs.get('plain').get('document');
- const shaded = runs.get('material').get('document');
+ // Read off the ORACLE side, which is the one that reports keys; the equality
+ // above has already tied each document's digest to its entities'.
+ const plain = runs.get('plain').get('entities');
+ const shaded = runs.get('material').get('entities');
console.log('');
check(plain.keysLo === shaded.keysLo && plain.keysHi === shaded.keysHi,
'the plain and material worlds need the SAME stock variants',
diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.ts
index 089178611..fd53a7540 100644
--- a/pipeline/src/runtime/gameHost.ts
+++ b/pipeline/src/runtime/gameHost.ts
@@ -142,6 +142,21 @@ async function boot(): Promise<void> {
if (headless) {
let statsOn = false;
const PREWARM_WORDS = 13;
+ const PREPARE_WORDS = 11;
+
+ /** Eleven words back from the production readying: whether a claim may be
+ * recorded at all, four counts, and the stamp with the generation that
+ * witnessed it. No key set — that is the oracle's job, not production's. */
+ const readPrepare = (heap: Uint32Array, ptr: number): Record<string, number> => {
+ const o = heap.subarray(ptr >> 2, (ptr >> 2) + PREPARE_WORDS);
+ return {
+ claimValid: o[0],
+ asks: o[1], compiles: o[2], materialAsks: o[3], materialCompiles: o[4],
+ digestLo: o[5], digestHi: o[6],
+ programEpoch: o[7] + o[8] * 0x100000000,
+ deviceGeneration: o[9] + o[10] * 0x100000000,
+ };
+ };
/** Thirteen words out: five counts, the stock key SET, the readiness stamp
* (digest over BOTH program paths plus the epoch it was taken under), and
* the device generation that guards it — never part of the claim itself. */
@@ -193,11 +208,11 @@ async function boot(): Promise<void> {
};
/**
- * The same readiness from the cell's DOCUMENT and the assets its preparation
- * decoded — no entity is consulted. Whether those facts SUFFICE is a claim
- * about the two derivations being equal, not about this call succeeding.
+ * The production path: readiness from the cell's DOCUMENT and the assets its
+ * preparation decoded, no entity consulted. Whether those facts SUFFICE is a
+ * claim about the two derivations agreeing, not about this call succeeding.
*/
- const prewarmMeshVariantsFromDocument = async (cell: string): Promise<Record<string, number>> => {
+ const prepareMeshPrograms = async (cell: string): Promise<Record<string, number>> => {
const found = worlds.flatMap((w) => w.cells).find((c) => c.name === cell);
if (!found) throw new Error(`[estella] no cooked cell "${cell}"`);
const doc = (await (await fetch(`./${found.path}`)).json()) as SceneData;
@@ -221,16 +236,16 @@ async function boot(): Promise<void> {
_malloc(n: number): number;
_free(p: number): void;
HEAPU32: Uint32Array;
- engine_prewarmMeshVariantsFromDocument(rowsPtr: number, count: number, outPtr: number): void;
+ engine_prepareMeshPrograms(rowsPtr: number, count: number, outPtr: number): void;
};
const rowsPtr = m._malloc(rows.length * 4);
- const outPtr = m._malloc(PREWARM_WORDS * 4);
+ const outPtr = m._malloc(PREPARE_WORDS * 4);
try {
m.HEAPU32.set(rows, rowsPtr >> 2);
const began = performance.now();
- m.engine_prewarmMeshVariantsFromDocument(rowsPtr, rows.length / 5, outPtr);
+ m.engine_prepareMeshPrograms(rowsPtr, rows.length / 5, outPtr);
const ms = performance.now() - began;
- return { ms, entities: rows.length / 5, ...readPrewarm(m.HEAPU32, outPtr) };
+ return { ms, entities: rows.length / 5, ...readPrepare(m.HEAPU32, outPtr) };
} finally {
m._free(rowsPtr);
m._free(outPtr);
@@ -631,14 +646,13 @@ async function boot(): Promise<void> {
return { changed: plan.changedAssets.length, applied: result.ok, failed: result.failed.length };
},
};
- // Registered only where the engine answers it. A release build exports no
- // test adapter, and a probe that existed there and threw would turn "this
- // build cannot do that" into a runtime error about something else.
- if (typeof (module as unknown as Record<string, unknown>).engine_prewarmMeshVariants
- === 'function') {
- cooked.prewarmMeshVariants = prewarmMeshVariants;
- cooked.prewarmMeshVariantsFromDocument = prewarmMeshVariantsFromDocument;
- }
+ // Each behind its OWN export. They are different ABIs now: readying a
+ // prepared cell ships, and deriving the same from live entities is the
+ // oracle that judges it and exists only in a probe build.
+ const has = (name: string): boolean =>
+ typeof (module as unknown as Record<string, unknown>)[name] === 'function';
+ if (has('engine_prepareMeshPrograms')) cooked.prepareMeshPrograms = prepareMeshPrograms;
+ if (has('engine_prewarmMeshVariants')) cooked.prewarmMeshVariants = prewarmMeshVariants;
(window as unknown as { __estellaCooked?: unknown }).__estellaCooked = cooked;
}
// physics.wasm sits next to esengine.wasm; the runtime loads it when a scene
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index b6487413a..68879c0d0 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -266,6 +266,7 @@ draw_textureRotated: (x: number, y: number, width: number, height: number, rotat
engine_getCounters: (() => string) | undefined
engine_getCpuScopes: (() => string) | undefined
engine_getGpuScopes: (() => string) | undefined
+engine_prepareMeshPrograms: ((rowsPtr: number, count: number, outPtr: number) => void) | undefined
engine_setCpuProfiling: ((on: boolean) => void) | undefined
engine_setRandomSeed: ((seed: number) => void) | undefined
environment_create: ((shPtr: number, specularHandle: number, faceSize: number, mipCount: number, maxRange: number) => number) | undefined
diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
index 6238b2d56..e78aced79 100644
--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts
@@ -45,6 +45,7 @@ export interface NativeEngineApi {
engine_getCounters?(): string;
engine_getCpuScopes?(): string;
engine_getGpuScopes?(): string;
+ engine_prepareMeshPrograms?(rowsPtr: number, count: number, outPtr: number): void;
engine_setCpuProfiling?(on: boolean): void;
engine_setRandomSeed?(seed: number): void;
environment_create?(shPtr: number, specularHandle: number, faceSize: number, mipCount: number, maxRange: number): number;
@@ -305,6 +306,7 @@ export function createNativeEngineApi(
bind('engine_getCounters', 'es_engine_getCounters', false);
bind('engine_getCpuScopes', 'es_engine_getCpuScopes', false);
bind('engine_getGpuScopes', 'es_engine_getGpuScopes', false);
+ bind('engine_prepareMeshPrograms', 'es_engine_prepareMeshPrograms', false);
bind('engine_setCpuProfiling', 'es_engine_setCpuProfiling', false);
bind('engine_setRandomSeed', 'es_engine_setRandomSeed', false);
bind('environment_create', 'es_environment_create', false);
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 7bc564c19..1df956f64 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -293,6 +293,13 @@ export interface ESEngineModule {
* Optional: absent on an older wasm build.
*/
renderer_deviceGeneration?(): number;
+ /**
+ * Ready the mesh programs a prepared cell requires, from its decoded document
+ * — no entity of it need exist, which is what preparing means. Eleven words
+ * out: claim-valid, four counts, the requirement digest, its epoch, and the
+ * device generation that witnessed it. Optional: absent on an older wasm.
+ */
+ engine_prepareMeshPrograms?(rowsPtr: number, count: number, outPtr: number): void;
/** Release a mesh and the buffers it owns. */
mesh_release?(meshHandle: number): void;
/**
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index 9fb7ccb37..919bf8aa1 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -821,6 +821,39 @@ std::string engine_getCpuScopes() {
return FrameProfiler::get().lastJson();
}
+void engine_prepareMeshPrograms(u32 rowsPtr, u32 count, u32 outPtr) {
+ auto* out = reinterpret_cast<u32*>(static_cast<uintptr_t>(outPtr));
+ for (u32 i = 0; i < 11; ++i) out[i] = 0;
+ if (!g_initialized || !g_renderFrame || !g_device) return;
+ const auto* rc = ctx().tryGet<RenderContext>();
+ if (!rc) return;
+
+ // Bracketed: a generation or epoch that moved underneath means neither
+ // reading describes the live renderer, so no claim is produced rather than
+ // one assembled out of two different worlds.
+ const u64 generationBefore = g_device->deviceGeneration();
+ const u64 epochBefore = rc->programEpoch();
+
+ const auto* rows = reinterpret_cast<const MeshDocumentRecord*>(static_cast<uintptr_t>(rowsPtr));
+ const RenderPrewarmResult r = g_renderFrame->prewarmDocument(rows, count);
+
+ const u64 generationAfter = g_device->deviceGeneration();
+ const u64 epochAfter = rc->programEpoch();
+
+ out[0] = (generationBefore == generationAfter && epochBefore == epochAfter) ? 1u : 0u;
+ out[1] = r.asks;
+ out[2] = r.compiles;
+ out[3] = r.materialAsks;
+ out[4] = r.materialCompiles;
+ const u64 digest = r.requirementDigest();
+ out[5] = static_cast<u32>(digest & 0xFFFFFFFFull);
+ out[6] = static_cast<u32>(digest >> 32);
+ out[7] = static_cast<u32>(epochAfter & 0xFFFFFFFFull);
+ out[8] = static_cast<u32>(epochAfter >> 32);
+ out[9] = static_cast<u32>(generationAfter & 0xFFFFFFFFull);
+ out[10] = static_cast<u32>(generationAfter >> 32);
+}
+
#ifdef ES_ENABLE_TEST_PROBES
/** Eleven words: five counts, the 64-bit stock key set, the requirement digest
* that also covers the material programs, and the epoch the digest was taken
@@ -856,13 +889,6 @@ void engine_prewarmMeshVariants(ecs::Registry& registry, u32 entitiesPtr, u32 co
writePrewarm(out, g_renderFrame->prewarmPrograms(registry, entities, count));
}
-void engine_prewarmMeshVariantsFromDocument(u32 rowsPtr, u32 count, u32 outPtr) {
- auto* out = reinterpret_cast<u32*>(static_cast<uintptr_t>(outPtr));
- for (u32 i = 0; i < 13; ++i) out[i] = 0;
- if (!g_initialized || !g_renderFrame) return;
- const auto* rows = reinterpret_cast<const MeshDocumentRecord*>(static_cast<uintptr_t>(rowsPtr));
- writePrewarm(out, g_renderFrame->prewarmDocument(rows, count));
-}
#endif
std::string engine_getCounters() {
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index f2acdcb7e..1125e163d 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -159,6 +159,14 @@ f64 renderer_programEpoch();
/** @brief Which generation of the GPU device is current. Not part of a readiness
* claim — the guard that says the claim was taken on one device. */
f64 renderer_deviceGeneration();
+
+/**
+ * @brief Readies the mesh programs a prepared cell requires, and reports what a
+ * readiness claim must record (layout in the .cpp).
+ * @details A generation or epoch that moves underneath voids the claim: one
+ * assembled from two reads of different worlds is worse than none.
+ */
+void engine_prepareMeshPrograms(u32 rowsPtr, u32 count, u32 outPtr);
void renderer_setClearColor(f32 r, f32 g, f32 b, f32 a);
void renderer_setViewport(i32 x, i32 y, i32 w, i32 h);
void renderer_setYSortLayers(u32 mask);
diff --git a/src/esengine/bindings/TestProbeBindings.hpp b/src/esengine/bindings/TestProbeBindings.hpp
index 1fc99332e..616762db4 100644
--- a/src/esengine/bindings/TestProbeBindings.hpp
+++ b/src/esengine/bindings/TestProbeBindings.hpp
@@ -23,17 +23,13 @@ namespace ecs { class Registry; }
/**
* @brief Ready the shader programs a set of entities will need, drawing none.
*
- * @details A disposable adapter over `RenderFrame::prewarmPrograms` — the only
- * gated part of shader readiness, the mechanism being ordinary renderer
- * code a production lifecycle would call directly. Writes seven counts
- * to @p outPtr; JSON here would put an allocation inside the measurement.
+ * @details The EQUIVALENCE oracle. Production readies a cell from its document
+ * (engine_prepareMeshPrograms) precisely because it has no entities
+ * yet; this derives the same requirements from live ones, so a test can
+ * judge the two against each other. Thirteen words to @p outPtr.
*/
void engine_prewarmMeshVariants(ecs::Registry& registry, u32 entitiesPtr, u32 count, u32 outPtr);
-/** @brief The same, from a prepared cell's own description — five words per
- * renderable at @p rowsPtr, and no entity of it need exist. */
-void engine_prewarmMeshVariantsFromDocument(u32 rowsPtr, u32 count, u32 outPtr);
-
} // namespace esengine
#endif
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 846d75b58..9d393de6f 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -727,14 +727,13 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("engine_getCpuScopes", &esengine::engine_getCpuScopes);
#ifdef ES_ENABLE_TEST_PROBES
emscripten::function("engine_prewarmMeshVariants", &esengine::engine_prewarmMeshVariants);
- emscripten::function("engine_prewarmMeshVariantsFromDocument",
- &esengine::engine_prewarmMeshVariantsFromDocument);
#endif
emscripten::function("engine_getCounters", &esengine::engine_getCounters);
emscripten::function("engine_getGpuScopes", &esengine::engine_getGpuScopes);
emscripten::function("renderer_getTextureBytes", &esengine::renderer_getTextureBytes);
emscripten::function("renderer_programEpoch", &esengine::renderer_programEpoch);
emscripten::function("renderer_deviceGeneration", &esengine::renderer_deviceGeneration);
+ emscripten::function("engine_prepareMeshPrograms", &esengine::engine_prepareMeshPrograms);
emscripten::function("renderer_setClearColor", &esengine::renderer_setClearColor);
emscripten::function("renderer_setViewport", &esengine::renderer_setViewport);
emscripten::function("renderer_setYSortLayers", &esengine::renderer_setYSortLayers);
diff --git a/tools/bindingDispositions.mjs b/tools/bindingDispositions.mjs
index f399b58e7..013109dbe 100644
--- a/tools/bindingDispositions.mjs
+++ b/tools/bindingDispositions.mjs
@@ -53,13 +53,9 @@ export const TEST_PROBE_BINDINGS = [
+ ' entities so a test can check them against what the prepared document'
+ ' derived. Production never has entities at that moment — the whole point'
+ ' of preparing a cell is that it is readied before it has any — so this'
- + ' side exists only to be the independent judge of the other.',
- },
- {
- id: 'engine_prewarmMeshVariantsFromDocument',
- why: 'the document-side derivation, still probe-only while the residency'
- + ' lifecycle calls it from nowhere. It is the half with a production'
- + ' consumer coming, so when preparation starts requiring a readiness'
- + ' stamp this row is what has to be removed rather than amended.',
+ + ' side exists only to be the independent judge of the other.'
+ + ' Its document-side twin left this census when it became'
+ + ' engine_prepareMeshPrograms, which is the shape of a probe that'
+ + ' earned a production consumer.',
},
];
diff --git a/tools/launchers/residency-run.mjs b/tools/launchers/residency-run.mjs
index f413d5541..3bbf4582e 100644
--- a/tools/launchers/residency-run.mjs
+++ b/tools/launchers/residency-run.mjs
@@ -244,10 +244,10 @@ async function main() {
// not built reads as "nothing needed compiling", which is the answer the
// experiment is trying to earn.
const has = await exec('typeof window.__estellaCooked.prewarmMeshVariants === "function"'
- + ' && typeof window.__estellaCooked.prewarmMeshVariantsFromDocument === "function"');
+ + ' && typeof window.__estellaCooked.prepareMeshPrograms === "function"');
if (!has) { stop(); server.close(); return fail('this build has no prewarm probe', 2); }
const call = step.from === 'document'
- ? `window.__estellaCooked.prewarmMeshVariantsFromDocument(${JSON.stringify(step.cell)})`
+ ? `window.__estellaCooked.prepareMeshPrograms(${JSON.stringify(step.cell)})`
: `window.__estellaCooked.prewarmMeshVariants(${JSON.stringify(step.cell)})`;
console.log(`prewarm ${step.as}: ${JSON.stringify(await exec(call))}`);
continue;