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): the engine returns its own pixels, so both backends are read alike

esengine604bf88a8f17
diff --git a/desktop/scripts/headless-verify.mjs b/desktop/scripts/headless-verify.mjs
index f953fc64d..d0f57f1d2 100644
--- a/desktop/scripts/headless-verify.mjs
+++ b/desktop/scripts/headless-verify.mjs
@@ -56,9 +56,9 @@ const DEPTH_LAYERS = process.env.ESTELLA_VERIFY_DEPTH_LAYERS ?? '';
// Headless / GPU-less (CI) WebGL2 falls back to SwiftShader; harmless with a GPU.
app.commandLine.appendSwitch('enable-unsafe-swiftshader');
-// capturePage returns DISPLAY-referred pixels: a page painting rgb(0,255,0)
-// captures as rgb(58,254,32) with this switch and without it, so a WebGPU
-// colour assertion needs an engine-side readback before it means anything.
+// Pins the profile for anything that goes through the compositor (a screenshot
+// for a human). The pixel assertions do not: a composited read is colour
+// managed, turning rgb(0,255,0) into rgb(58,254,32) switch or no switch.
app.commandLine.appendSwitch('force-color-profile', 'srgb');
// WebGPU: the unsafe flag covers non-default platforms (Linux CI); the optional
// software adapter (ESTELLA_VERIFY_WEBGPU_ADAPTER=swiftshader) gives GPU-less
@@ -270,60 +270,27 @@ app.whenReady().then(async () => {
})()`);
}
- // WebGPU: the engine has no synchronous readback (buffer maps are async)
- // and a hidden window never presents, so drawImage-style page readback is
- // blank — capture the PAGE instead (capturePage forces a composite; the
- // same technique the engine-parity runner uses). The canvas sits at the
- // page origin at its backing size, so the page pixels ARE the frame.
- // Converted to the RGBA bottom-up order of ViewportCapture so both
- // backends share the assertion math below.
- // NOT the same instrument as GL's: this composite is colour managed, so a
- // page painted rgb(0,255,0) reads back as rgb(58,254,32) and every colour
- // assertion carries that shift. Geometry is what it can answer.
- const grabWebGPU = async () => {
- const image = await win.webContents.capturePage({ x: 0, y: 0, width: W, height: H });
- const bmp = image.toBitmap(); // BGRA, top-down
- const { width, height } = image.getSize();
- const rgba = Buffer.alloc(width * height * 4);
- for (let y = 0; y < height; y++) {
- const srcRow = y * width * 4;
- const dstRow = (height - 1 - y) * width * 4;
- for (let x = 0; x < width; x++) {
- const s = srcRow + x * 4;
- const d = dstRow + x * 4;
- rgba[d] = bmp[s + 2];
- rgba[d + 1] = bmp[s + 1];
- rgba[d + 2] = bmp[s];
- rgba[d + 3] = bmp[s + 3];
- }
- }
- return { rgba, width, height };
- };
- const webgpuFrame = BACKEND === 'webgpu' ? await grabWebGPU() : null;
+ // Both backends are read the same way: the ENGINE's pixels, in the page.
+ // Reading the composited page instead answers what a display would show —
+ // rgb(0,255,0) comes back as rgb(58,254,32).
+ const readFrame = (expr) => exec(`(async () => {
+ const api = window.__estellaHeadless.api;
+ const c = (api.captureViewportPixels ? await api.captureViewportPixels() : null)
+ ?? api.captureViewport();
+ const px = c.rgba, w = c.width, h = c.height;
+ ${expr}
+ })()`);
- const captureStats = (rgba, width, height) => {
- const min = [255, 255, 255], max = [0, 0, 0];
- let nonZero = 0;
- for (let i = 0; i < rgba.length; i += 4) {
- for (let k = 0; k < 3; k++) { const v = rgba[i + k]; if (v < min[k]) min[k] = v; if (v > max[k]) max[k] = v; }
- if (rgba[i] | rgba[i + 1] | rgba[i + 2]) nonZero++;
- }
- const spread = (max[0] - min[0]) + (max[1] - min[1]) + (max[2] - min[2]);
- return { w: width, h: height, totalPixels: rgba.length / 4, nonZeroPixels: nonZero, min, max, spread, rendered: spread > 16 };
- };
- const capture = webgpuFrame
- ? captureStats(webgpuFrame.rgba, webgpuFrame.width, webgpuFrame.height)
- : await exec(`(() => {
- const c = window.__estellaHeadless.api.captureViewport();
- const px = c.rgba; const min = [255, 255, 255], max = [0, 0, 0]; let nonZero = 0;
+ const capture = await readFrame(`
+ const min = [255, 255, 255], max = [0, 0, 0]; let nonZero = 0;
for (let i = 0; i < px.length; i += 4) {
for (let k = 0; k < 3; k++) { const v = px[i + k]; if (v < min[k]) min[k] = v; if (v > max[k]) max[k] = v; }
if (px[i] | px[i + 1] | px[i + 2]) nonZero++;
}
const spread = (max[0] - min[0]) + (max[1] - min[1]) + (max[2] - min[2]);
- return { w: c.width, h: c.height, totalPixels: px.length / 4, nonZeroPixels: nonZero, min, max, spread, rendered: spread > 16 };
- })()`);
+ return { w, h, totalPixels: px.length / 4, nonZeroPixels: nonZero, min, max, spread, rendered: spread > 16 };
+ `);
const drawCalls = await exec('window.__estellaHeadless.api.getStats().drawCalls');
// Optional color/orientation assertion: ESTELLA_VERIFY_EXPECT is a JSON array of
// { x, y, rgb:[r,g,b], tol? } where x,y are normalized [0,1] from the TOP-LEFT.
@@ -331,52 +298,30 @@ app.whenReady().then(async () => {
// (TextureLoader imageOrientation) — `rendered` (color variation) alone misses it.
let expect = null;
if (process.env.ESTELLA_VERIFY_EXPECT) {
- const points = JSON.parse(process.env.ESTELLA_VERIFY_EXPECT);
- const evaluate = (rgba, w, h) => {
- const out = points.map((p) => {
- const px = Math.round(p.x * (w - 1));
- const glRow = (h - 1) - Math.round(p.y * (h - 1)); // capture rows are bottom-up
- const i = (glRow * w + px) * 4;
- const got = [rgba[i], rgba[i + 1], rgba[i + 2]];
- const tol = p.tol ?? 24;
- const ok = got.every((g, k) => Math.abs(g - p.rgb[k]) <= tol);
- return { x: p.x, y: p.y, want: p.rgb, got, ok };
- });
- return { points: out, ok: out.every((o) => o.ok) };
- };
- expect = webgpuFrame
- ? evaluate(webgpuFrame.rgba, webgpuFrame.width, webgpuFrame.height)
- : await exec(`(() => {
- const pts = ${JSON.stringify(points)};
- const c = window.__estellaHeadless.api.captureViewport();
- const { width: w, height: h, rgba } = c;
+ expect = await readFrame(`
+ const pts = ${JSON.stringify(JSON.parse(process.env.ESTELLA_VERIFY_EXPECT))};
const out = pts.map((p) => {
- const px = Math.round(p.x * (w - 1));
- const glRow = (h - 1) - Math.round(p.y * (h - 1)); // GL readback is bottom-up
- const i = (glRow * w + px) * 4;
- const got = [rgba[i], rgba[i + 1], rgba[i + 2]];
+ const pxX = Math.round(p.x * (w - 1));
+ const row = (h - 1) - Math.round(p.y * (h - 1)); // readback rows are bottom-up
+ const i = (row * w + pxX) * 4;
+ const got = [px[i], px[i + 1], px[i + 2]];
const tol = p.tol ?? 24;
const ok = got.every((g, k) => Math.abs(g - p.rgb[k]) <= tol);
return { x: p.x, y: p.y, want: p.rgb, got, ok };
});
return { points: out, ok: out.every((o) => o.ok) };
- })()`);
+ `);
}
// Optional PNG dump (ESTELLA_VERIFY_OUT) of the engine framebuffer (not the
// page) so the rendered frame can be eyeballed. GL readback is bottom-up → flip.
- if (process.env.ESTELLA_VERIFY_OUT && BACKEND === 'webgpu') {
- const image = await win.webContents.capturePage({ x: 0, y: 0, width: W, height: H });
- await writeFile(process.env.ESTELLA_VERIFY_OUT, image.toPNG());
- } else if (process.env.ESTELLA_VERIFY_OUT) {
- const dataUrl = await exec(`(() => {
- const c = window.__estellaHeadless.api.captureViewport();
- const cv = document.createElement('canvas'); cv.width = c.width; cv.height = c.height;
- const ctx = cv.getContext('2d'); const img = ctx.createImageData(c.width, c.height);
- const w = c.width, h = c.height, src = c.rgba;
- for (let y = 0; y < h; y++) { const sy = (h - 1 - y) * w * 4; img.data.set(src.subarray(sy, sy + w * 4), y * w * 4); }
+ if (process.env.ESTELLA_VERIFY_OUT) {
+ const dataUrl = await readFrame(`
+ const cv = document.createElement('canvas'); cv.width = w; cv.height = h;
+ const ctx = cv.getContext('2d'); const img = ctx.createImageData(w, h);
+ for (let y = 0; y < h; y++) { const sy = (h - 1 - y) * w * 4; img.data.set(px.subarray(sy, sy + w * 4), y * w * 4); }
ctx.putImageData(img, 0, 0);
return cv.toDataURL('image/png');
- })()`);
+ `);
await writeFile(process.env.ESTELLA_VERIFY_OUT, Buffer.from(dataUrl.split(',')[1], 'base64'));
}
// Optional resize assertion (ESTELLA_VERIFY_RESIZE = "WxH"): shrink the
@@ -387,20 +332,11 @@ app.whenReady().then(async () => {
const [rw, rh] = process.env.ESTELLA_VERIFY_RESIZE.split('x').map(Number);
await exec(`window.__estellaHeadless.api.resizeViewport(${rw}, ${rh})`);
await exec('window.__estellaHeadless.api.step(2, 1 / 60)');
- if (BACKEND === 'webgpu') {
- const image = await win.webContents.capturePage({ x: 0, y: 0, width: rw, height: rh });
- const bmp = image.toBitmap();
+ resize = await readFrame(`
let nonZero = 0;
- for (let i = 0; i < bmp.length; i += 4) if (bmp[i] | bmp[i + 1] | bmp[i + 2]) nonZero++;
- resize = { w: rw, h: rh, nonZeroPixels: nonZero, ok: nonZero > 0 };
- } else {
- resize = await exec(`(() => {
- const c = window.__estellaHeadless.api.captureViewport();
- let nonZero = 0;
- for (let i = 0; i < c.rgba.length; i += 4) if (c.rgba[i] | c.rgba[i + 1] | c.rgba[i + 2]) nonZero++;
- return { w: c.width, h: c.height, nonZeroPixels: nonZero, ok: c.width === ${rw} && c.height === ${rh} && nonZero > 0 };
- })()`);
- }
+ for (let i = 0; i < px.length; i += 4) if (px[i] | px[i + 1] | px[i + 2]) nonZero++;
+ return { w, h, nonZeroPixels: nonZero, ok: w === ${rw} && h === ${rh} && nonZero > 0 };
+ `);
}
// Optional offscreen material-preview assertion (ESTELLA_VERIFY_PREVIEW =
// {w,h,rgb:[r,g,b],tol?}): renders a scene material to an offscreen target and checks the
@@ -434,47 +370,28 @@ app.whenReady().then(async () => {
// Optional PNG of the grid-on frame (ESTELLA_VERIFY_GRID_OUT) for eyeballing.
// Same per-backend readback split as ESTELLA_VERIFY_OUT (GL page capture of a
// hidden window never composites — read the framebuffer in-page instead).
- if (process.env.ESTELLA_VERIFY_GRID_OUT && BACKEND === 'webgpu') {
- const image = await win.webContents.capturePage({ x: 0, y: 0, width: W, height: H });
- await writeFile(process.env.ESTELLA_VERIFY_GRID_OUT, image.toPNG());
- } else if (process.env.ESTELLA_VERIFY_GRID_OUT) {
- const dataUrl = await exec(`(() => {
- const c = window.__estellaHeadless.api.captureViewport();
- const cv = document.createElement('canvas'); cv.width = c.width; cv.height = c.height;
- const ctx = cv.getContext('2d'); const img = ctx.createImageData(c.width, c.height);
- const w = c.width, h = c.height, src = c.rgba;
- for (let y = 0; y < h; y++) { const sy = (h - 1 - y) * w * 4; img.data.set(src.subarray(sy, sy + w * 4), y * w * 4); }
+ if (process.env.ESTELLA_VERIFY_GRID_OUT) {
+ const dataUrl = await readFrame(`
+ const cv = document.createElement('canvas'); cv.width = w; cv.height = h;
+ const ctx = cv.getContext('2d'); const img = ctx.createImageData(w, h);
+ for (let y = 0; y < h; y++) { const sy = (h - 1 - y) * w * 4; img.data.set(px.subarray(sy, sy + w * 4), y * w * 4); }
ctx.putImageData(img, 0, 0);
return cv.toDataURL('image/png');
- })()`);
+ `);
await writeFile(process.env.ESTELLA_VERIFY_GRID_OUT, Buffer.from(dataUrl.split(',')[1], 'base64'));
}
- if (BACKEND === 'webgpu') {
- const on = (await grabWebGPU()).rgba;
- await exec('window.__estellaHeadless.api.setGrid(false)');
- await exec('window.__estellaHeadless.api.step(2, 1 / 60)');
- const off = (await grabWebGPU()).rgba;
+ await readFrame('window.__estellaGridOn = px.slice(); return true;');
+ await exec('window.__estellaHeadless.api.setGrid(false)');
+ await exec('window.__estellaHeadless.api.step(2, 1 / 60)');
+ grid = await readFrame(`
+ const on = window.__estellaGridOn;
let differing = 0;
for (let i = 0; i < on.length; i += 4) {
- const d = Math.abs(on[i] - off[i]) + Math.abs(on[i + 1] - off[i + 1]) + Math.abs(on[i + 2] - off[i + 2]);
+ const d = Math.abs(on[i] - px[i]) + Math.abs(on[i + 1] - px[i + 1]) + Math.abs(on[i + 2] - px[i + 2]);
if (d > 12) differing++;
}
- grid = { differingPixels: differing, ok: differing > 300 };
- } else {
- await exec('window.__estellaGridOn = window.__estellaHeadless.api.captureViewport().rgba.slice()');
- await exec('window.__estellaHeadless.api.setGrid(false)');
- await exec('window.__estellaHeadless.api.step(2, 1 / 60)');
- grid = await exec(`(() => {
- const off = window.__estellaHeadless.api.captureViewport().rgba;
- const on = window.__estellaGridOn;
- let differing = 0;
- for (let i = 0; i < on.length; i += 4) {
- const d = Math.abs(on[i] - off[i]) + Math.abs(on[i + 1] - off[i + 1]) + Math.abs(on[i + 2] - off[i + 2]);
- if (d > 12) differing++;
- }
- return { differingPixels: differing, ok: differing > 300 };
- })()`);
- }
+ return { differingPixels: differing, ok: differing > 300 };
+ `);
}
finish({ ok: true, entityCount, drawCalls, capture, expect, resize, preview, grid, deviceLoss }, server);
} catch (e) {
diff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.ts
index 2922d905f..fa0e7cf7a 100644
--- a/desktop/src/engine/EditorControlSurface.ts
+++ b/desktop/src/engine/EditorControlSurface.ts
@@ -30,7 +30,7 @@ import { EngineHost } from './EngineHost';
import { isRequiredEmpty, componentByName, userSchema, coerceEnumInput, componentAuthorability, inspectorFields, modelAddableComponentEntries } from './schema';
import { ViewportController } from './ViewportController';
import { PerfMonitor, type PerfSnapshot, type FrameSample } from './PerfMonitor';
-import { parseProfileCapture, summarizeCapture, frameProfileOf } from 'esengine';
+import { parseProfileCapture, summarizeCapture, frameProfileOf, captureFramePixels } from 'esengine';
import type { ProfileCapture, CapturedFrame } from 'esengine';
import { profileReportOf, type ProfileReport } from './profileReport';
import type { SceneCommandsImpl, EditorTransaction } from './SceneCommands';
@@ -887,6 +887,19 @@ export class EditorControlSurfaceImpl {
EngineHost.setGrid(enabled, spacing);
}
+ /**
+ * 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, colour managed everywhere else. Null when the surface was not
+ * configured for readback, which has to be decided before anything is drawn.
+ */
+ async captureViewportPixels(): Promise<ViewportCapture | null> {
+ const canvas = EngineHost.canvas;
+ const module = EngineHost.module;
+ if (!canvas || !module) return null;
+ return captureFramePixels(module, canvas.width, canvas.height, async () => { await this.step(1, 1 / 60); });
+ }
+
captureViewport(): ViewportCapture {
const canvas = EngineHost.canvas;
if (!canvas) {
diff --git a/desktop/src/engine/EngineHost.ts b/desktop/src/engine/EngineHost.ts
index eb004ec8d..c42d2d2d0 100644
--- a/desktop/src/engine/EngineHost.ts
+++ b/desktop/src/engine/EngineHost.ts
@@ -673,7 +673,10 @@ class EngineHostImpl {
// WebGPU hands the engine the whole canvas swapchain via the injected device
// (canvas resolved by selector); WebGL2 binds the context we registered above.
const renderSurface: RenderSurfaceSource = backend === 'webgpu'
- ? { kind: 'webgpu', canvasSelector: `#${canvas.id}` }
+ // readback: the editor reads its own frames back (screenshots, the
+ // automation surface, the pixel gates) — the WebGPU counterpart of
+ // preserveDrawingBuffer above, fixed at configure time.
+ ? { kind: 'webgpu', canvasSelector: `#${canvas.id}`, readback: true }
: { kind: 'gl-context', handle: glHandle! };
const app = await bootProfiler.phase('createWebApp', () => createWebApp(module, {
renderSurface,
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 5f4321eac..3c7d39d20 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -2,11 +2,11 @@
"note": "Generated by tools/api-stability.mjs from sdk/etc/*.api.md — do not edit.",
"counts": {
"public": 113,
- "beta": 60,
- "experimental": 1508,
+ "beta": 61,
+ "experimental": 1510,
"deprecated": 3
},
- "total": 1681,
+ "total": 1684,
"subsystems": [
{
"id": "ecs",
@@ -2188,6 +2188,18 @@
"minigame"
]
},
+ {
+ "name": "captureFramePixels",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "compileMaterialGraph",
"kind": "function",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 18b862cdb..f2ec97404 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 53 beta · 1393 experimental · 3 deprecated
+Symbols: 113 public · 54 beta · 1395 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -3069,6 +3069,13 @@ static new (capacity?: number): FrameHistory
static prototype: FrameHistory
```
+## FramePixels — interface @experimental
+```
+height: number
+rgba: Uint8Array<ArrayBufferLike>
+width: number
+```
+
## FrameProfile — interface @experimental
```
cpuMs: number
@@ -5728,7 +5735,13 @@ triangles: number
## RenderSurfaceSource — type @experimental
```
| { readonly kind: 'gl-context'; readonly handle: number }
- | { readonly kind: 'webgpu'; readonly canvasSelector?: string }
+ | {
+ readonly kind: 'webgpu';
+ readonly canvasSelector?: string;
+ /** Configure the swapchain so the engine can read its own frames back
+ * (`captureFrame`). Fixed at surface configuration, hence here. */
+ readonly readback?: boolean;
+ }
| { readonly kind: 'default' }
```
@@ -8995,6 +9008,11 @@ BtPlugin
(sourceX: number, sourceY: number, listenerX: number, listenerY: number, maxDistance: number): number
```
+## canCaptureFramePixels — function @experimental
+```
+(module: ESEngineModule): boolean
+```
+
## canHaveChildren — function @experimental
```
(type: BtNodeType): boolean
@@ -9005,6 +9023,11 @@ BtPlugin
(mode: TerrainMode, mask: number): number
```
+## captureFramePixels — function @beta
+```
+(module: ESEngineModule, width: number, height: number, advance?: () => void | Promise<void>): Promise<FramePixels | null>
+```
+
## catalogFromManifest — function @experimental
```
(manifest: AddressableManifest): Catalog | undefined
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 5f8913fbd..9c876cada 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 58 beta · 1412 experimental · 3 deprecated
+Symbols: 113 public · 59 beta · 1414 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -3077,6 +3077,13 @@ static new (capacity?: number): FrameHistory
static prototype: FrameHistory
```
+## FramePixels — interface @experimental
+```
+height: number
+rgba: Uint8Array<ArrayBufferLike>
+width: number
+```
+
## FrameProfile — interface @experimental
```
cpuMs: number
@@ -5921,7 +5928,13 @@ triangles: number
## RenderSurfaceSource — type @experimental
```
| { readonly kind: 'gl-context'; readonly handle: number }
- | { readonly kind: 'webgpu'; readonly canvasSelector?: string }
+ | {
+ readonly kind: 'webgpu';
+ readonly canvasSelector?: string;
+ /** Configure the swapchain so the engine can read its own frames back
+ * (`captureFrame`). Fixed at surface configuration, hence here. */
+ readonly readback?: boolean;
+ }
| { readonly kind: 'default' }
```
@@ -9203,6 +9216,11 @@ BtPlugin
(sourceX: number, sourceY: number, listenerX: number, listenerY: number, maxDistance: number): number
```
+## canCaptureFramePixels — function @experimental
+```
+(module: ESEngineModule): boolean
+```
+
## canHaveChildren — function @experimental
```
(type: BtNodeType): boolean
@@ -9213,6 +9231,11 @@ BtPlugin
(mode: TerrainMode, mask: number): number
```
+## captureFramePixels — function @beta
+```
+(module: ESEngineModule, width: number, height: number, advance?: () => void | Promise<void>): Promise<FramePixels | null>
+```
+
## catalogFromManifest — function @experimental
```
(manifest: AddressableManifest): Catalog | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index cbb3d258c..568b738ca 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 55 beta · 1392 experimental · 3 deprecated
+Symbols: 113 public · 56 beta · 1394 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3064,6 +3064,13 @@ static new (capacity?: number): FrameHistory
static prototype: FrameHistory
```
+## FramePixels — interface @experimental
+```
+height: number
+rgba: Uint8Array<ArrayBufferLike>
+width: number
+```
+
## FrameProfile — interface @experimental
```
cpuMs: number
@@ -5723,7 +5730,13 @@ triangles: number
## RenderSurfaceSource — type @experimental
```
| { readonly kind: 'gl-context'; readonly handle: number }
- | { readonly kind: 'webgpu'; readonly canvasSelector?: string }
+ | {
+ readonly kind: 'webgpu';
+ readonly canvasSelector?: string;
+ /** Configure the swapchain so the engine can read its own frames back
+ * (`captureFrame`). Fixed at surface configuration, hence here. */
+ readonly readback?: boolean;
+ }
| { readonly kind: 'default' }
```
@@ -8990,6 +9003,11 @@ BtPlugin
(sourceX: number, sourceY: number, listenerX: number, listenerY: number, maxDistance: number): number
```
+## canCaptureFramePixels — function @experimental
+```
+(module: ESEngineModule): boolean
+```
+
## canHaveChildren — function @experimental
```
(type: BtNodeType): boolean
@@ -9000,6 +9018,11 @@ BtPlugin
(mode: TerrainMode, mask: number): number
```
+## captureFramePixels — function @beta
+```
+(module: ESEngineModule, width: number, height: number, advance?: () => void | Promise<void>): Promise<FramePixels | null>
+```
+
## catalogFromManifest — function @experimental
```
(manifest: AddressableManifest): Catalog | undefined
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 3acc32680..15faebd51 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 53 beta · 1413 experimental · 3 deprecated
+Symbols: 113 public · 54 beta · 1415 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3064,6 +3064,13 @@ static new (capacity?: number): FrameHistory
static prototype: FrameHistory
```
+## FramePixels — interface @experimental
+```
+height: number
+rgba: Uint8Array<ArrayBufferLike>
+width: number
+```
+
## FrameProfile — interface @experimental
```
cpuMs: number
@@ -5968,7 +5975,13 @@ triangles: number
## RenderSurfaceSource — type @experimental
```
| { readonly kind: 'gl-context'; readonly handle: number }
- | { readonly kind: 'webgpu'; readonly canvasSelector?: string }
+ | {
+ readonly kind: 'webgpu';
+ readonly canvasSelector?: string;
+ /** Configure the swapchain so the engine can read its own frames back
+ * (`captureFrame`). Fixed at surface configuration, hence here. */
+ readonly readback?: boolean;
+ }
| { readonly kind: 'default' }
```
@@ -9235,6 +9248,11 @@ BtPlugin
(sourceX: number, sourceY: number, listenerX: number, listenerY: number, maxDistance: number): number
```
+## canCaptureFramePixels — function @experimental
+```
+(module: ESEngineModule): boolean
+```
+
## canHaveChildren — function @experimental
```
(type: BtNodeType): boolean
@@ -9245,6 +9263,11 @@ BtPlugin
(mode: TerrainMode, mask: number): number
```
+## captureFramePixels — function @beta
+```
+(module: ESEngineModule, width: number, height: number, advance?: () => void | Promise<void>): Promise<FramePixels | null>
+```
+
## catalogFromManifest — function @experimental
```
(manifest: AddressableManifest): Catalog | undefined
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 8396da0ea..05db2206b 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -245,7 +245,7 @@ getVelocityPtr: (registry: CppRegistry, entity: number) => number
gl_checkErrors: (context: string) => number
gl_enableErrorCheck: (enabled: boolean) => void
initRenderer: () => void
-initRendererWebGPU: (canvasSelector: string, width: number, height: number) => boolean
+initRendererWebGPU: (canvasSelector: string, width: number, height: number, readback: boolean) => boolean
initRendererWithCanvas: (canvasSelector: string) => boolean
initRendererWithContext: (contextHandle: number) => boolean
markDeviceRestored: (() => void) | undefined
@@ -299,6 +299,7 @@ renderFrame: (registry: CppRegistry, width: number, height: number) => void
renderFrameWithMatrix: (registry: CppRegistry, width: number, height: number, matrixPtr: number) => void
renderer_begin: (matrixPtr: number, targetHandle: number, clearFlags: number, r: number, g: number, b: number, a: number, clearX: number, clearY: number, clearW: number, clearH: number) => void
renderer_beginFrame: (elapsedSec: number) => void
+renderer_captureFrame: ((w: number, h: number) => number) | undefined
renderer_captureNextFrame: () => void
renderer_clearAllClipRects: () => void
renderer_clearAllStencilMasks: () => void
@@ -335,6 +336,7 @@ renderer_getTextureBytes: (() => number) | undefined
renderer_getTriangles: () => number
renderer_hasCapturedData: () => boolean
renderer_init: (width: number, height: number) => void
+renderer_pollFrameCapture: ((handle: number) => number) | undefined
renderer_pollPreviewReadback: () => number
renderer_pollSnapshotReadback: () => number
renderer_releaseTarget: (handle: number) => void
@@ -363,6 +365,7 @@ renderer_submitSpineBatch: ((verticesPtr: number, vertexCount: number, indicesPt
renderer_submitSprites: (registry: CppRegistry) => void
renderer_submitTextBatch: ((verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, transformPtr: number, entity: number, layer: number, depth: number, sdf: number, cullBit: number) => void) | undefined
renderer_submitUIElements: (registry: CppRegistry) => void
+renderer_takeFrameCapture: ((handle: number, dest: number, destSize: number) => boolean) | undefined
renderer_updateTransforms: (registry: CppRegistry) => void
sdfFromAlpha: ((alphaPtr: number, outPtr: number, width: number, height: number, spread: number) => void) | undefined
setActiveContext: (ctx: CppEngineContext | null) => void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 8294fa2c0..c3fce8c18 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 53 beta · 1403 experimental · 3 deprecated
+Symbols: 113 public · 54 beta · 1405 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -3064,6 +3064,13 @@ static new (capacity?: number): FrameHistory
static prototype: FrameHistory
```
+## FramePixels — interface @experimental
+```
+height: number
+rgba: Uint8Array<ArrayBufferLike>
+width: number
+```
+
## FrameProfile — interface @experimental
```
cpuMs: number
@@ -5730,7 +5737,13 @@ triangles: number
## RenderSurfaceSource — type @experimental
```
| { readonly kind: 'gl-context'; readonly handle: number }
- | { readonly kind: 'webgpu'; readonly canvasSelector?: string }
+ | {
+ readonly kind: 'webgpu';
+ readonly canvasSelector?: string;
+ /** Configure the swapchain so the engine can read its own frames back
+ * (`captureFrame`). Fixed at surface configuration, hence here. */
+ readonly readback?: boolean;
+ }
| { readonly kind: 'default' }
```
@@ -9017,6 +9030,11 @@ BtPlugin
(sourceX: number, sourceY: number, listenerX: number, listenerY: number, maxDistance: number): number
```
+## canCaptureFramePixels — function @experimental
+```
+(module: ESEngineModule): boolean
+```
+
## canHaveChildren — function @experimental
```
(type: BtNodeType): boolean
@@ -9027,6 +9045,11 @@ BtPlugin
(mode: TerrainMode, mask: number): number
```
+## captureFramePixels — function @beta
+```
+(module: ESEngineModule, width: number, height: number, advance?: () => void | Promise<void>): Promise<FramePixels | null>
+```
+
## catalogFromManifest — function @experimental
```
(manifest: AddressableManifest): Catalog | undefined
diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.ts
index c7ef1ff90..f6efe6221 100644
--- a/sdk/src/app/app.ts
+++ b/sdk/src/app/app.ts
@@ -1299,7 +1299,13 @@ export class App {
*/
export type RenderSurfaceSource =
| { readonly kind: 'gl-context'; readonly handle: number }
- | { readonly kind: 'webgpu'; readonly canvasSelector?: string }
+ | {
+ readonly kind: 'webgpu';
+ readonly canvasSelector?: string;
+ /** Configure the swapchain so the engine can read its own frames back
+ * (`captureFrame`). Fixed at surface configuration, hence here. */
+ readonly readback?: boolean;
+ }
| { readonly kind: 'default' };
export interface WebAppOptions {
@@ -1372,7 +1378,8 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): A
switch (surface.kind) {
case 'webgpu': {
const size = options?.getViewportSize?.() ?? { width: 800, height: 600 };
- if (!module.initRendererWebGPU(surface.canvasSelector ?? '#canvas', size.width, size.height)) {
+ if (!module.initRendererWebGPU(
+ surface.canvasSelector ?? '#canvas', size.width, size.height, surface.readback === true)) {
throw new Error(
'WebGPU renderer initialization failed — the module needs a ' +
'preinitializedWebGPUDevice and a WebGPU-enabled engine build.');
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index d19a22425..68e7ab9b5 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -180,6 +180,18 @@ export {
getContextLossGuardInfo,
} from './render/renderer';
+/**
+ * What the engine drew, from the backend that drew it — so a capture is not the
+ * display's opinion of the frame.
+ *
+ * @beta Pre-1.0: the frame-advance callback may become a schedule hook.
+ */
+export {
+ captureFramePixels,
+ canCaptureFramePixels,
+ type FramePixels,
+} from './render/framePixels';
+
export {
LayerOrder,
layerOrderOf,
diff --git a/sdk/src/render/framePixels.ts b/sdk/src/render/framePixels.ts
new file mode 100644
index 000000000..fa2dd2257
--- /dev/null
+++ b/sdk/src/render/framePixels.ts
@@ -0,0 +1,74 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Asking the engine what it drew.
+ *
+ * One answer for both backends, from the side that holds the pixels — a
+ * host that reads the page instead gets the DISPLAY's answer, colour
+ * managed on a wide-gamut machine, so a frame painting rgb(0,255,0) reads
+ * back as rgb(58,254,32) with nothing rendered wrong.
+ *
+ * GL serves the request on the spot. WebGPU books the copy for the end of
+ * its own frame, so the caller has to let a frame happen: that is what
+ * `advance` is for, and it is the whole difference between the backends.
+ */
+import { awaitReadback, READBACK_READY } from './readback';
+import { withScratch } from '../wasm/wasmScratch';
+import type { ESEngineModule } from '../wasm';
+
+/** Pixels as every capture consumer expects them: RGBA, rows bottom-up. */
+export interface FramePixels {
+ rgba: Uint8Array;
+ width: number;
+ height: number;
+}
+
+type CaptureModule = ESEngineModule & {
+ renderer_captureFrame?(w: number, h: number): number;
+ renderer_pollFrameCapture?(handle: number): number;
+ renderer_takeFrameCapture?(handle: number, dest: number, destSize: number): boolean;
+};
+
+/** Whether this build can return its own pixels — an older wasm cannot. */
+export function canCaptureFramePixels(module: ESEngineModule): boolean {
+ const m = module as CaptureModule;
+ return typeof m.renderer_captureFrame === 'function'
+ && typeof m.renderer_pollFrameCapture === 'function'
+ && typeof m.renderer_takeFrameCapture === 'function';
+}
+
+/**
+ * The next completed frame, read from the engine.
+ *
+ * `advance` runs one frame — a driver's own step, or waiting a rAF under a live
+ * loop. Null when the build cannot capture, when the request is refused (a
+ * WebGPU surface configured without readback), or when the readback never lands.
+ *
+ * @beta
+ */
+export async function captureFramePixels(
+ module: ESEngineModule,
+ width: number,
+ height: number,
+ advance?: () => void | Promise<void>,
+): Promise<FramePixels | null> {
+ const m = module as CaptureModule;
+ if (!canCaptureFramePixels(module) || width <= 0 || height <= 0) return null;
+
+ const handle = m.renderer_captureFrame!(width, height);
+ if (!handle) return null;
+
+ if (advance) await advance();
+ if (await awaitReadback(() => m.renderer_pollFrameCapture!(handle)) !== READBACK_READY) return null;
+
+ const size = width * height * 4;
+ const rgba = new Uint8Array(size);
+ const ok = withScratch(m, (alloc) => {
+ const ptr = alloc(size);
+ if (!ptr) return false;
+ if (!m.renderer_takeFrameCapture!(handle, ptr, size)) return false;
+ rgba.set(m.HEAPU8.subarray(ptr, ptr + size));
+ return true;
+ });
+ return ok ? { rgba, width, height } : null;
+}
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 5bd373835..932ea1b45 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -149,7 +149,7 @@ export interface ESEngineModule {
* instantiation; '#canvas' resolves to the module's canvas. Returns false
* when the build carries no WebGPU backend or no device was provided.
*/
- initRendererWebGPU(canvasSelector: string, width: number, height: number): boolean;
+ initRendererWebGPU(canvasSelector: string, width: number, height: number, readback: boolean): boolean;
shutdownRenderer(): void;
/**
* Select which EstellaContext the bindings route through. Pass null to clear.
@@ -459,6 +459,10 @@ export interface ESEngineModule {
// Frame Capture API
renderer_captureNextFrame(): void;
+ /** Books the next completed frame for readback; poll + take it (frameCapture.ts). */
+ renderer_captureFrame?(w: number, h: number): number;
+ renderer_pollFrameCapture?(handle: number): number;
+ renderer_takeFrameCapture?(handle: number, dest: number, destSize: number): boolean;
renderer_getCapturedFrameSize(): number;
renderer_getCapturedFrameData(): number;
renderer_getCapturedEntities(): number;
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index bfbb59da0..118c6239b 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -854,6 +854,40 @@ u32 renderer_getSnapshotHeight() {
return g_renderFrame->getSnapshotHeight();
}
+// =============================================================================
+// Frame readback (what was drawn, from the backend that drew it)
+// =============================================================================
+
+/**
+ * Books the next completed frame for readback and returns a handle to poll.
+ * The one way to ask a running engine what is on screen; a host that reads the
+ * page instead gets the display's answer, which is colour managed.
+ */
+u32 renderer_captureFrame(u32 w, u32 h) {
+ auto* device = g_device;
+ if (!device) return 0;
+ return static_cast<u32>(device->captureNextFrame(w, h));
+}
+
+/** 0 = pending (step a frame, poll again), 1 = ready, 2 = failed/unknown. */
+i32 renderer_pollFrameCapture(u32 handle) {
+ auto* device = g_device;
+ if (!device || !handle) return 2;
+ switch (device->pollReadback(static_cast<ReadbackHandle>(handle))) {
+ case GfxReadbackStatus::Pending: return 0;
+ case GfxReadbackStatus::Ready: return 1;
+ default: return 2;
+ }
+}
+
+/** Copies a ready capture into @p dest (w*h*4 bytes, bottom-up RGBA) and releases it. */
+bool renderer_takeFrameCapture(u32 handle, uintptr_t dest, u32 destSize) {
+ auto* device = g_device;
+ if (!device || !handle || !dest) return false;
+ return device->takeReadback(static_cast<ReadbackHandle>(handle),
+ reinterpret_cast<void*>(dest), static_cast<usize>(destSize));
+}
+
void renderer_renderMaterialPreview(u32 materialId, i32 w, i32 h) {
if (!g_renderFrame || w <= 0 || h <= 0) return;
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index 5fd6f3f9c..15738f9a9 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -137,6 +137,11 @@ void gl_enableErrorCheck(bool enabled);
u32 gl_checkErrors(const std::string& context);
void renderer_captureNextFrame();
+
+/** Books the next completed frame for readback; poll + take it. */
+u32 renderer_captureFrame(u32 w, u32 h);
+i32 renderer_pollFrameCapture(u32 handle);
+bool renderer_takeFrameCapture(u32 handle, uintptr_t dest, u32 destSize);
u32 renderer_getCapturedFrameSize();
uintptr_t renderer_getCapturedFrameData();
uintptr_t renderer_getCapturedEntities();
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 57568445d..99b62fb7c 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -180,7 +180,7 @@ bool initRendererInternal(const char* canvasSelector) {
// hands it over via Module.preinitializedWebGPUDevice; the wasm side stays
// fully synchronous. @p width/@p height size the canvas swapchain (the SDK
// passes the canvas backing size it already manages).
-bool initRendererWebGPU(const std::string& canvasSelector, u32 width, u32 height) {
+bool initRendererWebGPU(const std::string& canvasSelector, u32 width, u32 height, bool readback) {
#ifdef ES_ENABLE_WEBGPU
if (g_initialized) return true;
@@ -191,6 +191,10 @@ bool initRendererWebGPU(const std::string& canvasSelector, u32 width, u32 height
return false;
}
auto device = makeUnique<WebGPUDevice>(raw);
+ // Before the surface is configured, because the usage is fixed there: a host
+ // that will ask what was drawn (the editor's viewport capture, a pixel gate)
+ // has to say so now.
+ device->setSurfaceReadback(readback);
if (!device->configureSurface(canvasSelector.c_str(), width, height)) {
ES_LOG_ERROR("initRendererWebGPU: surface configuration failed for '{}'", canvasSelector);
return false;
@@ -202,7 +206,7 @@ bool initRendererWebGPU(const std::string& canvasSelector, u32 width, u32 height
g_activeContext = &legacyCtx().context();
return g_activeContext->init(std::move(device));
#else
- (void)canvasSelector; (void)width; (void)height;
+ (void)canvasSelector; (void)width; (void)height; (void)readback;
ES_LOG_ERROR("initRendererWebGPU: this build carries no WebGPU backend (ES_ENABLE_WEBGPU off)");
return false;
#endif
@@ -639,6 +643,9 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("renderer_diagnose", &esengine::renderer_diagnose);
emscripten::function("renderer_captureNextFrame", &esengine::renderer_captureNextFrame);
+ emscripten::function("renderer_captureFrame", &esengine::renderer_captureFrame);
+ emscripten::function("renderer_pollFrameCapture", &esengine::renderer_pollFrameCapture);
+ emscripten::function("renderer_takeFrameCapture", &esengine::renderer_takeFrameCapture);
emscripten::function("renderer_getCapturedFrameSize", &esengine::renderer_getCapturedFrameSize);
emscripten::function("renderer_getCapturedFrameData", &esengine::renderer_getCapturedFrameData);
emscripten::function("renderer_getCapturedEntities", &esengine::renderer_getCapturedEntities);
diff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hpp
index 4df104e6c..e3a8f3109 100644
--- a/src/esengine/renderer/rhi/GfxDevice.hpp
+++ b/src/esengine/renderer/rhi/GfxDevice.hpp
@@ -537,6 +537,16 @@ public:
/** @brief Abandons a readback (any state); its resources are released. */
virtual void discardReadback(ReadbackHandle handle) = 0;
+ /**
+ * @brief Requests the next completed frame's on-screen image as a readback.
+ * @details One question, whichever backend answers it: a default framebuffer
+ * is read directly, a swapchain image only inside its own frame.
+ * Poll and take it like any other readback.
+ */
+ virtual ReadbackHandle captureNextFrame(u32 w, u32 h) {
+ return requestReadback(FramebufferHandle::Default, w, h);
+ }
+
// =========================================================================
// GPU Timing (optional; EXT_disjoint_timer_query on WebGL2)
// =========================================================================
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index 15095b6ea..0842c31c4 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -380,10 +380,8 @@ bool WebGPUDevice::configureSwapchain(u32 width, u32 height) {
cfg.device = device_;
cfg.format = surface_format_;
cfg.usage = WGPUTextureUsage_RenderAttachment;
-#if !defined(__EMSCRIPTEN__)
- // Opt-in (setSurfaceReadback): lets requestReadback copy the presented frame.
+ // Opt-in (setSurfaceReadback): lets captureNextFrame copy the presented frame.
if (surface_readback_) cfg.usage |= WGPUTextureUsage_CopySrc;
-#endif
cfg.width = width;
cfg.height = height;
// Auto, not Opaque: let the backend pick a mode the surface advertises. A
@@ -1533,6 +1531,7 @@ void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {
WGPUTextureView dsView = nullptr;
pass_ds_format_ = WGPUTextureFormat_Undefined;
pass_color_format_ = surface_format_;
+ pass_is_surface_ = desc.target == FramebufferHandle::Default;
if (desc.target != FramebufferHandle::Default) {
auto fbIt = framebuffers_.find(static_cast<u32>(desc.target));
if (fbIt == framebuffers_.end()) {
@@ -1675,6 +1674,15 @@ void WebGPUDevice::endRenderPass() {
gpu_time_ring_[gpu_time_slot_].buf, 0, 16);
}
+ // A booked capture rides the pass's OWN encoder: the browser presents the
+ // swapchain image with this submit, so a copy encoded afterwards copies a
+ // destroyed texture. Several surface passes overwrite; the last one wins.
+ if (capture_id_ && pass_is_surface_ && frame_texture_ && encoder_) {
+ encodeReadbackCopy(encoder_, capture_id_, frame_texture_);
+ capture_copied_ = true;
+ }
+ pass_is_surface_ = false;
+
WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder_, nullptr);
wgpuCommandEncoderRelease(encoder_);
encoder_ = nullptr;
@@ -1699,14 +1707,16 @@ void WebGPUDevice::endRenderPass() {
/** Give the swapchain texture back: the frame is over (see GfxDevice::endFrame).
* A frame may have opened several passes on it, so no single pass may do this. */
void WebGPUDevice::endFrame() {
-#if !defined(__EMSCRIPTEN__)
// A capture is served HERE and nowhere else: this is the last instant at which
// the frame is both finished and still ours. Asking from outside cannot work —
// whoever could ask runs after the renderer has already given the image back.
if (capture_id_) {
const u32 id = capture_id_;
capture_id_ = 0;
- if (frame_texture_) {
+ if (capture_copied_) {
+ capture_copied_ = false;
+ mapReadback(id);
+ } else if (frame_texture_) {
submitReadbackCopy(id, frame_texture_);
} else {
// Nothing drew, so there is no image to copy. Leaving the record
@@ -1715,12 +1725,10 @@ void WebGPUDevice::endFrame() {
if (it != readbacks_.end()) it->second.status = GfxReadbackStatus::Failed;
}
}
-#endif
if (frame_view_) { wgpuTextureViewRelease(frame_view_); frame_view_ = nullptr; }
if (frame_texture_) { wgpuTextureRelease(frame_texture_); frame_texture_ = nullptr; }
}
-#if !defined(__EMSCRIPTEN__)
ReadbackHandle WebGPUDevice::captureNextFrame(u32 w, u32 h) {
if (!isDeviceUsable() || !device_ || w == 0 || h == 0) return ReadbackHandle::Invalid;
if (!surface_readback_) {
@@ -1732,7 +1740,6 @@ ReadbackHandle WebGPUDevice::captureNextFrame(u32 w, u32 h) {
capture_id_ = allocReadback(w, h);
return static_cast<ReadbackHandle>(capture_id_);
}
-#endif
// =============================================================================
// Readback (async seam: texture → staging copy, resolved when the map lands)
@@ -1800,12 +1807,11 @@ u32 WebGPUDevice::allocReadback(u32 w, u32 h) {
return id;
}
-void WebGPUDevice::submitReadbackCopy(u32 id, WGPUTexture source) {
+void WebGPUDevice::encodeReadbackCopy(WGPUCommandEncoder encoder, u32 id, WGPUTexture source) {
auto it = readbacks_.find(id);
- if (it == readbacks_.end() || !source) return;
+ if (it == readbacks_.end() || !source || !encoder) return;
ReadbackRec& rec = it->second;
- WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr);
WGPUTexelCopyTextureInfo src = WGPU_TEXEL_COPY_TEXTURE_INFO_INIT;
src.texture = source;
WGPUTexelCopyBufferInfo dst = WGPU_TEXEL_COPY_BUFFER_INFO_INIT;
@@ -1815,11 +1821,12 @@ void WebGPUDevice::submitReadbackCopy(u32 id, WGPUTexture source) {
dst.layout.rowsPerImage = rec.height;
WGPUExtent3D size{rec.width, rec.height, 1};
wgpuCommandEncoderCopyTextureToBuffer(encoder, &src, &dst, &size);
- WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder, nullptr);
- wgpuCommandEncoderRelease(encoder);
- wgpuQueueSubmit(queue_, 1, &commands);
- wgpuCommandBufferRelease(commands);
+}
+void WebGPUDevice::mapReadback(u32 id) {
+ auto it = readbacks_.find(id);
+ if (it == readbacks_.end()) return;
+ ReadbackRec& rec = it->second;
WGPUBufferMapCallbackInfo cb = WGPU_BUFFER_MAP_CALLBACK_INFO_INIT;
cb.mode = WGPUCallbackMode_AllowSpontaneous;
cb.callback = &WebGPUDevice::onReadbackMapped;
@@ -1829,6 +1836,17 @@ void WebGPUDevice::submitReadbackCopy(u32 id, WGPUTexture source) {
static_cast<u64>(rec.paddedBytesPerRow) * rec.height, cb);
}
+void WebGPUDevice::submitReadbackCopy(u32 id, WGPUTexture source) {
+ if (readbacks_.find(id) == readbacks_.end() || !source) return;
+ WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr);
+ encodeReadbackCopy(encoder, id, source);
+ WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder, nullptr);
+ wgpuCommandEncoderRelease(encoder);
+ wgpuQueueSubmit(queue_, 1, &commands);
+ wgpuCommandBufferRelease(commands);
+ mapReadback(id);
+}
+
GfxReadbackStatus WebGPUDevice::pollReadback(ReadbackHandle handle) {
// AllowSpontaneous callbacks fire from the browser's event loop on their own;
// the pump is defensive (and required if the callback mode ever tightens).
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index 9b1a22d72..1e0afd868 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -220,6 +220,16 @@ public:
* endRenderPass. No-op until a surface is configured. */
void present();
+ /**
+ * @brief Whether bytes read back from the DEFAULT framebuffer are BGRA rather
+ * than RGBA.
+ *
+ * The format is the surface's choice (BGRA8 on Metal, RGBA8 on Vulkan), so
+ * anyone writing an image has to ask rather than assume.
+ */
+ bool surfaceBytesAreBGRA() const;
+#endif
+
/**
* @brief Configure the swapchain with CopySrc, so {@link captureNextFrame}
* can read it. Must be set BEFORE the surface is configured.
@@ -230,25 +240,17 @@ public:
void setSurfaceReadback(bool enabled) { surface_readback_ = enabled; }
/**
- * @brief Copy the next completed frame's swapchain image into a readback,
- * resolved through the usual pollReadback / takeReadback pair.
+ * @brief Copy the next completed frame's swapchain image into a readback.
*
* Books the copy; endFrame performs it, because the renderer gives the
- * swapchain image back there and every caller outside runs too late.
+ * swapchain image back there and every caller outside runs too late. This is
+ * the whole reason the seam is virtual: a GL default framebuffer can be read
+ * on demand, and this one cannot.
*
* Invalid without {@link setSurfaceReadback}, or with a capture in flight.
*/
- ReadbackHandle captureNextFrame(u32 w, u32 h);
+ ReadbackHandle captureNextFrame(u32 w, u32 h) override;
- /**
- * @brief Whether bytes read back from the DEFAULT framebuffer are BGRA rather
- * than RGBA.
- *
- * The format is the surface's choice (BGRA8 on Metal, RGBA8 on Vulkan), so
- * anyone writing an image has to ask rather than assume.
- */
- bool surfaceBytesAreBGRA() const;
-#endif
void endFrame() override;
private:
@@ -386,6 +388,10 @@ private:
WGPUTextureFormat surface_format_ = WGPUTextureFormat_RGBA8Unorm;
/** Whether the surface was configured with CopySrc — see setSurfaceReadback. */
bool surface_readback_ = false;
+ /** The pass being recorded draws to the surface, so a capture rides its encoder. */
+ bool pass_is_surface_ = false;
+ /** A booked capture was already copied by a pass; endFrame only maps it. */
+ bool capture_copied_ = false;
/** A capture booked by captureNextFrame, served by endFrame. 0 = none. */
u32 capture_id_ = 0;
u32 surface_width_ = 0;
@@ -410,6 +416,8 @@ private:
/** A staging buffer + record with no copy submitted yet; 0 on failure. */
u32 allocReadback(u32 w, u32 h);
void submitReadbackCopy(u32 id, WGPUTexture source);
+ void encodeReadbackCopy(WGPUCommandEncoder encoder, u32 id, WGPUTexture source);
+ void mapReadback(u32 id);
// Internal clear family (region-scoped clears + mid-pass clearStencil).
// Explicit layout so ONE bind group serves every write-mask variant.
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index 6bb36bcb2..11522fab4 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -23,14 +23,12 @@
export const TIERS = ['pr', 'nightly'];
/**
- * Why the second backend's answer cannot be trusted yet: the two are read by
- * different instruments. GL reports the engine's buffer; WebGPU has no web
- * readback, so the runner captures the composited page — a colour-managed path
- * that reads a painted rgb(0,255,0) as rgb(58,254,32).
+ * What still separates the second backend from the first: a CI runner has no
+ * Dawn adapter, so nothing here runs it. Where an adapter exists, every scene
+ * that declares `webgpu` passes — both backends are read the same way, off the
+ * engine's own buffer.
*/
-export const WEBGPU_GAP = 'no CI adapter; and where one exists the frames are read by capturePage, '
- + 'which colour-manages them (rgb(0,255,0) captures as rgb(58,254,32)) — the backend needs an '
- + 'engine-side readback before these ten mean anything';
+export const WEBGPU_GAP = 'no adapter on a CI runner; with one, all 10 pass (`--backend webgpu`)';
/**
* Every pixel gate. `env` is handed to desktop/scripts/headless-verify.mjs