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.

perf: reuse depth prepass for planar reflections

yhhc0133903daca
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 1f1f527fc..5c879cea8 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -100,12 +100,15 @@ jobs:
run: |
node tools/render-host/build.mjs
node tools/tests/planar-reflection.e2e.mjs --webgl-only
+ node tools/tests/planar-reflection.e2e.mjs --webgl-only --prepass
- name: Upload planar reflection runtime observations
if: always()
uses: actions/upload-artifact@v7
with:
name: planar-reflection-runtime
- path: output/rm044-runtime/
+ path: |
+ output/rm044-runtime/
+ output/rm044-runtime-prepass/
retention-days: 3
- name: Upload OpenPaaS contract observations and frames
if: always()
diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cpp
index 8e7a531b4..74867c5db 100644
--- a/src/esengine/renderer/frame/RenderFrame.cpp
+++ b/src/esengine/renderer/frame/RenderFrame.cpp
@@ -260,6 +260,36 @@ bool RenderFrame::gpuDetailWanted() const {
#endif
}
+void RenderFrame::submitColorList(DrawList& list, TransientBufferPool& buffers, FrameCapture* capture,
+ DrawList::Phase phase, const char* prepassCounter) {
+ const bool opaque = phase == DrawList::Phase::All || phase == DrawList::Phase::WithoutSceneColor || phase == DrawList::Phase::OpaqueOnly;
+ const u32 prepassDraws = depth_prepass_ && opaque ? list.depthPrepassDraws() : 0u;
+ const bool prepass = prepassDraws > 0;
+ if (opaque) ES_PROFILE_COUNTER(prepassCounter, prepassDraws);
+ const bool detail = running_pass_timer_ && gpuDetailWanted();
+ const auto sinkFor = [this, &list](const char* prefix) {
+ rg::PassTimer* timer = running_pass_timer_;
+ list.setShaderRunSink([timer, prefix](const char* shader) {
+ timer->segment(shader ? std::string(prefix) + shader : std::string("tail"));
+ });
+ };
+ if (prepass) {
+ ES_PROFILE_SCOPE("render.submit.prepass");
+ if (detail) sinkFor("prepass:");
+ list.execute(device_, buffers, context_.materials(), context_.getWhiteTextureId(),
+ nullptr, context_.perDrawBlocks(), phase, DrawList::DrawPass::DepthPrepass);
+ if (detail) list.setShaderRunSink(nullptr);
+ }
+ if (detail) sinkFor("");
+ list.execute(device_, buffers, context_.materials(), context_.getWhiteTextureId(),
+ capture, context_.perDrawBlocks(), phase,
+ prepass ? DrawList::DrawPass::ColorAfterPrepass : DrawList::DrawPass::Color);
+ if (detail) {
+ running_pass_timer_->segment("tail");
+ list.setShaderRunSink(nullptr);
+ }
+}
+
void RenderFrame::drawScene(DrawList::Phase phase) {
// A temporal effect in the chain asks for the picture to be shifted by a different
// sub-pixel amount each frame, so its history samples what a single frame cannot.
@@ -310,36 +340,7 @@ void RenderFrame::drawScene(DrawList::Phase phase) {
#ifdef ES_ENABLE_POSTPROCESS
draw_list_.setGBufferPass(post_process_ && post_process_->sceneHasGBuffer());
#endif
- // The opaque surfaces first, depth alone, so the colour pass shades each pixel for the surface that is in front of it and not for every
- // one that was drawn there on the way. Only a phase that draws the opaque scene, and only when something in the list has a depth program.
- const bool opaque = phase == DrawList::Phase::All || phase == DrawList::Phase::WithoutSceneColor || phase == DrawList::Phase::OpaqueOnly;
- const u32 prepassDraws = depth_prepass_ && opaque ? draw_list_.depthPrepassDraws() : 0u;
- const bool prepass = prepassDraws > 0;
- if (opaque) ES_PROFILE_COUNTER("render.prepass.draws", prepassDraws);
- // With the pass timer running and detail asked for, each run of draws of one shader is its own timed segment of the pass.
- const bool detail = running_pass_timer_ && gpuDetailWanted();
- const auto sinkFor = [this](const char* prefix) {
- rg::PassTimer* timer = running_pass_timer_;
- draw_list_.setShaderRunSink([timer, prefix](const char* shader) {
- timer->segment(shader ? std::string(prefix) + shader : std::string("tail"));
- });
- };
- if (prepass) {
- ES_PROFILE_SCOPE("render.submit.prepass");
- if (detail) sinkFor("prepass:");
- draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),
- nullptr, context_.perDrawBlocks(), phase, DrawList::DrawPass::DepthPrepass);
- if (detail) draw_list_.setShaderRunSink(nullptr);
- }
- if (detail) sinkFor("");
- draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),
- &frame_capture_, context_.perDrawBlocks(), phase,
- prepass ? DrawList::DrawPass::ColorAfterPrepass : DrawList::DrawPass::Color);
- if (detail) {
- // The rest of the pass (the resolve, the state restored) is its own segment, closed by the graph.
- running_pass_timer_->segment("tail");
- draw_list_.setShaderRunSink(nullptr);
- }
+ submitColorList(draw_list_, pool_, &frame_capture_, phase, "render.prepass.draws");
draw_list_.setGBufferPass(false);
if (device_.skipPendingPrograms()) {
ES_PROFILE_COUNTER("render.draws.waitingForProgram", draw_list_.skippedForProgram());
diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hpp
index 02577483a..f84e2f5e3 100644
--- a/src/esengine/renderer/frame/RenderFrame.hpp
+++ b/src/esengine/renderer/frame/RenderFrame.hpp
@@ -868,6 +868,9 @@ private:
void releaseShadowFrameUbos();
/// The scene pass's body: the draw, and the constants it needs current.
void drawScene(DrawList::Phase phase = DrawList::Phase::All);
+ /// Shared colour submission for scene and reflected views, including the quality policy's depth prepass and shader timings.
+ void submitColorList(DrawList& list, TransientBufferPool& buffers, FrameCapture* capture,
+ DrawList::Phase phase, const char* prepassCounter);
/// Drops the atlas texture id the frame published; its target is the graph's
/// to give back.
void releaseFrameTargets();
diff --git a/src/esengine/renderer/frame/RenderFramePlanar.cpp b/src/esengine/renderer/frame/RenderFramePlanar.cpp
index b90648db0..941a109fc 100644
--- a/src/esengine/renderer/frame/RenderFramePlanar.cpp
+++ b/src/esengine/renderer/frame/RenderFramePlanar.cpp
@@ -170,8 +170,7 @@ void RenderFrame::executePlanarReflection(ecs::Registry& registry, u32 view) {
// The tiled lights' masks are for the camera the scene is seen from; this one looks from the mirror.
context_.lights().suspendTiled(true);
context_.lights().uploadAndBind();
- planar_list_.execute(device_, planar_pool_, context_.materials(),
- context_.getWhiteTextureId(), nullptr, context_.perDrawBlocks());
+ submitColorList(planar_list_, planar_pool_, nullptr, DrawList::Phase::All, "render.planar.prepass.draws");
context_.lights().suspendTiled(false);
capture.valid = true;
capture.lastTime = planar_elapsed_;
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index 444b50d2f..f5f0faef8 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -978,16 +978,18 @@ export const SCENES = [
const PREPASS_TWINS = [
// Scenes that draw opaque meshes already.
'mesh-opaque', 'mesh-instanced', 'prepass-hook', 'corpus-cutout-edge', 'mesh-normalmap', 'mesh-shadow-cutout', 'mesh-shadow', 'sun-shadow',
+ { id: 'planar-reflection', counters: { 'render.planar.prepass.draws': 1 } },
// The same scenes with their meshes made opaque (fixtures/scenes/*-opaque.esscene), for what a mesh can be besides a rigid one that is lit:
// skinned, morphing.
{ id: 'mesh-skin', scene: 'mesh-skin-opaque.esscene' }, { id: 'mesh-morph-shaped', scene: 'mesh-morph-opaque.esscene' },
{ id: 'mesh-lit', scene: 'mesh-lit-opaque.esscene' }, { id: 'mesh-resident', scene: 'mesh-renderer-opaque.esscene', as: 'mesh-renderer' },
];
for (const entry of PREPASS_TWINS) {
- const { id, scene, as } = typeof entry === 'string' ? { id: entry } : entry;
+ const { id, scene, as, counters } = typeof entry === 'string' ? { id: entry } : entry;
const base = SCENES.find((s) => s.id === id);
if (!base) throw new Error(`renderScenes: no scene "${id}" to run a prepass twin of`);
const env = { ...base.env, ESTELLA_VERIFY_PREPASS: '1' };
+ if (counters) env.ESTELLA_VERIFY_COUNTERS = JSON.stringify({ ...JSON.parse(env.ESTELLA_VERIFY_COUNTERS ?? '{}'), ...counters });
if (scene) env.ESTELLA_VERIFY_SCENE = `/scenes/${scene}`;
SCENES.push({ ...base, id: `${as ?? (scene ? scene.replace('.esscene', '') : id)}-prepass`, env });
}
diff --git a/tools/tests/planar-reflection.e2e.mjs b/tools/tests/planar-reflection.e2e.mjs
index 7e5c27113..aafeafa54 100644
--- a/tools/tests/planar-reflection.e2e.mjs
+++ b/tools/tests/planar-reflection.e2e.mjs
@@ -12,7 +12,8 @@ import { requireCurrentEngine } from '../lib/engineBuild.mjs';
const { PNG } = createRequire(new URL('../../pipeline/package.json', import.meta.url))('pngjs');
const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
requireCurrentEngine(repo, path.join(repo, 'build/render-host/wasm'));
-const out = path.join(repo, 'output/rm044-runtime');
+const prepass = process.argv.includes('--prepass');
+const out = path.join(repo, `output/rm044-runtime${prepass ? '-prepass' : ''}`);
await mkdir(out, { recursive: true });
const server = http.createServer(async (req, res) => {
try {
@@ -29,7 +30,7 @@ const server = http.createServer(async (req, res) => {
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const browser = await chromium.launch({ channel: 'chromium', headless: true, args: ['--enable-unsafe-webgpu', '--ignore-gpu-blocklist', '--enable-unsafe-swiftshader', '--mute-audio'] });
-const report = { status: 'failed', mode: 'headless-engine', checks: [], deviceAcceptance: 'pending' };
+const report = { status: 'failed', mode: 'headless-engine', prepass, checks: [], deviceAcceptance: 'pending' };
try {
const backends = process.argv.includes('--webgl-only') ? ['webgl2'] : ['webgl2', 'webgpu'];
for (const backend of backends) {
@@ -41,8 +42,9 @@ try {
report.errors = errors;
page.on('pageerror', e => errors.push(String(e)));
page.on('console', msg => { if (msg.type() === 'error') (injectingLoss ? lossLogs : errors).push(msg.text()); });
- await page.goto(`http://127.0.0.1:${server.address().port}/?w=512&h=512&backend=${backend}`);
+ await page.goto(`http://127.0.0.1:${server.address().port}/?w=512&h=512&backend=${backend}&prepass=${prepass ? 1 : 0}`);
await page.evaluate(async () => { await window.__estellaHeadless.ready; });
+ await page.evaluate(() => window.__estellaHeadless.api.setCpuProfiling(true));
const load = await page.evaluate(() => window.__estellaHeadless.api.loadScene('/scenes/planar-reflection.esscene'));
assert.deepEqual(load.missing, []);
const step = n => page.evaluate(n => window.__estellaHeadless.api.step(n), n);
@@ -73,6 +75,10 @@ try {
assert.equal(ready.width,512); assert.ok(ready.draws>0);
const on = await capture('enabled');
const drawsOn = await page.evaluate(() => window.__estellaHeadless.api.getStats().drawCalls);
+ const countersOn = await page.evaluate(() => window.__estellaHeadless.api.getCounters());
+ const prepassDraws = countersOn['render.planar.prepass.draws'];
+ if (prepass) assert.ok(prepassDraws > 0, 'the reflection must execute its depth prepass');
+ else assert.equal(prepassDraws, 0, 'the disabled quality policy must not add a depth prepass');
await page.evaluate(() => window.__estellaHeadless.api.idleRenderFrames(8));
assert.equal((await status()).state,'ready','cached editor frames must retain the last capture');
await step(1);
@@ -85,7 +91,10 @@ try {
assert.equal((await status()).state,'inactive');
const off = await capture('disabled');
const drawsOff = await page.evaluate(() => window.__estellaHeadless.api.getStats().drawCalls);
+ const countersOff = await page.evaluate(() => window.__estellaHeadless.api.getCounters());
assert.equal(drawsOn-drawsOff,ready.draws,'frame statistics must include the capture cost');
+ assert.equal(countersOn['render.gpu.draws']-countersOff['render.gpu.draws'],ready.draws+prepassDraws,
+ 'GPU statistics must include both reflected colour draws and the depth prepass');
assert.ok(changed(on,off,256)>100,'reflection must change the lower half of the image');
assert.ok(pixel(off,200,290).every(c=>c<10),'disabled reflection must not leave stale pixels');
await field(2,'PlanarReflection','enabled',true); await step(2);
@@ -148,7 +157,7 @@ try {
assert.ok(pixel(split,72,290)[0]>230,'first view must keep its own reflection');
assert.ok(pixel(split,375,268)[1]>230,'second view must capture from its own camera');
assert.deepEqual(errors,[]);
- report.checks.push({backend,ready,drawsOn,drawsOff,reflectionPixels:changed(on,off,256),movingPixels:changed(on,moved,256),recovery,secondView,lossLogs,errors});
+ report.checks.push({backend,ready,drawsOn,drawsOff,prepassDraws,reflectionPixels:changed(on,off,256),movingPixels:changed(on,moved,256),recovery,secondView,lossLogs,errors});
await page.close();
}
report.status = 'checks-passed';