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(gi): the scene key is asked every frame and the boxes are built only when it changes; profiling switch u_skip is declared so it reaches the engine

yhha61aff964897
diff --git a/docs/GI_LUMEN_DESIGN.md b/docs/GI_LUMEN_DESIGN.md
index 5690e00ca..0ee2a4da1 100644
--- a/docs/GI_LUMEN_DESIGN.md
+++ b/docs/GI_LUMEN_DESIGN.md
@@ -143,6 +143,19 @@
- **未查明**:这 15 ms 在哪。候选:场景通道为 G-buffer 和反照率多写两个附件(这在 tile 型 GPU 上按带宽算很贵,体素 GI 也有);应用通道全分辨率读写 RGBA16F;探针通道的固定开销。已加 `u_skip`(1 卡面、2 探针、4 应用)用来逐项扣除,**没有跑完**:手机已经发烫,按用户的话停了。
- **发热**:反复以不限帧率连续跑了几分钟,CPU 约 78–80 °C、电池 46.6 °C。之后的测量必须限时、限次,中间让手机降温。
+### 5.3.1 那约 15 ms 的追查(2026-11-11,同一台手机,限时限次地跑)
+
+已排除:
+- **不是 JS 每帧在重建场景**:系统每帧都在算盒子的距离场和卡面,手机上很贵。改成每帧只算一个键(`instanceKey`),变了才建。帧时间没变,`update`(脚本)本来就只有 0.02 ms。这个改动仍然该做。
+- **不是多重采样**:关掉 MSAA 结果一样(23.7)。
+- **不是后处理链本身**:只开暗角 7.8 ms(与没有后效 7.7 相同)。
+- **G-buffer 约 +3 ms**:只开 SSAO(同样要深度与 G-buffer)11.0 ms。
+- **没喂场景时**:开着 `dynamicGI` 但场景里没有立方体(不上传),9.9 ms,与 SSAO 相当。
+
+所以 **一旦场景上传,帧时间从 9.9 跳到 23.5**。其中卡面与探针的光线本身只占约 6.5 ms(分片拉满加探针步长拉满,23.5→22.6 之前的数是 23.0→22.6,见上表)。把 `u_skip` 接进后效(它原先没有声明,SDK 不会把它交给原生,所以先前所有 `u_skip` 的数都是没生效的“默认”,**那几行 `skip` 数据无效**)之后的逐项扣除没有跑完:跑到一半手机被拿起来用了(`frames: paused`),按用户的话停止。
+
+下一步:手机降温、空闲时,按 `u_skip` = 8(场景已上传,什么都不声明)、3(只有应用)、16(只有卡面和探针,无应用通道)各跑一次,每次 16 s,中间间隔 30 s。
+
## 5.4 成本断言(2026-11-11)
`node tools/gi/check-gi-cost.mjs`(门禁 `gi-cost`,本地范围)。一帧的成本是“工作量 × 设备上每份工作的代价”,第二个因子是设备的(同一份工作,RTX 3 ms,手机 20 ms),第一个因子是引擎的,在 `DynamicGI` 派发通道的地方计数(`DynamicGIStats`,经 `postprocess_giStats` 读回,页面里是 `window.__estellaGIStats()`),两边一样,所以在 GPU 快得看不出差别的机器上也能拦住回归。
diff --git a/pipeline/tests/gpu-scene.test.ts b/pipeline/tests/gpu-scene.test.ts
index fa527f57e..2df1b7442 100644
--- a/pipeline/tests/gpu-scene.test.ts
+++ b/pipeline/tests/gpu-scene.test.ts
@@ -8,7 +8,7 @@ import { describe, it, expect } from 'vitest';
import { MeshChannel, MeshChannelType, type MeshData } from 'esengine';
import { bakeMeshCards } from '../src/assets/meshCards';
import { bakeMeshSdf } from '../src/assets/meshSdf';
-import { buildInstances, type GIEntry } from '../../sdk/src/gi/dynamicGISystem';
+import { buildInstances, instanceKey, type GIEntry } from '../../sdk/src/gi/dynamicGISystem';
import { packGPUScene, GI_HEADER_FLOATS, GI_INSTANCE_FLOATS } from '../../sdk/src/gi/gpuScene';
import { GlobalSdf } from '../../sdk/src/gi/globalSdf';
@@ -71,6 +71,13 @@ describe('which renderers become instances', () => {
expect(Math.abs(m[2]! + 1)).toBeLessThan(1e-6); // local x now points along world -z
});
+ it('has a key that can be had without building: the same string, for the system to ask every frame', () => {
+ const entries = [entry(CUBE, transform([0, 0, 0], [2, 1, 3]), null, [1, 0, 0]), entry(9, transform([300, 0, 0], [2, 2, 2]), 'assets/rock.esmesh'), entry(9, transform([0, 0, 0], [1, 2, 1]), 'assets/rock.esmesh')];
+ const found = (p: string) => (p === 'assets/rock.esmesh' ? baked : null);
+ expect(instanceKey(entries, CUBE, found)).toBe(buildInstances(entries, CUBE, found).key);
+ expect(instanceKey(entries, CUBE, () => null)).toBe(buildInstances(entries, CUBE, () => null).key);
+ });
+
it('changes its key when anything that matters moves, and not when nothing does', () => {
const a = buildInstances([entry(CUBE, transform([0, 0, 0]))], CUBE, () => null).key;
expect(buildInstances([entry(CUBE, transform([0, 0, 0]))], CUBE, () => null).key).toBe(a);
diff --git a/sdk/src/gi/dynamicGISystem.ts b/sdk/src/gi/dynamicGISystem.ts
index 054c472be..5e6119498 100644
--- a/sdk/src/gi/dynamicGISystem.ts
+++ b/sdk/src/gi/dynamicGISystem.ts
@@ -59,13 +59,38 @@ export interface GISidecars { sdf: MeshSdf; cards: MeshCards }
* mesh is the baked `.esmeshsdf` and `.esmeshcards` beside it, when it has them and is scaled the same along every axis (a distance field
* does not survive a stretch). Everything else is not in the GI scene.
*/
+function poseKey(e: GIEntry): string {
+ const s = e.transform.worldScale, p = e.transform.worldPosition, q = e.transform.worldRotation;
+ return `${[p.x, p.y, p.z, q.x, q.y, q.z, q.w, s.x, s.y, s.z].map((v) => v.toFixed(3)).join(',')};${e.colour.join(',')};${e.emissive.join(',')}`;
+}
+
+/**
+ * What `buildInstances` would make of the entries, as a string, without making it. The system asks this every frame and builds only when it
+ * changes: building is the distance fields and cards of every box, which is milliseconds on a desktop and tens on a phone, and a scene that
+ * has not moved should cost a string compare and not that.
+ */
+export function instanceKey(entries: readonly GIEntry[], cube: number, sidecars: (path: string) => GISidecars | null): string {
+ let key = '';
+ for (const e of entries) {
+ const s = e.transform.worldScale;
+ if (e.mesh === cube) key += `|c${poseKey(e)}`;
+ else if (e.path) {
+ if (!sidecars(e.path)) continue;
+ const lo = Math.min(s.x, s.y, s.z), hi = Math.max(s.x, s.y, s.z);
+ if (lo <= 0 || hi / lo > 1.05) continue;
+ key += `|m${e.path};${poseKey(e)}`;
+ }
+ }
+ return key;
+}
+
export function buildInstances(entries: readonly GIEntry[], cube: number, sidecars: (path: string) => GISidecars | null): { instances: GIInstance[]; key: string } {
const instances: GIInstance[] = [];
let key = '';
const extent = Math.max(1, ...entries.filter((e) => e.mesh === cube).flatMap((e) => [e.transform.worldScale.x, e.transform.worldScale.y, e.transform.worldScale.z].map((v) => v * CUBE)));
for (const e of entries) {
- const s = e.transform.worldScale, p = e.transform.worldPosition, q = e.transform.worldRotation;
- const pose = `${[p.x, p.y, p.z, q.x, q.y, q.z, q.w, s.x, s.y, s.z].map((v) => v.toFixed(3)).join(',')};${e.colour.join(',')};${e.emissive.join(',')}`;
+ const s = e.transform.worldScale;
+ const pose = poseKey(e);
if (e.mesh === cube) {
const size: [number, number, number] = [s.x * CUBE, s.y * CUBE, s.z * CUBE];
// A box with a cell fine enough that a wall a tenth of a metre thick is still more than one.
@@ -196,15 +221,17 @@ export function dynamicGISystem(app: App) {
}
entries.push({ mesh: r.mesh, transform: t, colour: [r.color.r, r.color.g, r.color.b], emissive: emissiveOf(r.material), path });
}
- const { instances, key: sceneKey } = buildInstances(entries, cube, (p) => sidecars.get(p) ?? null);
+ const sceneKey = instanceKey(entries, cube, (p) => sidecars.get(p) ?? null);
// A cell size asks for the field that follows the eye: three levels, each four times the last, around the camera. Without one the
// field is a single window that holds the whole scene.
const following = effect.cellSize > 0 && eye !== null;
const snap = following ? effect.cellSize * 8 : 1;
const eyeKey = following ? eye!.map((v) => Math.floor(v / snap)).join(',') : '';
const key = (light ? `${light.toLight.join(',')}|${light.radiance.join(',')}` : 'dark') + sceneKey + '#' + lightKey + '#' + effect.cellSize + eyeKey;
- if (key === lastKey || instances.length === 0) return;
+ if (key === lastKey || sceneKey === '') return;
lastKey = key;
+ const { instances } = buildInstances(entries, cube, (p) => sidecars.get(p) ?? null);
+ if (instances.length === 0) return;
let sdf: GlobalSdf | undefined;
if (following) {
const cell = effect.cellSize;
diff --git a/sdk/src/postprocess/effects.ts b/sdk/src/postprocess/effects.ts
index 99bd8fea4..417a8effc 100644
--- a/sdk/src/postprocess/effects.ts
+++ b/sdk/src/postprocess/effects.ts
@@ -583,6 +583,8 @@ registerEffect({
{ name: 'u_probeStride', label: 'Probe Ray Stride', min: 1, max: 8, step: 1, defaultValue: 2 },
// 0 fits one field to the whole scene. A size (world units) makes three levels, each four times the last, that follow the camera: the
// finest holds what is near the eye at this resolution and the others carry the far scene, so a world larger than one window works.
+ // Measuring: skip the cards (1), the probes (2), the apply (4), declare nothing (8), or stop before the apply (16), to read what the rest costs.
+ { name: 'u_skip', label: 'Skip Passes (profiling)', min: 0, max: 63, step: 1, defaultValue: 0 },
{ name: 'u_cellSize', label: 'Field Cell Size', min: 0, max: 1000, step: 0.1, defaultValue: 0, worldUnits: 1 },
],
});
diff --git a/src/esengine/renderer/frame/DynamicGI.cpp b/src/esengine/renderer/frame/DynamicGI.cpp
index e14217f34..68e8aa03d 100644
--- a/src/esengine/renderer/frame/DynamicGI.cpp
+++ b/src/esengine/renderer/frame/DynamicGI.cpp
@@ -671,6 +671,7 @@ rg::ResourceId DynamicGI::declare(rg::RenderGraph& graph, rg::ResourceId input,
u32 width, u32 height) {
if (!ensure() || input == rg::kNoResource || scene == rg::kNoResource) return input;
if (!upload()) return input;
+ if (params.skip & 8u) return input; // measuring: nothing declared at all
// About 160 x 90 probes whatever the size of the picture: 8 pixels apart at 720p, 12 at 1080p, 16 at 1440p. Their cost is in their number.
probeSpacing_ = std::clamp(((height + 89) / 90 + 1) / 2 * 2, 8u, 32u);
const u32 tilesX = (width + probeSpacing_ - 1) / probeSpacing_, tilesY = (height + probeSpacing_ - 1) / probeSpacing_;
@@ -786,6 +787,7 @@ rg::ResourceId DynamicGI::declare(rg::RenderGraph& graph, rg::ResourceId input,
graph.addPass(std::move(pass));
}
+ if (params.skip & 16u) return input; // measuring: the cards and the probes, and no apply pass nor the target it writes
rg::TargetDesc full;
full.format = GfxPixelFormat::RGBA16F;
full.storage = true;
diff --git a/src/esengine/renderer/frame/PostProcessPipeline.cpp b/src/esengine/renderer/frame/PostProcessPipeline.cpp
index d3bcd87d1..9f1a93b0b 100644
--- a/src/esengine/renderer/frame/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/frame/PostProcessPipeline.cpp
@@ -411,6 +411,8 @@ bool PostProcessPipeline::passesWantGBuffer() {
if (!pass.enabled) continue;
// The voxel GI reads the surface's normal, whatever the effect's shader (it has none).
if (!pass.nativeKind.empty()) {
+ // Measuring (DynamicGI u_skip bit 32): this pass does not ask for the G-buffer, to read what the G-buffer scene costs by itself.
+ if (const auto skip = pass.floatUniforms.find("u_skip"); skip != pass.floatUniforms.end() && (static_cast<u32>(skip->second) & 32u)) continue;
if (device_.supportsCompute()) return true;
continue;
}