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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(render): shaders can compile without stopping the frame, and a tile-based GPU is told what a pass does not keep
yhhfa1d3521a193
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8145cc379..098005441 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **Shaders that compile without stopping the frame.** `quality.asyncShaderCompile` (off unless a game turns it on): a draw whose shader the browser is still compiling is left out until it is ready, and every shader asked for in the meantime compiles at once, where before each was waited for in turn. On a first visit the Terrain & Water example's shaders took 43 seconds of a frozen page on Chrome and D3D11 (the heavy lit ones 3 to 10 seconds each, the worst frame 10 seconds); with this on the page was blocked for about a second in all and the whole scene was drawn at 20 seconds, not 56. The same scene, once everything has compiled, is the same picture. `renderer_getPendingShaders()` says how many are still compiling, for a loading screen. Off, nothing changes. WebGL2 only (a WebGPU pipeline is not compiled this way).- **A depth prepass for the opaque scene.** A quality level can draw the opaque meshes twice, depth alone first, so a pixel is shaded for the surface that is in front of it and not for every one drawn there on the way: `QualityProfile.depthPrepass` (on for `high` and `medium`, off for `low` and with the quality system off), and `renderer_setDepthPrepass` for a host without one. Cut-out leaves take part, with the coverage their own shader writes. A surface whose material bends its vertices with a hook takes part too, unless it is also a cut-out. On the Terrain & Water example, on an RTX 3060, a frame is 4 to 39 ms shorter, most where trees stand thick.- **A third mesh for a plant.** A part of a world's plants can name `lod2Mesh` and its kind `lod2Distance`: past that distance the third mesh stands in for the cheaper one, until the kind stops being drawn as itself. The Terrain & Water example's trees have one (a tenth of the triangles, made by `tools/plant-lod2.mjs`) from 80 m, which takes 9 to 15 ms off a frame on an RTX 3060 where trees stand between 60 and 170 m. `tools/terrain-water-cost.mjs` measures what each part of that example costs a frame headless, and `docs/TERRAIN_WATER_GPU_COST.md` has the numbers.- **A generated world on worker threads.** A planet provider can give the engine its generator as `workerSource` (the text of a self-contained module), and the world's placements and the planet's pages (heights, normals, and the paint by the biomes) are then worked out by a pool of workers (`runtime/jobs.ts`), byte for byte what the main thread works out, while the main thread only puts each answer in the world as it arrives. Laying out a planet's world no longer costs the frame: 2 to 8 frames a second while it was laid out became 60.@@ -30,6 +31,7 @@ published separately; it ships inside the editor.### Changed+- **A multisampled frame is not written out on a tile-based GPU.** The samples of a multisampled target, once resolved and with nothing left to draw on it, the depth of a shadow pass (the map keeps its depth in colour), and the default framebuffer's depth and stencil at the end of a frame are now said not to be needed, which a phone's GPU takes as not writing them to memory. The picture is the same on both backends; it changes nothing measurable on a desktop GPU and is most of a multisampled frame's memory traffic on a phone, which is where it was not measured.- **A sun's shadow map leaves out the casters that shade nothing the camera sees.** A directional light with a fixed reach (`shadowExtent`) draws one map of its whole reach, so every caster in it was drawn however much of it the camera looked at. A caster's shadow is the segment its bounds sweep along the light's rays down to the lowest thing that can receive it; one whose segment stays outside the camera's view is no longer drawn into the map. The picture is the same (a mean difference under half a level on the Terrain & Water example); its shadow pass is 4.0 to 1.7 ms and 4.7 to 1.4 ms at two of its viewpoints on an RTX 3060, and unchanged where the camera sees the whole island. A cascaded sun (no `shadowExtent`) already fits its maps to the view and is as it was; a frame with a planar reflection keeps every caster.- **The sea takes the sun's shadow as one hard edge.** The water lit itself with the sun's full soft shadow (a search for blockers and a filter of up to sixty-four taps), which a surface the sun seldom leaves and whose edge the waves hide does not need; a shader can now set `g_shadowHard` before it lights to read the shadow as the edge a source with no size throws, nine taps, and the water does. The picture is the same to the eye (a mean difference of a quarter of a level on the Terrain & Water example); the water is about 0.5 ms shorter on an RTX 3060.- **A lit surface no longer works out the light slots nothing shines from.** The light block holds sixteen lights and a scene has one or two, but the lighting loop shaded all sixteen: every empty slot paid for its distance, its direction and the whole specular lobe, to add zero. A slot with no intensity returns at once now; the picture is the same to the pixel gates on WebGL2 and WebGPU. A frame of the Terrain & Water example is 4 to 6 ms shorter on an RTX 3060 (the trees' shading alone is more than a third faster).diff --git a/docs/TERRAIN_WATER_GPU_COST.md b/docs/TERRAIN_WATER_GPU_COST.mdindex 2f8e32e6e..a78380d83 100644--- a/docs/TERRAIN_WATER_GPU_COST.md+++ b/docs/TERRAIN_WATER_GPU_COST.md@@ -476,3 +476,19 @@| 画面平均差 | | 0.27 / 1.12 / 1.42(机位 1 / 0 / 3),差超过 24 的像素 0.1% 到 0.3%:灌木、石头、箱子的影子出现了 |`mesh-shadow-small` 渲染场景在两个后端上钉住它(范围 8000,60 单位投射体的影子必须在)。18 个阴影与光照场景在两个后端都通过。++### Web:着色器首次编译(2026-10-26)++`node tools/shader-compile-cost.mjs [--dir 包] [--async]`:包上的 WebGL 调用都被计时,浏览器的着色器缓存关掉(等于第一次访问)。示例在 Chrome、D3D11 上:++| | 同步(原来) | `asyncShaderCompile` 开 |+|---|---|---|+| 页面被编译卡住的总时长 | 42.6 s | 约 1 s |+| 最长的一帧 | 10.0 s | 1.1 s |+| 场景画全的时刻(页面时间) | 55.8 s | 20.1 s |++- **链接才是慢的地方,不是编译。**一个 50 到 73 KB 片元的光照着色器,`COMPILE_STATUS` 几毫秒,`LINK_STATUS` 3 到 10 秒(ANGLE 在链接时才把 GLSL 翻成 HLSL 再交给 D3D 编译)。示例首次访问共 39 个程序。+- **并行是真的。**把同一个 3.2 秒的程序复制 6 份:一份份等是 19.2 s,全部发出去再等是 5.1 s,发出去只要 1 ms,轮询 `COMPLETION_STATUS_KHR` 期间页面一直在响应(1100 次定时器)。机器 20 个核。+- **只做"延迟链接"不够。**材质变体是一帧一个、创建完马上要画的,没有重叠(43.5 s 对 49.8 s);要**让帧别等**:没好的程序,画它的绘制先跳过(`GfxDevice::setSkipPendingPrograms`)。材质着色器、后处理着色器、默认网格着色器、网格变体都是排队创建,第一个要用的才等(`GfxShaderSource::deferLink`、`Shader::whenLinked`)。+- **试过没用的:**把阴影采样改成 `textureLod`(想让 ANGLE 不展开循环)——编译反而慢了一个数量级(单个程序 37 到 82 s),已还原。哪些代码贡献最多(剪掉实验):阴影接收约 60%(10.9 s → 4.4 s),地形 8 层混合循环约 55%(10.9 → 5.0 s);灯循环只占一成多。减小这些着色器本身还能再省,没做。+- 选项默认关,和动态分辨率一样是显式开启:开了以后第一次看到的画面会有东西"长出来"。diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 62f0b3b88..d5ad8a627 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -7623,6 +7623,7 @@ ResourceDef<QualityController | null>## QualityConfig — interface @experimental```+asyncShaderCompile: boolean | undefineddeviceRules: DeviceQualityRule[] | undefineddynamicResolution: boolean | undefinedmode: QualityMode | undefineddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 47abe5194..552ecc929 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -7826,6 +7826,7 @@ ResourceDef<QualityController | null>## QualityConfig — interface @experimental```+asyncShaderCompile: boolean | undefineddeviceRules: DeviceQualityRule[] | undefineddynamicResolution: boolean | undefinedmode: QualityMode | undefineddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex ce5df1f9c..966f46b72 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -7618,6 +7618,7 @@ ResourceDef<QualityController | null>## QualityConfig — interface @experimental```+asyncShaderCompile: boolean | undefineddeviceRules: DeviceQualityRule[] | undefineddynamicResolution: boolean | undefinedmode: QualityMode | undefineddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex d03f679c7..e3d6958ff 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -7911,6 +7911,7 @@ ResourceDef<QualityController | null>## QualityConfig — interface @experimental```+asyncShaderCompile: boolean | undefineddeviceRules: DeviceQualityRule[] | undefineddynamicResolution: boolean | undefinedmode: QualityMode | undefineddiff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.mdindex fadc9edae..b1cc53f6b 100644--- a/sdk/etc/wasm.api.md+++ b/sdk/etc/wasm.api.md@@ -475,6 +475,7 @@ renderer_getEstimatedGpuBytes: (() => number) | undefinedrenderer_getGpuTimeMs: (() => number) | undefinedrenderer_getLiveObjects: (() => GfxLiveObjects | null) | undefinedrenderer_getMeshes: () => number+renderer_getPendingShaders: (() => number) | undefinedrenderer_getPlanarReflectionStatus: ((view: number, entity: number) => string) | undefinedrenderer_getPreviewHeight: () => numberrenderer_getPreviewPtr: () => number@@ -510,6 +511,7 @@ renderer_renderMeshPreview: (meshId: number, w: number, h: number) => voidrenderer_renderSkeletalPreview: (preview: number, viewProjectionPtr: number) => numberrenderer_replayToDrawCall: (drawCallIndex: number) => voidrenderer_resize: (width: number, height: number) => void+renderer_setAsyncShaderCompile: ((on: boolean) => void) | undefinedrenderer_setClearColor: (r: number, g: number, b: number, a: number) => voidrenderer_setColorSpace: ((linear: number) => void) | undefinedrenderer_setCullingMask: ((mask: number) => void) | undefineddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 0ddc29cfc..02df99b38 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -7625,6 +7625,7 @@ ResourceDef<QualityController | null>## QualityConfig — interface @experimental```+asyncShaderCompile: boolean | undefineddeviceRules: DeviceQualityRule[] | undefineddynamicResolution: boolean | undefinedmode: QualityMode | undefineddiff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.tsindex 93289bc64..3d398efdd 100644--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts@@ -174,6 +174,7 @@ export interface NativeEngineApi {renderer_getEstimatedGpuBytes?(): number;renderer_getGpuTimeMs?(): number;renderer_getMeshes?(): number;+ renderer_getPendingShaders?(): number;renderer_getPlanarReflectionStatus?(view: number, entity: number): string;renderer_getPreviewHeight?(): number;renderer_getPreviewSize?(): number;@@ -206,6 +207,7 @@ export interface NativeEngineApi {renderer_renderSkeletalPreview?(preview: number, viewProjectionPtr: number): number;renderer_replayToDrawCall?(drawCallIndex: number): void;renderer_resize?(width: number, height: number): void;+ renderer_setAsyncShaderCompile?(on: boolean): void;renderer_setClearColor?(r: number, g: number, b: number, a: number): void;renderer_setColorSpace?(linear: number): void;renderer_setCullingMask?(mask: number): void;@@ -501,6 +503,7 @@ export function createNativeEngineApi(bind('renderer_getEstimatedGpuBytes', 'es_renderer_getEstimatedGpuBytes', false);bind('renderer_getGpuTimeMs', 'es_renderer_getGpuTimeMs', false);bind('renderer_getMeshes', 'es_renderer_getMeshes', false);+ bind('renderer_getPendingShaders', 'es_renderer_getPendingShaders', false);bind('renderer_getPlanarReflectionStatus', 'es_renderer_getPlanarReflectionStatus', false);bind('renderer_getPreviewHeight', 'es_renderer_getPreviewHeight', false);bind('renderer_getPreviewSize', 'es_renderer_getPreviewSize', false);@@ -533,6 +536,7 @@ export function createNativeEngineApi(bind('renderer_renderSkeletalPreview', 'es_renderer_renderSkeletalPreview', false);bind('renderer_replayToDrawCall', 'es_renderer_replayToDrawCall', false);bind('renderer_resize', 'es_renderer_resize', false);+ bind('renderer_setAsyncShaderCompile', 'es_renderer_setAsyncShaderCompile', false);bind('renderer_setClearColor', 'es_renderer_setClearColor', false);bind('renderer_setColorSpace', 'es_renderer_setColorSpace', false);bind('renderer_setCullingMask', 'es_renderer_setCullingMask', false);diff --git a/sdk/src/render/quality.ts b/sdk/src/render/quality.tsindex 7749a2fcd..7ead0a610 100644--- a/sdk/src/render/quality.ts+++ b/sdk/src/render/quality.ts@@ -74,6 +74,12 @@ export interface QualityConfig {mode?: QualityMode;targetFps?: number;dynamicResolution?: boolean;+ /**+ * A frame never waits for a shader the browser is still compiling: what needs it is left out until it is ready, and several compile at once. Off+ * (the default) the first draw to need a shader waits for it, which keeps every frame complete and can stop one for seconds on a first visit+ * (a heavy lit shader on a driver that compiles slowly). Turn it on for a game that would rather open fast and fill in.+ */+ asyncShaderCompile?: boolean;profiles?: Partial<Record<QualityLevel, Partial<QualityProfile>>>;deviceRules?: DeviceQualityRule[];}@@ -126,6 +132,7 @@ export function parseQualityConfig(value: unknown): QualityConfig {const config: QualityConfig = {mode, targetFps: finite(raw.targetFps, 60, 15, 120),dynamicResolution: raw.dynamicResolution === true,+ asyncShaderCompile: raw.asyncShaderCompile === true,};if (raw.profiles) {config.profiles = {};diff --git a/sdk/src/render/qualityRuntime.ts b/sdk/src/render/qualityRuntime.tsindex 63169910a..b7a851bf4 100644--- a/sdk/src/render/qualityRuntime.ts+++ b/sdk/src/render/qualityRuntime.ts@@ -19,6 +19,8 @@ export function installQuality(app: App, config: QualityConfig, authoredMsaa: numodel: platform.deviceName?.(), ...info, gpu,});app.insertResource(Quality, quality);+ // A delivery choice and not a level of quality: it holds whatever the level, and whether the quality system is on at all.+ engineApi(app)?.renderer_setAsyncShaderCompile?.(config.asyncShaderCompile === true);let applied: Readonly<QualityProfile> | null = null;let enabled: boolean | null = null;let last = 0;diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 1bef65497..28ef219df 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -700,6 +700,8 @@ export interface ESEngineModule {renderer_setShadowDistance?(distance: number): void;/** Draw the opaque scene twice, depth alone first, so a pixel is shaded for the surface in front of it. */renderer_setDepthPrepass?(on: boolean): void;+ renderer_setAsyncShaderCompile?(on: boolean): void;+ renderer_getPendingShaders?(): number;renderer_setPlanarReflectionQuality?(scale: number, maxSize: number, updatesPerSecond: number): void;renderer_getPlanarReflectionStatus?(view: number, entity: number): string;renderer_setViewLighting?(mode: number, rotationDegrees: number, keyIntensity: number, fillIntensity: number, skyIntensity: number, showSky: boolean): void;diff --git a/sdk/tests/quality-runtime.test.ts b/sdk/tests/quality-runtime.test.tsindex bf4978502..0805a280b 100644--- a/sdk/tests/quality-runtime.test.ts+++ b/sdk/tests/quality-runtime.test.ts@@ -12,10 +12,10 @@ vi.mock('../src/platform', () => ({platformOnAppHide: () => () => {}, platformOnAppShow: () => () => {},}));vi.mock('../src/ecs/bridge/engineApi', () => ({- engineApi: () => ({ renderer_setQualityBudgets: vi.fn(), renderer_setShadowDistance: distanceBudget, renderer_setPlanarReflectionQuality: reflectionBudget, renderer_setDepthPrepass: prepass }),+ engineApi: () => ({ renderer_setQualityBudgets: vi.fn(), renderer_setShadowDistance: distanceBudget, renderer_setPlanarReflectionQuality: reflectionBudget, renderer_setDepthPrepass: prepass, renderer_setAsyncShaderCompile: asyncCompile }),}));-const { distanceBudget, reflectionBudget, prepass } = vi.hoisted(() => ({ distanceBudget: vi.fn(), reflectionBudget: vi.fn(), prepass: vi.fn() }));+const { distanceBudget, reflectionBudget, prepass, asyncCompile } = vi.hoisted(() => ({ distanceBudget: vi.fn(), reflectionBudget: vi.fn(), prepass: vi.fn(), asyncCompile: vi.fn() }));describe('quality runtime device selection', () => {it('applies the tier shadow range and restores camera coverage when disabled', () => {@@ -48,6 +48,15 @@ describe('quality runtime device selection', () => {controller!.setMode('off'); apply!();expect(prepass).toHaveBeenLastCalledWith(false);});+ it('leaves shader compiles waited for unless the config asks for them not to be, whatever the level', () => {+ const app = { wasmModule: null, insertResource: vi.fn(), addPlugin: vi.fn(), onFrameEnd: () => () => {} } as unknown as App;+ installQuality(app, { mode: 'high' }, 4);+ expect(asyncCompile).toHaveBeenLastCalledWith(false);+ installQuality(app, { mode: 'off', asyncShaderCompile: true }, 4);+ expect(asyncCompile).toHaveBeenLastCalledWith(true);+ installQuality(app, { mode: 'low', asyncShaderCompile: true }, 4);+ expect(asyncCompile).toHaveBeenLastCalledWith(true);+ });it('uses this app’s actual renderer identity when a GPU rule matches', () => {const insertResource = vi.fn();const wasmModule = { deviceIdentity: () => 'WebGL2|NVIDIA|RTX 3060|driver' } as ESEngineModule;diff --git a/src/esengine/bindings/MaterialBindings.cpp b/src/esengine/bindings/MaterialBindings.cppindex ec840f423..55553425b 100644--- a/src/esengine/bindings/MaterialBindings.cpp+++ b/src/esengine/bindings/MaterialBindings.cpp@@ -48,8 +48,10 @@ u32 material_compileEsshader(const std::string& source, const std::string& featu}// No DrawParams rewrite: assembled material sources already carry their// params in MaterialConstants; only sampler uniforms remain loose.+ // A material shader the package ships, and a post-process effect: both known to compile, so with the async policy on they are queued+ // and waited for by whoever draws with them, not one by one here.resource::ShaderHandle handle = rm->createShader(vert, frag, /*rewriteLoose=*/false,- rm->preferredShaderLanguage());+ rm->preferredShaderLanguage(), rm->deferLinks());if (!handle.isValid()) return 0;if (auto* rc = g_renderContext) {if (Shader* s = rm->getShader(handle)) {diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cppindex 60fd368e7..67f6adbcb 100644--- a/src/esengine/bindings/RendererBindings.cpp+++ b/src/esengine/bindings/RendererBindings.cpp@@ -1166,6 +1166,15 @@ void renderer_setDepthPrepass(bool on) {if (g_renderFrame) g_renderFrame->setDepthPrepass(on);}+void renderer_setAsyncShaderCompile(bool on) {+ if (auto* device = g_device) device->setSkipPendingPrograms(on);+}++u32 renderer_getPendingShaders() {+ auto* device = g_device;+ return device ? device->pendingProgramCount() : 0u;+}+// Which layers the NEXT collect draws. Set per camera, before renderer_submitAll.void renderer_setCullingMask(u32 mask) {if (auto* frame = g_renderFrame) frame->setCullingMask(mask);diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hppindex 5c86918ec..6a7d71435 100644--- a/src/esengine/bindings/RendererBindings.hpp+++ b/src/esengine/bindings/RendererBindings.hpp@@ -27,6 +27,13 @@ void renderer_resize(u32 width, u32 height);void renderer_setQualityBudgets(u32 atlasSize, u32 cellSize, u32 cascades, u32 particleLimit);void renderer_setShadowDistance(f32 distance);void renderer_setDepthPrepass(bool on);+/**+ * Draws whose shader the browser is still compiling are left out, not waited for: a frame never stops for a compile, and what needs the shader+ * appears when it is done (several at once compile side by side, which the waiting form never gives them). Off (the default) is a frame that waits.+ */+void renderer_setAsyncShaderCompile(bool on);+/** How many shaders are still compiling in the background; a loading screen waits for it to reach 0. */+u32 renderer_getPendingShaders();void renderer_setPlanarReflectionQuality(f32 scale, u32 maxSize, f32 updatesPerSecond);std::string renderer_getPlanarReflectionStatus(u32 view, u32 entity);/**diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 95da58451..c28dfb707 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -789,6 +789,8 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("renderer_setQualityBudgets", &esengine::renderer_setQualityBudgets);emscripten::function("renderer_setShadowDistance", &esengine::renderer_setShadowDistance);emscripten::function("renderer_setDepthPrepass", &esengine::renderer_setDepthPrepass);+ emscripten::function("renderer_setAsyncShaderCompile", &esengine::renderer_setAsyncShaderCompile);+ emscripten::function("renderer_getPendingShaders", &esengine::renderer_getPendingShaders);emscripten::function("renderer_setPlanarReflectionQuality", &esengine::renderer_setPlanarReflectionQuality);emscripten::function("renderer_getPlanarReflectionStatus", &esengine::renderer_getPlanarReflectionStatus);emscripten::function("renderer_setViewLighting", &esengine::renderer_setViewLighting);diff --git a/src/esengine/renderer/draw/DrawList.cpp b/src/esengine/renderer/draw/DrawList.cppindex bbeccd75a..15a7debaa 100644--- a/src/esengine/renderer/draw/DrawList.cpp+++ b/src/esengine/renderer/draw/DrawList.cpp@@ -406,6 +406,8 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,PipelineDesc lastDesc{};PipelineHandle lastHandle = PipelineHandle::Invalid;const std::string* lastRun = nullptr;+ skipped_for_program_ = 0;+ const bool skipUnready = device.skipPendingPrograms();// The draws of this phase read the scene's colour and compose it under themselves.const bool composes = phase == Phase::SceneColorOnly;@@ -486,6 +488,12 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,desc.depthWrite = false;}+ // A program still compiling in the background: this draw waits for a later frame instead of making this one wait for it.+ if (skipUnready && desc.program != ShaderHandle::Invalid && !device.programReady(desc.program)) {+ ++skipped_for_program_;+ continue;+ }+if (lastHandle == PipelineHandle::Invalid || !(desc == lastDesc)) {lastHandle = device.createPipeline(desc);lastDesc = desc;diff --git a/src/esengine/renderer/draw/DrawList.hpp b/src/esengine/renderer/draw/DrawList.hppindex fbfd9e975..d2c68b6ba 100644--- a/src/esengine/renderer/draw/DrawList.hpp+++ b/src/esengine/renderer/draw/DrawList.hpp@@ -74,6 +74,9 @@ public:/// the scene a shader at a time. Empty costs nothing; a sink is installed only while someone is measuring.void setShaderRunSink(std::function<void(const char*)> sink) { shader_run_sink_ = std::move(sink); }+ /// How many merged draws the last execute left out because their program was not ready (GfxDevice::setSkipPendingPrograms).+ u32 skippedForProgram() const { return skipped_for_program_; }+/// How many of the merged draws take part in a depth prepass; 0 means a prepass has nothing to draw.u32 depthPrepassDraws() const;@@ -222,6 +225,7 @@ public:private:std::function<void(const char*)> shader_run_sink_;+ u32 skipped_for_program_ = 0;struct SortEntry {u64 key;u32 index;diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex 6d72b1604..0d5285b13 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -340,6 +340,10 @@ void RenderFrame::drawScene(DrawList::Phase phase) {draw_list_.setShaderRunSink(nullptr);}draw_list_.setGBufferPass(false);+ if (device_.skipPendingPrograms()) {+ ES_PROFILE_COUNTER("render.draws.waitingForProgram", draw_list_.skippedForProgram());+ ES_PROFILE_COUNTER("render.programs.pending", device_.pendingProgramCount());+ }}// Handed over to whatever the graph runs next. Blend/depth/colour-mask come@@ -2288,6 +2292,8 @@ void RenderFrame::declareShadowPass(ecs::Registry& registry) {rg::PassDesc shadow;shadow.name = "shadow-atlas";shadow.write = shadow_resource_;+ // The map is the packed depth in its colour; the depth buffer beside it only orders the casters while they are drawn.+ shadow.discardDepth = true;// One pass for every map the frame renders, because they share an attachment:// a point light's six faces are six viewports inside this pass rather than six// passes the device has to transition the atlas between.diff --git a/src/esengine/renderer/graph/RenderGraph.cpp b/src/esengine/renderer/graph/RenderGraph.cppindex 1521bc940..f914de3eb 100644--- a/src/esengine/renderer/graph/RenderGraph.cpp+++ b/src/esengine/renderer/graph/RenderGraph.cpp@@ -287,6 +287,13 @@ void RenderGraph::execute() {}}+ // The last live pass to draw on each resource: after it nothing continues on that target, so its multisampled attachments, resolved by+ // then, need not be kept.+ std::vector<i32> lastWriter(resources_.size(), -1);+ for (usize i = 0; i < passes_.size(); ++i) {+ if (live[i] && passes_[i].write < resources_.size()) lastWriter[passes_[i].write] = static_cast<i32>(i);+ }+for (usize i = 0; i < passes_.size(); ++i) {if (!live[i]) continue;PassDesc& pass = passes_[i];@@ -334,6 +341,8 @@ void RenderGraph::execute() {RenderPassDesc rp{};rp.target = fbo;+ rp.discardMultisampled = target.kind == Kind::Transient && lastWriter[pass.write] == static_cast<i32>(i);+ rp.discardDepth = pass.discardDepth;rp.clearColor = pass.clear;rp.clearDepth = pass.clearDepth;if (pass.clear) {diff --git a/src/esengine/renderer/graph/RenderGraph.hpp b/src/esengine/renderer/graph/RenderGraph.hppindex 248427564..54093cf76 100644--- a/src/esengine/renderer/graph/RenderGraph.hpp+++ b/src/esengine/renderer/graph/RenderGraph.hpp@@ -110,6 +110,8 @@ struct PassDesc {* writing `ctx.output`, which has to be a target declared with `storage`. Ordered, culled and recycled like any pass.*/bool compute = false;+ /// Its target's depth is only for testing while it draws, and nothing reads it afterwards (see RenderPassDesc::discardDepth).+ bool discardDepth = false;bool clear = false;/// Clears the depth attachment with the colour, for a target that has one./// A geometry pass writes depth, so the frame before it is not what itdiff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cppindex 417acf9a2..a5ddaab87 100644--- a/src/esengine/renderer/plugins/MeshPlugin.cpp+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp@@ -433,16 +433,19 @@ u32 MeshPlugin::meshProgram(RenderFrameContext& ctx, u32 variant) {handle = ctx.resources.createShaderWithBindings(resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex, "", features, target),resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment, "", features, target),- {}, ctx.resources.preferredShaderLanguage());+ {}, ctx.resources.preferredShaderLanguage(), ctx.resources.deferLinks());Shader* shader = ctx.resources.getShader(handle);if (!shader || !shader->isValid()) return 0;if (shader->language() == GfxShaderLanguage::GLSL_ES300) {- shader->bind();- // A depth-only variant has no colour texture to seed.- if (shader->hasUniform("u_texture")) shader->setUniform("u_texture", 0);- // Slot 1 is where a draw's own second texture is bound (see pushBatchDraw).- if (normalMapped) shader->setUniform("u_normalMap", 1);- shader->unbind();+ // After it links: at once, or (where shaders are not waited for) when a draw first needs it.+ shader->whenLinked([normalMapped](Shader& s) {+ s.bind();+ // A depth-only variant has no colour texture to seed.+ if (s.hasUniform("u_texture")) s.setUniform("u_texture", 0);+ // Slot 1 is where a draw's own second texture is bound (see pushBatchDraw).+ if (normalMapped) s.setUniform("u_normalMap", 1);+ s.unbind();+ });}return shader->getProgramId();};diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cppindex b27340b2d..2af8215d7 100644--- a/src/esengine/renderer/rhi/GLDevice.cpp+++ b/src/esengine/renderer/rhi/GLDevice.cpp@@ -357,6 +357,10 @@ void GLDevice::onDeviceLost() {for (auto& [id, resolve] : framebuffer_resolve_) {if (resolve.destFbo) glDeleteFramebuffers(1, &resolve.destFbo);}+ for (auto& [id, shaders] : pending_programs_) {+ glDeleteShader(shaders.vertex);+ glDeleteShader(shaders.fragment);+ }for (usize id = 0; id < program_names_.size(); ++id) {if (program_names_[id]) glDeleteProgram(program_names_[id]);}@@ -383,6 +387,8 @@ bool GLDevice::recreateDevice() {texture_names_.clear();array_names_.clear();program_names_.clear();+ pending_programs_.clear();+ failed_programs_.clear();framebuffer_names_.clear();query_names_.clear();framebuffer_resolve_.clear();@@ -635,13 +641,16 @@ bool GLDevice::backendCreateProgram(u32 id, const GfxShaderSource& source,if (outFailedStage) *outFailedStage = stage;};+ // Deferred: compile and link are queued with no question asked in between, and the first thing that needs the program asks. A driver that+ // compiles on its own threads (ANGLE does, once the page does not wait) then works on every program asked for in the meantime at once.+ const bool defer = source.deferLink;GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);glShaderSource(vertexShader, 1, &vertexSrc, nullptr);glCompileShader(vertexShader);GLint success = 0;- glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);- if (!success) {+ if (!defer) glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);+ if (!defer && !success) {std::string log = readShaderInfoLog(vertexShader);ES_LOG_ERROR("Vertex shader compilation failed: {}", log);setFailure(GfxShaderStage::Vertex, std::move(log));@@ -653,8 +662,8 @@ bool GLDevice::backendCreateProgram(u32 id, const GfxShaderSource& source,glShaderSource(fragmentShader, 1, &fragmentSrc, nullptr);glCompileShader(fragmentShader);- glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);- if (!success) {+ if (!defer) glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);+ if (!defer && !success) {std::string log = readShaderInfoLog(fragmentShader);ES_LOG_ERROR("Fragment shader compilation failed: {}", log);setFailure(GfxShaderStage::Fragment, std::move(log));@@ -673,6 +682,13 @@ bool GLDevice::backendCreateProgram(u32 id, const GfxShaderSource& source,glLinkProgram(program);+ if (defer) {+ pending_programs_[id] = PendingProgram{vertexShader, fragmentShader};+ if (outFailedStage) *outFailedStage = GfxShaderStage::None;+ setName(program_names_, id, program);+ return true;+ }+glGetProgramiv(program, GL_LINK_STATUS, &success);if (!success) {std::string log = readProgramInfoLog(program);@@ -692,29 +708,90 @@ bool GLDevice::backendCreateProgram(u32 id, const GfxShaderSource& source,return true;}+u32 GLDevice::programName(u32 id) {+ if (!pending_programs_.empty() && pending_programs_.count(id)) backendFinishProgram(id);+ return nameOf(program_names_, id);+}++bool GLDevice::backendFinishProgram(u32 id) {+ auto it = pending_programs_.find(id);+ if (it == pending_programs_.end()) return nameOf(program_names_, id) != 0;+ const PendingProgram shaders = it->second;+ pending_programs_.erase(it);+ const GLuint program = nameOf(program_names_, id);+ GLint success = 0;+ glGetProgramiv(program, GL_LINK_STATUS, &success);+ if (!success) {+ // Only now does anyone ask why: the stage that refused, then the link.+ GLint vertexOk = 0, fragmentOk = 0;+ glGetShaderiv(shaders.vertex, GL_COMPILE_STATUS, &vertexOk);+ glGetShaderiv(shaders.fragment, GL_COMPILE_STATUS, &fragmentOk);+ std::string why;+ if (!vertexOk) why += "vertex: " + readShaderInfoLog(shaders.vertex) + " ";+ if (!fragmentOk) why += "fragment: " + readShaderInfoLog(shaders.fragment) + " ";+ why += readProgramInfoLog(program);+ ES_LOG_ERROR("Deferred shader program {} failed to link: {}", id, why);+ glDeleteShader(shaders.vertex);+ glDeleteShader(shaders.fragment);+ glDeleteProgram(program);+ setName(program_names_, id, 0);+ failed_programs_.insert(id);+ return false;+ }+ glDeleteShader(shaders.vertex);+ glDeleteShader(shaders.fragment);+ notifyProgramLinked(id);+ return true;+}++bool GLDevice::backendProgramReady(u32 id) {+ if (failed_programs_.count(id)) return false;+ if (!pending_programs_.count(id)) return true;+#ifdef __EMSCRIPTEN__+ if (completion_status_ == 0) {+ const EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();+ completion_status_ = (ctx && emscripten_webgl_enable_extension(ctx, "KHR_parallel_shader_compile")) ? 1 : 2;+ }+ if (completion_status_ == 1) {+ // The browser's answer to "is it done", which does not make the page wait for it.+ constexpr GLenum kCompletionStatus = 0x91B1;+ GLint done = 0;+ glGetProgramiv(nameOf(program_names_, id), kCompletionStatus, &done);+ if (!done) return false;+ }+#endif+ // Done (or no way to tell, in which case the wait is the same one a draw would have made): finishing it now costs nothing.+ return backendFinishProgram(id);+}+void GLDevice::backendDeleteProgram(u32 id) {const u32 name = nameOf(program_names_, id);if (!name) return;+ if (auto it = pending_programs_.find(id); it != pending_programs_.end()) {+ glDeleteShader(it->second.vertex);+ glDeleteShader(it->second.fragment);+ pending_programs_.erase(it);+ }glDeleteProgram(name);if (current_program_name_ == name) current_program_name_ = 0;setName(program_names_, id, 0);}void GLDevice::backendUseProgram(u32 id) {- const u32 name = nameOf(program_names_, id);+ const u32 name = programName(id);if (name == current_program_name_) return;glUseProgram(name);current_program_name_ = name;}i32 GLDevice::backendUniformLocation(u32 program, const char* name) {- const u32 programName = nameOf(program_names_, program);- return programName ? glGetUniformLocation(programName, name) : -1;+ const u32 glName = programName(program);+ return glName ? glGetUniformLocation(glName, name) : -1;}i32 GLDevice::backendAttribLocation(u32 program, const char* name) {- const u32 programName = nameOf(program_names_, program);- return programName ? glGetAttribLocation(programName, name) : -1;+ const u32 glName = programName(program);+ return glName ? glGetAttribLocation(glName, name) : -1;}void GLDevice::backendSetUniform(i32 location, const GfxUniformValue& value) {@@ -760,7 +837,7 @@ GfxUniformType fromGLUniformType(GLenum type) {std::vector<GfxUniformInfo> GLDevice::backendActiveUniforms(u32 program) {std::vector<GfxUniformInfo> result;- const GLuint programId = nameOf(program_names_, program);+ const GLuint programId = programName(program);if (!programId) return result;GLint count = 0;@@ -801,14 +878,14 @@ std::vector<GfxUniformInfo> GLDevice::backendActiveUniforms(u32 program) {}u32 GLDevice::backendUniformBlockIndex(u32 program, const char* name) {- const u32 programName = nameOf(program_names_, program);- if (!programName) return GFX_INVALID_UNIFORM_BLOCK;- return static_cast<u32>(glGetUniformBlockIndex(programName, name));+ const u32 glName = programName(program);+ if (!glName) return GFX_INVALID_UNIFORM_BLOCK;+ return static_cast<u32>(glGetUniformBlockIndex(glName, name));}void GLDevice::backendUniformBlockBinding(u32 program, u32 nativeBlockIndex, u32 bindingPoint) {- const u32 programName = nameOf(program_names_, program);- if (programName) glUniformBlockBinding(programName, nativeBlockIndex, bindingPoint);+ const u32 glName = programName(program);+ if (glName) glUniformBlockBinding(glName, nativeBlockIndex, bindingPoint);}// =============================================================================@@ -1410,9 +1487,47 @@ void GLDevice::resolveFramebuffer(u32 framebufferId) {// differs, and depth refuses anything but NEAREST.glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_DEPTH_BUFFER_BIT, GL_NEAREST);}+ if (pass_discard_msaa_) {+ // Resolved, and nothing draws on it again: a tile-based GPU need not write the samples out to memory.+ GLenum attachments[4];+ GLsizei n = 0;+ attachments[n++] = GL_COLOR_ATTACHMENT0;+ if (r.gbuffer) attachments[n++] = GL_COLOR_ATTACHMENT1;+ attachments[n++] = GL_DEPTH_ATTACHMENT;+ attachments[n++] = GL_STENCIL_ATTACHMENT;+ glInvalidateFramebuffer(GL_READ_FRAMEBUFFER, n, attachments);+ }glBindFramebuffer(GL_FRAMEBUFFER, nameOf(framebuffer_names_, current_framebuffer_));}+void GLDevice::discardLeftDepth() {+ if (!pass_discard_depth_ || current_framebuffer_ == 0) return;+ const GLenum depth = GL_DEPTH_ATTACHMENT;+ glBindFramebuffer(GL_FRAMEBUFFER, nameOf(framebuffer_names_, current_framebuffer_));+ glInvalidateFramebuffer(GL_FRAMEBUFFER, 1, &depth);+}++void GLDevice::endFrame() {+ // The default framebuffer's depth and stencil are never read after the frame, which the page shows by its colour: a tile-based GPU that is told so+ // does not write them out. Only with that framebuffer bound, so nothing is rebound under whoever draws next.+ if (current_framebuffer_ != 0) return;+ if (default_depth_bits_ < 0) {+ GLint depth = 0, stencil = 0;+ glBindFramebuffer(GL_FRAMEBUFFER, 0);+ glGetIntegerv(GL_DEPTH_BITS, &depth);+ glGetIntegerv(GL_STENCIL_BITS, &stencil);+ default_depth_bits_ = depth > 0 ? 1 : 0;+ default_stencil_bits_ = stencil > 0 ? 1 : 0;+ }+ GLenum attachments[2];+ GLsizei n = 0;+ if (default_depth_bits_ > 0) attachments[n++] = GL_DEPTH;+ if (default_stencil_bits_ > 0) attachments[n++] = GL_STENCIL;+ if (n == 0) return;+ glBindFramebuffer(GL_FRAMEBUFFER, 0);+ glInvalidateFramebuffer(GL_FRAMEBUFFER, n, attachments);+}+void GLDevice::backendDeleteFramebuffer(u32 id) {if (auto it = framebuffer_resolve_.find(id); it != framebuffer_resolve_.end()) {if (it->second.destFbo != 0) glDeleteFramebuffers(1, &it->second.destFbo);@@ -1433,7 +1548,12 @@ void GLDevice::beginRenderPass(const RenderPassDesc& desc) {// Retargeting LEAVES the previous target, and the model has no explicit pass// object to hang the resolve on — so leaving is the event, whether it comes// from endRenderPass or from being retargeted out from under.- if (current_framebuffer_ != target) resolveFramebuffer(current_framebuffer_);+ if (current_framebuffer_ != target) {+ resolveFramebuffer(current_framebuffer_);+ discardLeftDepth();+ }+ pass_discard_msaa_ = desc.discardMultisampled;+ pass_discard_depth_ = desc.discardDepth;current_framebuffer_ = target;glBindFramebuffer(GL_FRAMEBUFFER, nameOf(framebuffer_names_, target));@@ -1513,6 +1633,9 @@ void GLDevice::applyDrawBuffers(bool gbuffer) {void GLDevice::endRenderPass() {resolveFramebuffer(current_framebuffer_);+ discardLeftDepth();+ pass_discard_msaa_ = false;+ pass_discard_depth_ = false;current_framebuffer_ = 0;current_fbo_has_gbuffer_ = false;glBindFramebuffer(GL_FRAMEBUFFER, 0);diff --git a/src/esengine/renderer/rhi/GLDevice.hpp b/src/esengine/renderer/rhi/GLDevice.hppindex 6d0b562d1..5336f9800 100644--- a/src/esengine/renderer/rhi/GLDevice.hpp+++ b/src/esengine/renderer/rhi/GLDevice.hpp@@ -137,6 +137,13 @@ protected:u32 primitiveMode() const;void backendInvalidatePipelineCache() override;+ bool supportsDeferredLink() const override { return true; }+ bool backendProgramPending(u32 id) const override { return pending_programs_.count(id) != 0; }+ bool backendFinishProgram(u32 id) override;+ void endFrame() override;+ bool backendProgramReady(u32 id) override;+ u32 backendPendingProgramCount() const override { return static_cast<u32>(pending_programs_.size()); }+bool backendCreateFramebuffer(u32 id, const FramebufferDesc& desc) override;void backendDeleteFramebuffer(u32 id) override;@@ -209,6 +216,23 @@ private:std::vector<u32> buffer_names_;std::vector<u32> texture_names_;std::vector<u32> program_names_;+ /// A program made with deferLink, until something waits for it: the shader objects to delete once it has linked.+ struct PendingProgram { u32 vertex = 0; u32 fragment = 0; };+ std::unordered_map<u32, PendingProgram> pending_programs_;+ /// The program's GL name, waiting for it first if it was deferred: every use of a program goes through here.+ u32 programName(u32 id);+ /// What the pass now running said of its attachments (RenderPassDesc::discard*), acted on when it is left.+ bool pass_discard_msaa_ = false;+ bool pass_discard_depth_ = false;+ /// What the default framebuffer has to be told to forget at the end of a frame: its depth and its stencil, where it has them (-1 not yet asked).+ i8 default_depth_bits_ = -1;+ i8 default_stencil_bits_ = -1;+ /// The target being left: its depth, if the pass said nothing reads it.+ void discardLeftDepth();+ /// Programs whose link failed, found out when something first asked: never ready, so a draw that skips what is not ready skips them for good.+ std::unordered_set<u32> failed_programs_;+ /// 0 unknown, 1 the browser reports a program's completion without waiting for it (KHR_parallel_shader_compile), 2 it does not.+ i8 completion_status_ = 0;std::vector<u32> framebuffer_names_;std::vector<u32> query_names_;/** Buffer id per uniform binding slot, as the renderer set it. */diff --git a/src/esengine/renderer/rhi/GfxDevice.cpp b/src/esengine/renderer/rhi/GfxDevice.cppindex beb87b3b6..bb3f948a7 100644--- a/src/esengine/renderer/rhi/GfxDevice.cpp+++ b/src/esengine/renderer/rhi/GfxDevice.cpp@@ -114,6 +114,9 @@ void GfxDevice::realizeRegistry() {static_cast<u32>(bindings.size()), &log, &stage);if (record.realized) {realizeProgramState(id, record);+ // A program that was queued and never waited for before the loss has linked now, and what was owed to it (its block bindings,+ // its pinned samplers) is done here rather than when a draw first asks.+ if (record.onLinked) notifyProgramLinked(id);} else {ES_LOG_ERROR("Device recovery: program {} did not rebuild: {}", id, log);}@@ -611,6 +614,29 @@ ShaderHandle GfxDevice::createProgram(const GfxShaderSource& source,return ShaderHandle{id};}+void GfxDevice::onProgramLinked(ShaderHandle program, std::function<void()> callback) {+ const u32 id = static_cast<u32>(program);+ auto* record = registry_.programs.find(id);+ if (!record || !callback) return;+ if (backendProgramPending(id)) {+ record->onLinked = std::move(callback);+ return;+ }+ callback();+}++void GfxDevice::notifyProgramLinked(u32 id) {+ auto* record = registry_.programs.find(id);+ if (!record || !record->onLinked) return;+ auto callback = std::move(record->onLinked);+ record->onLinked = nullptr;+ // The callback binds programs of its own (a sampler is pinned through the bound one); the draw that waited for this one has it bound.+ const ShaderHandle bound = current_program_;+ callback();+ current_program_ = bound;+ backendUseProgram(registry_.programs.find(static_cast<u32>(bound)) ? static_cast<u32>(bound) : 0u);+}+void GfxDevice::deleteProgram(ShaderHandle program) {const u32 id = static_cast<u32>(program);auto* record = registry_.programs.find(id);diff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hppindex bb4302430..abb84a31f 100644--- a/src/esengine/renderer/rhi/GfxDevice.hpp+++ b/src/esengine/renderer/rhi/GfxDevice.hpp@@ -493,6 +493,35 @@ public:/** @brief Whether this backend compiles @p language (GL: GLSL ES 300; WebGPU: WGSL). */virtual bool supportsShaderLanguage(GfxShaderLanguage language) const = 0;+ /** @brief Whether createProgram honours GfxShaderSource::deferLink (GL: yes; a backend that links at once does not). */+ virtual bool supportsDeferredLink() const { return false; }++ /**+ * @brief Runs @p callback when @p program has linked, once: now if it already has, at the first thing that needs it otherwise.+ * @details For what has to be done to a program only after it links. Never runs for one that fails.+ */+ void onProgramLinked(ShaderHandle program, std::function<void()> callback);++ /** @brief Waits for @p program to link if it has not yet. False when it failed to. */+ bool finishProgram(ShaderHandle program) { return backendFinishProgram(static_cast<u32>(program)); }++ /**+ * @brief Whether @p program can be drawn with now, without waiting: linked, or finished linking in the background (and then finished here, which+ * is quick). False while it is still compiling, and for one that failed. Always true for a program that was not deferred.+ */+ bool programReady(ShaderHandle program) { return backendProgramReady(static_cast<u32>(program)); }++ /** @brief How many programs made with deferLink nothing has waited for yet. */+ u32 pendingProgramCount() const { return backendPendingProgramCount(); }++ /**+ * @brief Whether a draw whose program is not ready is left out, instead of waited for.+ * @details Off: the first draw to need a program waits for it, and a frame that needs one the browser has not compiled yet stops (seconds, for a+ * heavy lit shader on a driver that compiles slowly). On: the draw is skipped until the program is ready, and the frame goes on.+ */+ void setSkipPendingPrograms(bool on) { skip_pending_programs_ = on; }+ bool skipPendingPrograms() const { return skip_pending_programs_; }+/*** @brief Whether texel (0,0) of a rendered texture is its TOP-left corner.*@@ -851,6 +880,14 @@ protected:const GfxAttribBinding* bindings, u32 bindingCount,std::string* outLog, GfxShaderStage* outFailedStage) = 0;virtual void backendDeleteProgram(u32 id) = 0;+ /** @brief True while a program created with deferLink has not been waited for. */+ virtual bool backendProgramPending(u32 id) const { (void)id; return false; }+ virtual bool backendProgramReady(u32 id) { (void)id; return true; }+ virtual u32 backendPendingProgramCount() const { return 0; }+ /** @brief Waits for a deferred program, runs its onLinked callback; false when it failed to link. True for a program that was not deferred. */+ virtual bool backendFinishProgram(u32 id) { (void)id; return true; }+ /** @brief For a backend finishing a deferred program: runs its onLinked callback, leaving the bound program as it was. */+ void notifyProgramLinked(u32 id);virtual void backendUseProgram(u32 id) = 0;/** @brief The backend's own location this generation, -1 when absent. */virtual i32 backendUniformLocation(u32 program, const char* name) = 0;@@ -953,6 +990,7 @@ private:usize retained_budget_ = 0;bool over_retained_budget_ = false;ShaderHandle current_program_ = ShaderHandle::Invalid;+ bool skip_pending_programs_ = false;PipelineHandle current_pipeline_ = PipelineHandle::Invalid;/// Native uniform locations per program for the current generation; -2 = not asked yet.std::map<u32, std::vector<i32>> native_locations_;diff --git a/src/esengine/renderer/rhi/GfxEnums.hpp b/src/esengine/renderer/rhi/GfxEnums.hppindex 963a4c65d..9f6eee11f 100644--- a/src/esengine/renderer/rhi/GfxEnums.hpp+++ b/src/esengine/renderer/rhi/GfxEnums.hpp@@ -469,6 +469,14 @@ struct RenderPassDesc {i32 clearStencilValue = 0;i32 clearX = 0, clearY = 0; ///< Clear region origin (pixels).u32 clearW = 0, clearH = 0; ///< Clear region size; 0 = the whole target.+ /**+ * What this pass leaves in the target's multisampled attachments is not drawn on or read again once it has been resolved: nothing later+ * continues on this target. A tile-based GPU keeps a pass's samples in memory on the chip and only writes them out if asked to; this says+ * it need not, which is most of the memory traffic of a multisampled frame on a phone. Ignored where the target is not multisampled.+ */+ bool discardMultisampled = false;+ /** The pass's depth attachment was there to test against and nothing reads it afterwards (a shadow map keeps its depth in colour). */+ bool discardDepth = false;};// =============================================================================@@ -631,6 +639,12 @@ struct GfxShaderSource {GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300;const char* vertexSrc = nullptr;const char* fragmentSrc = nullptr;+ /**+ * Where the backend can (GfxDevice::supportsDeferredLink), create the program without waiting for it to compile and link: the work is queued and+ * the wait is the first thing that needs the program (a draw, a uniform location). Programs asked for one after another then compile side by+ * side instead of one by one. A program that fails to link is only found out then; use it for source that is known to compile.+ */+ bool deferLink = false;};/** @brief A compute program's source. Compute is WGSL only: GLSL ES 3.00 has no compute stage. */diff --git a/src/esengine/renderer/rhi/GfxResourceRegistry.hpp b/src/esengine/renderer/rhi/GfxResourceRegistry.hppindex 6e9587db6..7a8c9b06e 100644--- a/src/esengine/renderer/rhi/GfxResourceRegistry.hpp+++ b/src/esengine/renderer/rhi/GfxResourceRegistry.hpp@@ -17,6 +17,7 @@#include "./PipelineState.hpp"#include <map>+#include <functional>#include <string>#include <utility>#include <vector>@@ -69,6 +70,8 @@ struct GfxProgramRecord {/// Binding point per block name, or GFX_UNBOUND_BLOCK.std::vector<u32> blockBindings;bool realized = false;+ /// What the owner of a program created with GfxShaderSource::deferLink does once it has linked (the block bindings, the pinned samplers). Run once.+ std::function<void()> onLinked;};inline constexpr u32 GFX_UNBOUND_BLOCK = 0xFFFFFFFFu;diff --git a/src/esengine/renderer/rhi/Shader.cpp b/src/esengine/renderer/rhi/Shader.cppindex e4a8dcde5..9ab2efb2d 100644--- a/src/esengine/renderer/rhi/Shader.cpp+++ b/src/esengine/renderer/rhi/Shader.cpp@@ -55,8 +55,12 @@ Shader::Shader(Shader&& other) noexcept, paramsShadow_(std::move(other.paramsShadow_)), paramsDirty_(other.paramsDirty_), paramsUbo_(other.paramsUbo_) {+ linked_ = other.linked_;+ afterLink_ = std::move(other.afterLink_);other.program_ = ShaderHandle::Invalid;other.paramsUbo_ = BufferHandle::Invalid;+ other.linked_ = true;+ if (!linked_ && device_) device_->onProgramLinked(program_, [this] { finishLink(); });}Shader& Shader::operator=(Shader&& other) noexcept {@@ -74,8 +78,12 @@ Shader& Shader::operator=(Shader&& other) noexcept {paramsShadow_ = std::move(other.paramsShadow_);paramsDirty_ = other.paramsDirty_;paramsUbo_ = other.paramsUbo_;+ linked_ = other.linked_;+ afterLink_ = std::move(other.afterLink_);other.program_ = ShaderHandle::Invalid;other.paramsUbo_ = BufferHandle::Invalid;+ other.linked_ = true;+ if (!linked_ && device_) device_->onProgramLinked(program_, [this] { finishLink(); });}return *this;}@@ -93,10 +101,10 @@ Unique<Shader> Shader::create(GfxDevice& device, const std::string& vertexSrc, cUnique<Shader> Shader::createWithBindings(GfxDevice& device,const std::string& vertexSrc, const std::string& fragmentSrc,std::initializer_list<AttribBinding> bindings,- GfxShaderLanguage language) {+ GfxShaderLanguage language, bool deferLink) {auto shader = makeUnique<Shader>();shader->device_ = &device;- if (!shader->compile(vertexSrc, fragmentSrc, bindings, nullptr, nullptr, language)) {+ if (!shader->compile(vertexSrc, fragmentSrc, bindings, nullptr, nullptr, language, deferLink)) {return nullptr;}return shader;@@ -145,9 +153,25 @@ Unique<Shader> Shader::createFromFile(GfxDevice& device,void Shader::bind() const {// Direct program bind for setup-time use (e.g. seeding a sampler uniform). Per-frame// rendering binds programs through GfxDevice::setPipeline, not here.+ ensureLinked();if (device_) device_->useProgram(program_);}+void Shader::ensureLinked() const {+ if (linked_ || !device_) return;+ // The device runs finishLink as the program links; a program that failed to never does, and is not waited for twice.+ if (!device_->finishProgram(program_)) linked_ = true;+}++void Shader::whenLinked(std::function<void(Shader&)> fn) {+ if (!fn) return;+ if (linked_) {+ fn(*this);+ return;+ }+ afterLink_.push_back(std::move(fn));+}+void Shader::unbind() const {if (device_) device_->useProgram(ShaderHandle::Invalid);}@@ -156,8 +180,10 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSrconst std::vector<AttribBinding>& bindings,std::string* outLog,ShaderStageFailure* outFailedStage,- GfxShaderLanguage language) {+ GfxShaderLanguage language,+ bool deferLink) {language_ = language;+ linked_ = false;// Fail fast on a language the backend cannot compile, before any GPU call —// the caller gets a diagnostic instead of a backend-specific compile error.@@ -176,6 +202,7 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSrGfxShaderStage stage = GfxShaderStage::None;GfxShaderSource source{language, vertexSrc.c_str(), fragmentSrc.c_str()};+ source.deferLink = deferLink && device_->supportsDeferredLink();program_ = device_->createProgram(source,binds.data(), static_cast<u32>(binds.size()),outLog, &stage);@@ -190,9 +217,21 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSr}if (program_ == ShaderHandle::Invalid) {+ linked_ = true;return false;}+ if (source.deferLink) {+ // Queued, not waited for: the device finishes it (block bindings, pinned samplers) when something first needs the program.+ device_->onProgramLinked(program_, [this] { finishLink(); });+ return true;+ }+ finishLink();+ return true;+}++void Shader::finishLink() {+ linked_ = true;reflectActiveUniforms();// Link the per-frame constants block to its shared binding point, so the program@@ -286,19 +325,22 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSrES_LOG_DEBUG("Shader compiled successfully (program handle: {}, active uniforms: {})",static_cast<u32>(program_), activeUniforms_.size());- return true;+ auto after = std::move(afterLink_);+ afterLink_.clear();+ for (auto& fn : after) fn(*this);}ShaderCompileOutcome Shader::createEx(GfxDevice& device,const std::string& vertexSrc,const std::string& fragmentSrc,std::initializer_list<AttribBinding> bindings,- GfxShaderLanguage language) {+ GfxShaderLanguage language,+ bool deferLink) {ShaderCompileOutcome outcome;auto shader = makeUnique<Shader>();shader->device_ = &device;if (!shader->compile(vertexSrc, fragmentSrc, bindings, &outcome.log, &outcome.failedStage,- language)) {+ language, deferLink)) {return outcome;}outcome.shader = std::move(shader);@@ -310,6 +352,7 @@ void Shader::reflectActiveUniforms() {}i32 Shader::cacheUniformLocation(const std::string& name, bool warnOnMiss) const {+ ensureLinked();auto [it, inserted] = uniformCache_.emplace(name, -1);if (inserted) {it->second = device_->getUniformLocation(program_, name.c_str());@@ -447,6 +490,7 @@ void Shader::setUniform(i32 location, const glm::mat4& value) const {}i32 Shader::getAttribLocation(const std::string& name) const {+ ensureLinked();auto [it, inserted] = attribCache_.emplace(name, -1);if (inserted) {it->second = device_->getAttribLocation(program_, name.c_str());diff --git a/src/esengine/renderer/rhi/Shader.hpp b/src/esengine/renderer/rhi/Shader.hppindex 7643f362d..fc7c7b095 100644--- a/src/esengine/renderer/rhi/Shader.hpp+++ b/src/esengine/renderer/rhi/Shader.hpp@@ -26,6 +26,7 @@// Standard library#include <initializer_list>+#include <functional>#include <string>#include <unordered_map>#include <vector>@@ -118,7 +119,8 @@ public:static Unique<Shader> createWithBindings(GfxDevice& device,const std::string& vertexSrc, const std::string& fragmentSrc,std::initializer_list<AttribBinding> bindings,- GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300);+ GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300,+ bool deferLink = false);/** @brief The source language this program was compiled from. */GfxShaderLanguage language() const { return language_; }@@ -143,7 +145,15 @@ public:const std::string& vertexSrc,const std::string& fragmentSrc,std::initializer_list<AttribBinding> bindings = {},- GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300);+ GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300,+ bool deferLink = false);++ /**+ * @brief Runs @p fn on this shader once it has linked: at once for one that has.+ * @details What is done to a program only after it links (a sampler pinned to its unit) is handed here, so a shader made with deferLink is not+ * waited for just to be finished.+ */+ void whenLinked(std::function<void(Shader&)> fn);// =========================================================================// Operations@@ -203,7 +213,7 @@ public:bool hasUniform(const std::string& name) const;/** @brief Returns reflected metadata for every active uniform, populated at link time */- const std::vector<GfxUniformInfo>& getActiveUniforms() const { return activeUniforms_; }+ const std::vector<GfxUniformInfo>& getActiveUniforms() const { ensureLinked(); return activeUniforms_; }// =========================================================================// DrawParams (per-draw parameter block)@@ -257,10 +267,16 @@ private:const std::vector<AttribBinding>& bindings = {},std::string* outLog = nullptr,ShaderStageFailure* outFailedStage = nullptr,- GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300);+ GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300,+ bool deferLink = false);void reflectActiveUniforms();+ /** @brief What is done to a linked program: reflect it, bind its blocks, pin its samplers, then whatever was asked for with whenLinked. */+ void finishLink();+ /** @brief Waits for the program to link if it was made with deferLink and nothing has needed it yet. */+ void ensureLinked() const;+/** @brief Resolve + cache a uniform location; warns on miss only when asked. */i32 cacheUniformLocation(const std::string& name, bool warnOnMiss) const;@@ -271,6 +287,9 @@ private:GfxDevice* device_ = nullptr; ///< Set by the create* factories; all GL goes through it.GfxShaderLanguage language_ = GfxShaderLanguage::GLSL_ES300;ShaderHandle program_ = ShaderHandle::Invalid;+ /// False from a deferLink creation until the program has linked and finishLink has run.+ mutable bool linked_ = true;+ std::vector<std::function<void(Shader&)>> afterLink_;/** @brief Cached uniform locations (mutable for const uniform setters) */mutable std::unordered_map<std::string, i32> uniformCache_;diff --git a/src/esengine/renderer/store/MaterialStore.cpp b/src/esengine/renderer/store/MaterialStore.cppindex 3769387cb..3176169f3 100644--- a/src/esengine/renderer/store/MaterialStore.cpp+++ b/src/esengine/renderer/store/MaterialStore.cpp@@ -156,7 +156,8 @@ u32 MaterialStore::shadowProgram(u32 materialId, resource::ResourceManager& resovariants[shape] = {};return 0;}- resource::ShaderHandle handle = resources.createShaderWithBindings(vert, frag, {}, resources.preferredShaderLanguage());+ // Deferred: the program is waited for by the first draw that uses it, so the programs a frame asks for together compile together.+ resource::ShaderHandle handle = resources.createShaderWithBindings(vert, frag, {}, resources.preferredShaderLanguage(), /*deferLink=*/true);Shader* shader = resources.getShader(handle);if (!shader || !shader->isValid()) {resources.releaseShader(handle);@@ -210,7 +211,7 @@ u32 MaterialStore::prepassCoverageProgram(u32 materialId, resource::ResourceManavariants[shape] = {};return 0;}- resource::ShaderHandle handle = resources.createShaderWithBindings(vert, frag, {}, resources.preferredShaderLanguage());+ resource::ShaderHandle handle = resources.createShaderWithBindings(vert, frag, {}, resources.preferredShaderLanguage(), /*deferLink=*/true);Shader* shader = resources.getShader(handle);if (!shader || !shader->isValid()) {resources.releaseShader(handle);@@ -283,7 +284,7 @@ u32 MaterialStore::variantProgram(u32 materialId, resource::ResourceManager& res}resource::ShaderHandle handle = resources.createShader(vert, frag, /*rewriteLoose=*/false,- resources.preferredShaderLanguage());+ resources.preferredShaderLanguage(), /*deferLink=*/true);Shader* shader = resources.getShader(handle);if (!shader || !shader->isValid()) {resources.releaseShader(handle);@@ -352,13 +353,18 @@ MaterialUniformLayout MaterialStore::layoutOf(const resource::ParsedShader& parsvoid MaterialStore::seedSamplers(Shader& shader, const resource::ParsedShader& parsed) {if (shader.language() != GfxShaderLanguage::GLSL_ES300) return;- shader.bind();+ std::vector<std::pair<std::string, i32>> seeds;for (const auto& p : parsed.properties) {if (p.fromParam && p.type == resource::ShaderPropertyType::Texture && p.textureUnit >= 0) {- shader.setUniform(p.name, static_cast<i32>(p.textureUnit));+ seeds.emplace_back(p.name, static_cast<i32>(p.textureUnit));}}- shader.unbind();+ // After the program links, which for one made with deferLink is when something first needs it.+ shader.whenLinked([seeds = std::move(seeds)](Shader& s) {+ s.bind();+ for (const auto& [name, unit] : seeds) s.setUniform(name, unit);+ s.unbind();+ });}void MaterialStore::bindForDraw(u32 materialId) {diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cppindex 054d31fe4..f9610a582 100644--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp@@ -2354,7 +2354,8 @@ void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {color.resolveTarget = resolveView;color.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;color.loadOp = toWGPULoadOp(desc.clearColor, scoped);- color.storeOp = WGPUStoreOp_Store;+ // Resolved into its single-sample twin by the pass itself; when nothing continues on this target the samples need not be kept.+ color.storeOp = (desc.discardMultisampled && resolveView) ? WGPUStoreOp_Discard : WGPUStoreOp_Store;color.clearValue = toWGPUClearColor(desc);// The surface record clears to zero — "nothing wrote here" — whatever the background is.@@ -2365,7 +2366,7 @@ void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {colors[1].resolveTarget = gbufferResolveView;colors[1].depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;colors[1].loadOp = toWGPULoadOp(desc.clearColor, scoped);- colors[1].storeOp = WGPUStoreOp_Store;+ colors[1].storeOp = (desc.discardMultisampled && gbufferResolveView) ? WGPUStoreOp_Discard : WGPUStoreOp_Store;colors[1].clearValue = {0.0, 0.0, 0.0, 0.0};}@@ -2377,7 +2378,8 @@ void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {if (dsView) {ds.view = dsView;ds.depthLoadOp = toWGPULoadOp(desc.clearDepth, scoped);- ds.depthStoreOp = WGPUStoreOp_Store;+ // Kept unless the pass said it is only for testing, and unless a multisampled one is resolved by hand after the pass.+ ds.depthStoreOp = (desc.discardDepth && pass_depth_msaa_ == 0) ? WGPUStoreOp_Discard : WGPUStoreOp_Store;ds.depthClearValue = 1.0f; // GL's default clear depth; no RHI override existsif (hasStencilPlanes(pass_ds_format_)) {ds.stencilLoadOp = toWGPULoadOp(desc.clearStencil, scoped);diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cppindex 28024b119..eb17ea783 100644--- a/src/esengine/resource/ResourceManager.cpp+++ b/src/esengine/resource/ResourceManager.cpp@@ -107,8 +107,12 @@ ShaderTargetLanguage ResourceManager::preferredShaderTarget() const {: ShaderTargetLanguage::GLSL_ES300;}+bool ResourceManager::deferLinks() const {+ return device_ && device_->skipPendingPrograms();+}+ShaderHandle ResourceManager::createShader(const std::string& vertSrc, const std::string& fragSrc,- bool rewriteLoose, GfxShaderLanguage language) {+ bool rewriteLoose, GfxShaderLanguage language, bool deferLink) {if (!device_) return {};// Lift loose non-sampler uniforms into a std140 DrawParams block, so this@@ -134,7 +138,7 @@ ShaderHandle ResourceManager::createShader(const std::string& vertSrc, const std// Through createEx for the LOG: the device already answers why it refused, and a// caller that drops it leaves "failed to create" as the only thing anybody sees.- auto outcome = Shader::createEx(*device_, vertSrc, fragSrc, {}, language);+ auto outcome = Shader::createEx(*device_, vertSrc, fragSrc, {}, language, deferLink);if (!outcome.shader) {ES_LOG_ERROR("Failed to create shader from source: {}",outcome.log.empty() ? "no reason given by the device" : outcome.log.c_str());@@ -145,9 +149,9 @@ ShaderHandle ResourceManager::createShader(const std::string& vertSrc, const stdShaderHandle ResourceManager::createShaderWithBindings(const std::string& vertSrc, const std::string& fragSrc,std::initializer_list<AttribBinding> bindings,- GfxShaderLanguage language) {+ GfxShaderLanguage language, bool deferLink) {if (!device_) return {};- auto shader = Shader::createWithBindings(*device_, vertSrc, fragSrc, bindings, language);+ auto shader = Shader::createWithBindings(*device_, vertSrc, fragSrc, bindings, language, deferLink);if (!shader) {ES_LOG_ERROR("Failed to create shader with bindings from source");return ShaderHandle();diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hppindex e13db82c2..aaedb96f2 100644--- a/src/esengine/resource/ResourceManager.hpp+++ b/src/esengine/resource/ResourceManager.hpp@@ -183,12 +183,17 @@ public:* material output).* @return Handle to the shader, or invalid handle on failure*/+ /** @brief Whether a shader that is known to compile is made without waiting for it (the device's skip-what-is-not-ready policy is on). */+ bool deferLinks() const;+ShaderHandle createShader(const std::string& vertSrc, const std::string& fragSrc,bool rewriteLoose = true,- GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300);+ GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300,+ bool deferLink = false);ShaderHandle createShaderWithBindings(const std::string& vertSrc, const std::string& fragSrc,std::initializer_list<AttribBinding> bindings,- GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300);+ GfxShaderLanguage language = GfxShaderLanguage::GLSL_ES300,+ bool deferLink = false);/*** @brief Loads a shader from file paths (with caching)diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 070d9fb5d..aa79dc2e7 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2996,4 +2996,6 @@ export const NOTED = {{"note":"A sun's shadow map leaves out the casters that shade nothing the camera sees."},"fix(shadow): a caster narrower than the blocker search's gaps no longer vanishes from a wide shadow map":{"note":"A small caster no longer drops out of a wide shadow map."},+ "feat(render): shaders can compile without stopping the frame, and a tile-based GPU is told what a pass does not keep":+ {"note":"Shaders that compile without stopping the frame."},};diff --git a/tools/shader-compile-cost.mjs b/tools/shader-compile-cost.mjsnew file mode 100644index 000000000..f8304e710--- /dev/null+++ b/tools/shader-compile-cost.mjs@@ -0,0 +1,108 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file shader-compile-cost.mjs+ * @brief What compiling shaders costs a package between page load and its first frames: how many programs, and how long the page was blocked on them.+ *+ * The page's WebGL context is wrapped before the engine runs, and the calls that wait for the driver are timed: compileShader and linkProgram only+ * queue work, getShaderParameter(COMPILE_STATUS) and getProgramParameter(LINK_STATUS) are where the page stops until it is done. A program that is+ * queried right after each stage waits for each in turn; one queried once, after both, can overlap them.+ *+ * node tools/shader-compile-cost.mjs [--dir output/tw-export] [--frames 30] [--w 1280] [--h 720]+ */+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { chromium } from 'playwright';+import { serveHost } from './lib/staticServer.mjs';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const argv = process.argv.slice(2);+const flag = (n, d) => { const i = argv.indexOf(`--${n}`); return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : d; };+const DIR = path.resolve(flag('dir', path.join(ROOT, 'output', 'tw-export')));+const W = Number(flag('w', '1280'));+const H = Number(flag('h', '720'));+const FRAMES = Number(flag('frames', '30'));++const wrap = () => {+ const stats = { programs: 0, shaders: 0, statusWaits: 0, waitMs: 0, maxWaitMs: 0, issueMs: 0, ext: false, longest: [] };+ window.__shaderStats = stats;+ const proto = WebGL2RenderingContext.prototype;+ const issue = (ms) => { stats.issueMs += ms; };+ const wait = (ms) => { stats.statusWaits++; stats.waitMs += ms; if (ms > stats.maxWaitMs) stats.maxWaitMs = ms; if (ms > 5) stats.longest.push(+ms.toFixed(1)); };+ const origCompile = proto.compileShader; proto.compileShader = function (s) { const t = performance.now(); origCompile.call(this, s); stats.shaders++; issue(performance.now() - t); };+ const origLink = proto.linkProgram; proto.linkProgram = function (p) { const t = performance.now(); origLink.call(this, p); stats.programs++; issue(performance.now() - t); };+ const sources = new Map();+ const origSource = proto.shaderSource; proto.shaderSource = function (sh, src) { sources.set(sh, src); origSource.call(this, sh, src); };+ const origAttach = proto.attachShader; proto.attachShader = function (p, sh) { (p.__stages ||= []).push(sh); origAttach.call(this, p, sh); };+ stats.log = [];+ const label = (p) => {+ const fs = (p.__stages || []).map((sh) => sources.get(sh) || '').find((src) => src.includes('fragColor') || src.includes('precision')) || '';+ return `${(p.__stages || []).reduce((n, sh) => n + (sources.get(sh) || '').length, 0)}B, fragment ${fs.length}B, ${(p.__stages || []).some((sh) => sh.__asked) ? 'made waiting (sync)' : 'deferred'}`;+ };+ const origShaderParam = proto.getShaderParameter;+ proto.getShaderParameter = function (s, pname) { if (pname === this.COMPILE_STATUS) s.__asked = true; const t = performance.now(); const r = origShaderParam.call(this, s, pname); if (pname === this.COMPILE_STATUS) wait(performance.now() - t); return r; };+ const origProgramParam = proto.getProgramParameter;+ proto.getProgramParameter = function (p, pname) { const t = performance.now(); const r = origProgramParam.call(this, p, pname); if (pname === this.LINK_STATUS) { const ms = performance.now() - t; wait(ms); if (ms > 5) stats.log.push(`${label(p)} ${ms.toFixed(0)}ms @${(t / 1000).toFixed(1)}s`); if (ms > 1500) (stats.dump ||= []).push({ ms: Math.round(ms), vs: sources.get((p.__stages || [])[0]) || '', fs: sources.get((p.__stages || [])[1]) || '' }); if (ms > 1500) (stats.stacks ||= []).push(new Error().stack.split(String.fromCharCode(10)).slice(1, 14).join(' | ')); } return r; };+ const origExt = proto.getExtension;+ proto.getExtension = function (name) { if (name === 'KHR_parallel_shader_compile') stats.ext = true; return origExt.call(this, name); };+};++// --async turns the package's quality.asyncShaderCompile on for the run (and puts the config back after).+const ASYNC = argv.includes('--async');+const configPath = path.join(DIR, 'game.config.json');+const { readFile, writeFile } = await import('node:fs/promises');+const originalConfig = await readFile(configPath, 'utf8');+if (ASYNC) {+ const cfg = JSON.parse(originalConfig);+ cfg.quality = { ...cfg.quality, asyncShaderCompile: true };+ await writeFile(configPath, JSON.stringify(cfg));+}+const server = await serveHost(DIR);+const browser = await chromium.launch({ headless: true, args: ['--use-angle=d3d11', '--enable-webgl', '--ignore-gpu-blocklist', '--disable-gpu-vsync', '--disable-frame-rate-limit', '--enable-unsafe-swiftshader', '--disable-gpu-shader-disk-cache'] });+try {+ const context = await browser.newContext({ viewport: { width: W, height: H }, deviceScaleFactor: 1 });+ const page = await context.newPage();+ await page.addInitScript(wrap);+ const t0 = Date.now();+ await page.goto(`http://127.0.0.1:${server.address().port}/?headless`, { waitUntil: 'load', timeout: 120000 });+ await page.waitForFunction(() => window.__estellaCooked?.facts && window.__estellaCooked.bakes, null, { timeout: 120000 });+ const booted = Date.now() - t0;+ const atBoot = await page.evaluate(() => JSON.parse(JSON.stringify(window.__shaderStats)));+ await page.evaluate(() => window.__estellaCooked.setPaused(true));+ // The frames after the page is up, until the world has laid itself out (the example's plants and terrain grow on worker threads): the programs a+ // frame asks for the first time (a material's variant, a pass's) are compiled here, in the middle of play.+ const frameMs = await page.evaluate(async (frames) => {+ const c = window.__estellaCooked;+ const out = [];+ let steady = 0;+ for (let i = 0; i < 600 && out.length < frames + 600; i++) {+ const t = performance.now();+ await c.step(1, 1 / 60);+ c.capture();+ out.push(+(performance.now() - t).toFixed(1));+ const k = c.render();+ const settledNow = c.bakes().length === 0 && i > 20 && !(k['render.draws.waitingForProgram'] > 0);+ if (settledNow && !window.__settledAt) window.__settledAt = Math.round(performance.now());+ if (settledNow && ++steady > frames) break;+ await new Promise((r) => setTimeout(r, 16));+ }+ return out;+ }, FRAMES);+ const after = await page.evaluate(() => JSON.parse(JSON.stringify(window.__shaderStats)));+ const counters = await page.evaluate(async () => { const c = window.__estellaCooked; c.render(); await c.step(2, 1 / 60); return c.render(); });+ console.log(`the world laid out and nothing waiting on a program at ${await page.evaluate(() => window.__settledAt)} ms of page time (the page started its clock ${await page.evaluate(() => Math.round(performance.now()))} ms ago)`);+ console.log(`counters: waitingForProgram ${counters['render.draws.waitingForProgram'] ?? 'unset (policy off)'}, pending ${counters['render.programs.pending'] ?? 'unset'}`);+ const sorted = [...frameMs].sort((a, b) => a - b);+ console.log(`boot ${booted} ms to the engine up`);+ console.log(` by then: ${atBoot.programs} programs (${atBoot.shaders} stages), page blocked ${atBoot.waitMs.toFixed(0)} ms on ${atBoot.statusWaits} status reads, longest ${atBoot.maxWaitMs.toFixed(0)} ms, ${atBoot.issueMs.toFixed(0)} ms issuing; parallel-compile extension asked for: ${atBoot.ext}`);+ console.log(`the ${frameMs.length} frames after it (to the world laid out): ${after.programs - atBoot.programs} more programs, blocked ${(after.waitMs - atBoot.waitMs).toFixed(0)} ms`);+ console.log(` frames over 50 ms: ${frameMs.filter((x) => x > 50).length}; first ${frameMs.slice(0, 4).join(' ')} ... median ${sorted[Math.floor(sorted.length / 2)]}, worst ${sorted[sorted.length - 1]}`);+ console.log(` waits over 5 ms (ms): ${after.longest.slice(0, 24).join(' ')}`);+ if (process.env.DUMP_SLOW && after.dump) { const { writeFile, mkdir } = await import('node:fs/promises'); await mkdir('output/slow-shaders', { recursive: true }); for (const [i, d] of after.dump.entries()) { await writeFile(`output/slow-shaders/${i}-${d.ms}ms.vert`, d.vs); await writeFile(`output/slow-shaders/${i}-${d.ms}ms.frag`, d.fs); } console.log(`dumped ${after.dump.length} programs`); }+ if (after.stacks) console.log([' stacks of the long waits:', ...after.stacks].join(String.fromCharCode(10) + ' '));+ console.log([' link waits over 5 ms:', ...after.log].join(String.fromCharCode(10) + ' '));+} finally {+ await writeFile(configPath, originalConfig);+ await browser.close();+ server.close();+}diff --git a/tools/terrain-water-cost.mjs b/tools/terrain-water-cost.mjsindex 6ced5be34..8b8ba0808 100644--- a/tools/terrain-water-cost.mjs+++ b/tools/terrain-water-cost.mjs@@ -94,6 +94,19 @@ const VARIANTS = [{ id: 'stars-0', label: 'sky without stars and moon', scene: (d) => { const u = effect(d, 'skyAtmosphere').uniforms; u.u_stars = 0; u.u_moon = 0; } },{ id: 'shade-0', label: 'fog on, cloud shafts 0', scene: (d) => { effect(d, 'heightFog').uniforms.u_cloudShade = 0; } },{ id: 'vol-0-shade-0', label: 'fog without volumetric light or cloud shafts', scene: (d) => { const u = effect(d, 'heightFog').uniforms; u.u_volumetric = 0; u.u_cloudShade = 0; } },+ // Temporal anti-aliasing in place of multisampling: after the lighting effects and the fog, before exposure, bloom and grading.+ ...[[1, 0.1], [1, 0.2], [2, 0.1]].map(([samples, blend]) => ({+ id: `taa-msaa${samples}-b${String(blend).replace('.', '')}`,+ label: `${samples}x multisampling and temporal AA at blend ${blend}, no FXAA`,+ scene: (d) => {+ const v = volume(d);+ v.effects = v.effects.filter((e) => e.type !== 'fxaa');+ const at = v.effects.findIndex((e) => e.type === 'autoExposure');+ v.effects.splice(at < 0 ? v.effects.length : at, 0, { type: 'taa', enabled: true, uniforms: { u_blend: blend, u_objectMotion: 1 } });+ },+ config: quality('high', { msaaSamples: samples }),+ })),+ { id: 'async-shaders', label: 'quality.asyncShaderCompile on (draws wait for a program still compiling)', config: (cfg) => { cfg.quality = { ...cfg.quality, asyncShaderCompile: true }; } },{ id: 'volumetric-off', label: 'fog on, volumetric light 0', scene: (d) => { effect(d, 'heightFog').uniforms.u_volumetric = 0; } },{ id: 'autoexposure-off', label: 'auto exposure off', scene: dropEffects('autoExposure') },{ id: 'bloom-off', label: 'bloom off', scene: dropEffects('bloom') },@@ -181,7 +194,9 @@ async function measure(server, original, variant, browser) {const c = window.__estellaCooked;for (let i = 0; i < 600; i++) {await c.step(2, 1 / 60);- if (c.bakes().length === 0 && i > 20) return i;+ // Also nothing waiting on a shader (the package may skip draws whose program is still compiling).+ const waiting = c.render()['render.draws.waitingForProgram'] > 0;+ if (c.bakes().length === 0 && i > 20 && !waiting) return i;await new Promise((r) => setTimeout(r, 50));}return -1;