WebGPU: CPU cost per draw call in 9.29/9.30, and which small PRs would you welcome?

Update (Oct 26): latest improvements applied. The route as it runs now, and a short walk through the same world:

It’s a streamed cell world of about 1 × 1 km: 3D Tiles 1.1, 64 cells of 128 m and 16 of 256 m, plus HLOD. Measured at the start of the drive, at 1920 × 1080: about 500 enabled meshes, 88.5k instances culled on the GPU in about 700 groups, about 580 draw calls per frame, 482 GPU textures in use and 222 materials. The same world also runs on Android, iOS and in VR. New since the last video: contact shadows, light through the leaves and a far shadow map. From this thread, #19037 is merged and #19038 and #19060 are approved. Thanks for the reviews.

Our goal is a fully GPU-driven renderer, and we still feel we’re short of it. We’ll share several tools here soon.

Hi everyone, hi @Evgeni_Popov,

Our scenes are CPU-bound on draw submission, so we read two public benchmarks from the last weeks closely. We did not find them discussed here yet. In 64212 you mentioned that the current WebGPU path already has more CPU-side overhead than WebGL, partly because of the extra bookkeeping and caches. Below are the numbers that show how large that gap is, what we read in the source, and four small PRs we could send.

The numbers (published, not ours)

web-engines-compare, results of 2026-10-01, Chrome 154, every engine at its defaults: 1K-20K boxes cloned from 100 meshes, 100 PBR materials with 4 textures each, one directional light with one shadow map, so 2 draws per box. CPU time per draw call in µs, lower is better:

Engine M4 Max WebGPU M4 Max WebGL2 i7-10700F WebGPU i7-10700F WebGL2 Pixel 8 Pro WebGPU Pixel 8 Pro WebGL2
Babylon.js 9.29.0 4.40 2.35 7.34 4.83 9.25 5.93
PlayCanvas 2.23.0 0.43 0.75 1.22 1.66 1.63 2.16
three.js r186 2.10 0.89 4.68 2.10 5.66 2.43
  • The author, Martin Valigursky, works on PlayCanvas. The code is public. We read the Babylon adapter: it uses plain defaults (clones, PBRMetallicRoughnessMaterial, a PCF ShadowGenerator, nothing frozen, compatibility mode on).
  • An independent run, endel/webgpu-webgl-benchmarks (Babylon 9.26.0, PlayCanvas 2.22.2, three.js r186, Chrome 151, Apple M1 Pro): 5,000 separate animated meshes on WebGPU cost 12 ms of CPU per frame in PlayCanvas, 24 ms in Babylon.js and 29 ms in three.js.
  • Babylon’s own WebGL2 path is 1.5-1.9x cheaper per draw than its WebGPU path on the same scene. PlayCanvas got 3.1-4.0x faster on WebGPU between 2.22.6 and 2.23.0 (same test, same browser).

PlayCanvas 2.23 recipe vs Babylon 9.30

From reading 9.30.0 (_draw is the same in 9.29.0 and on current master), compatibility mode:

PlayCanvas PR (their result) Babylon today
#9380 + #9492: keep the bound pipeline, look it up only when a state changes (#9492: -18% CPU frame time at 20K draws) The lookup is skipped when nothing changed (_isDirty), but the six state setters run on every draw, and setPipeline() is called on every draw (L3935).
#9496: skip vertex and index buffer binds the pass already has (draw call cost 2.8 to 0.9 ms per frame, best case) setIndexBuffer() and every setVertexBuffer() run on every draw (L3938-3954). The WebGL path already skips them (bindBuffers, _bindIndexBufferWithCache).
#9413: bind the material bind group only at a material switch (7.6% when the material changes every draw, neutral when sorted) A clean draw does no bind group lookup, but every group is set on every draw (L3957-3959). With _SimplifiedKnownBindings, group 0 is the Scene UBO and group 1 holds lights, material, Mesh UBO and textures, so group 1 is unique per mesh. Each cache leaf also creates its own group 0.
#9614: matrices in a persistent storage buffer, indexed by first instance (-34% to -44% static, -23% to -24% moving) Partly there: the Mesh UBO is persistent, shared by the main and shadow passes, and only uploaded when it changes. But it lives in group 1, which makes each draw’s bind group unique per mesh (and grows the bind group cache per mesh, see 64212).
#9482: light uniforms uploaded once per pass (per-draw UBO 528 B to 128 B) Already done: Light._bindLight refreshes a light’s data once per render id. BindLights still runs on every main-pass draw. Freezing the material skips it only on WebGL2, and only while the material, effect and visibility stay the same from one draw to the next; on WebGPU it runs even then (the WebGPU engine sets needToAlwaysBindUniformBuffers).

Small PRs we could send

No API change. A, B and the setBindGroup part of C go in _draw. The bound state is tracked per encoder and reset at each render pass, at each bundle encoder, after executeBundles (WebGPU clears the pass state there) and after a scissored clear (in compatibility mode its clear quad binds its own pipeline and bind groups on the same pass). So they only skip calls on an encoder that is reused across draws: the render pass in compatibility mode, and the bundle encoder while a snapshot is being recorded. Outside recording, non-compatibility mode replays each draw’s cached bundle or encodes the draw into a new bundle of its own, so they change nothing there. The group 0 part of C goes in WebGPUCacheBindGroups and D in WebGPUCacheRenderPipeline. Both caches also serve non-compatibility mode and snapshot recording, and the clear quad has its own WebGPUCacheRenderPipeline, so those two PRs would come with the before/after and the pixel diff in those modes too, and with a scissored clear.

  • A. Skip setPipeline() when the same GPURenderPipeline is already bound.
  • B. Skip setVertexBuffer() and setIndexBuffer() when buffer, offset and format did not change, like the WebGL path does.
  • C. Skip setBindGroup(i, g) when g is already bound at i, and reuse the group 0 bind group (Scene UBO only) per effect instead of creating one per cache leaf. Then meshes of one material skip the group 0 rebind, and the cache should keep about half as many GPUBindGroup objects.
  • D. Mark the pipeline dirty from the state setters instead of recomputing all states on every draw (the #9492 idea).

Each PR would come with a Playground, counters of the skipped calls, a before/after on the benchmark scene (several runs per build, alternating the build order, on a quiet machine), and a pixel diff. We saw #18562 by matthargett: it diffed this same state inside a new command-stream layer for native hosts and was closed in June, for now, because of overhead on the web path. These would be a few comparisons with no new layer, and we would drop any PR that shows no gain on the web.

Bigger changes, only if you think they belong in core and not only in Babylon Lite: split group 1 so that material and lights are bound once per material switch, and an opt-in storage buffer for world matrices.

Questions

  1. Would you welcome A, B and C as separate small PRs? Is there one you would rather not have?
  2. Would you consider D, or the bind group split, for core?
  3. Is there a scene you want the before/after on, besides web-engines-compare?

What we are not claiming

  • We have not measured A-D. They only cut repeated encoder calls and pipeline state checks during draw submission; they do not touch the per-mesh work above _draw. So we expect a few percent, not the 5.7-10x gap. PlayCanvas saw the same: #9380 alone showed no measurable CPU gain, and #9496’s best case is one mesh drawn many times in a row.
  • We expect most of the per-draw time to be above _draw (active mesh evaluation, render list, bindForSubMesh, shadow map rendering). We are not proposing anything there yet.
  • We do not claim the benchmark is neutral. Its author works on PlayCanvas; its code is public and its Babylon adapter looks fair to us.
  • We know about snapshot rendering and non-compatibility mode, and we plan to use them where they fit. Snapshot rendering replays a recorded frame, so the set of draws is fixed while it is on. This post is about the default path, which is what most apps and this benchmark run.

Probe (public APIs only). Paste it into the Playground, pick WebGPU or WebGL2 in the toolbar and read the console: draws per frame, CPU ms per frame and µs per draw.

Credit and disclosure: this post, the source reading and the probe were prepared by Memo, the AI of our studio 53ON (Claude with MemoriaBios, our long-term memory), and reviewed by me.

Playground code
// Per-draw CPU cost probe for Babylon.js, public APIs only.
// Same scene shape as the draw-calls test of github.com/mvaligursky/web-engines-compare:
// N boxes cloned from 100 meshes, 100 PBR materials with 4 textures each,
// one directional light with a PCF shadow map, so about 2 draws per box.
// Pick WebGPU or WebGL2 in the Playground toolbar, run, and read the console.
const N = 4000; // boxes
const MESHES = 100;
const MATERIALS = 100;
const TEX = 32; // texture size
const GRID = 142; // boxes per row

var createScene = function () {
    const scene = new BABYLON.Scene(engine);
    scene.useRightHandedSystem = true;
    scene.clearColor = new BABYLON.Color4(0.035, 0.035, 0.06, 1);

    // mulberry32, so every run builds the same scene
    let seed = 12345;
    const rnd = () => {
        seed = (seed + 0x6d2b79f5) | 0;
        let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
        t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
        return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
    };

    const camera = new BABYLON.FreeCamera("camera", new BABYLON.Vector3(0, 0, 180), scene);
    camera.fov = Math.PI / 4;
    camera.minZ = 1;
    camera.maxZ = 600;
    camera.setTarget(BABYLON.Vector3.Zero());

    const dir = new BABYLON.Vector3(-0.35, -0.45, -0.82).normalize();
    const light = new BABYLON.DirectionalLight("light", dir, scene);
    light.intensity = 3.4;
    light.position = dir.scale(-100);
    const shadows = new BABYLON.ShadowGenerator(2048, light);
    shadows.usePercentageCloserFiltering = true;

    const planeMat = new BABYLON.PBRMetallicRoughnessMaterial("planeMat", scene);
    planeMat.baseColor = new BABYLON.Color3(0.55, 0.55, 0.55).toLinearSpace();
    planeMat.metallic = 0;
    planeMat.roughness = 0.9;
    const plane = BABYLON.MeshBuilder.CreatePlane("plane", { size: GRID + 8, sideOrientation: BABYLON.Mesh.DOUBLESIDE }, scene);
    plane.material = planeMat;
    plane.position.z = -1;
    plane.receiveShadows = true;

    const makeTexture = (linear, fill) => {
        const data = new Uint8Array(TEX * TEX * 4);
        for (let i = 0; i < data.length; i += 4) {
            fill(data, i);
        }
        const t = new BABYLON.RawTexture(data, TEX, TEX, BABYLON.Constants.TEXTUREFORMAT_RGBA, scene, true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
        t.gammaSpace = !linear;
        return t;
    };
    const noise = (d, i) => {
        d[i] = d[i + 1] = d[i + 2] = 128 + rnd() * 127;
        d[i + 3] = 255;
    };
    const flatNormal = (d, i) => {
        d[i] = 128;
        d[i + 1] = 128;
        d[i + 2] = 255;
        d[i + 3] = 255;
    };

    const materials = [];
    for (let m = 0; m < MATERIALS; m++) {
        const mat = new BABYLON.PBRMetallicRoughnessMaterial("mat" + m, scene);
        mat.baseColor = BABYLON.Color3.FromHSV((m * 222.5) % 360, 0.6, 0.8).toLinearSpace();
        mat.metallic = Math.round(rnd() * 4) / 4;
        mat.roughness = 0.25 + rnd() * 0.7;
        mat.baseTexture = makeTexture(false, noise);
        mat.metallicRoughnessTexture = makeTexture(true, noise);
        mat.normalTexture = makeTexture(true, flatNormal);
        mat.emissiveColor = mat.baseColor.scale(0.25);
        mat.emissiveTexture = makeTexture(false, noise);
        materials.push(mat);
    }

    const masters = [];
    for (let k = 0; k < MESHES; k++) {
        const s = () => 0.42 * (0.6 + rnd() * 0.4);
        const master = BABYLON.MeshBuilder.CreateBox("mesh" + k, { width: s(), height: s(), depth: s() }, scene);
        master.setEnabled(false);
        masters.push(master);
    }
    for (let i = 0; i < N; i++) {
        // a clone shares the geometry of its master but is its own draw call
        const cube = masters[Math.floor(rnd() * MESHES)].clone("cube" + i);
        cube.setEnabled(true);
        cube.material = materials[i % MATERIALS];
        cube.position.set((i % GRID) - (GRID - 1) / 2, (GRID - 1) / 2 - Math.floor(i / GRID), 0);
        shadows.addShadowCaster(cube, false);
    }

    // CPU time from beginFrame to endFrame (scene.render() plus the submit), like the benchmark.
    // GPU execution is not included. SceneInstrumentation resets the draw call counter every frame.
    const instrumentation = new BABYLON.SceneInstrumentation(scene);
    let t0 = 0;
    let warmup = 120;
    let frames = 0;
    let sumMs = 0;
    let sumDraws = 0;
    const onBegin = engine.onBeginFrameObservable.add(() => {
        t0 = performance.now();
    });
    const onEnd = engine.onEndFrameObservable.add(() => {
        const ms = performance.now() - t0;
        const draws = instrumentation.drawCallsCounter.current;
        if (warmup > 0 || draws < 2 * N) {
            // skip warm-up frames and frames where shaders are still compiling
            warmup--;
            return;
        }
        frames++;
        sumMs += ms;
        sumDraws += draws;
        if (frames === 300) {
            console.log(
                `${engine.isWebGPU ? "WebGPU" : "WebGL2"}, Babylon ${BABYLON.Engine.Version}, ${N} boxes: ` +
                    `${Math.round(sumDraws / frames)} draws/frame, ${(sumMs / frames).toFixed(2)} ms CPU/frame, ` +
                    `${((1000 * sumMs) / sumDraws).toFixed(2)} us/draw`
            );
            frames = 0;
            sumMs = 0;
            sumDraws = 0;
        }
    });
    scene.onDisposeObservable.add(() => {
        engine.onBeginFrameObservable.remove(onBegin);
        engine.onEndFrameObservable.remove(onEnd);
        instrumentation.dispose();
    });

    return scene;
};

Made with the help of 53ON Harness (GitHub - enriqxxx/53on-harness: The open desktop shell of 53ON: hands, eyes and voice for your AI on your PC. You stay the only guardian. · GitHub). It gives an AI memories and recollections, plus hands, eyes and voice on the user’s own PC, with the user deciding what it can do. It works on its own with an API, together with VS Code and others, or without an API, with a local model.

Prepared by Ramon and Mema, the AI of our studio 53ON (:hand_with_fingers_splayed:, :eyes:, :abacus::hammer::screwdriver:, :brain: human memory simulation).

Thanks for the detailed write-up, and especially for distinguishing the published measurements from the proposed optimizations that have not been measured yet. Your description of the current draw path is broadly correct.

In principle, yes: small, focused PRs that reduce redundant work would be welcome, provided the before/after measurements show a worthwhile CPU improvement without regressions. Reducing the number of WebGPU calls is useful evidence, but is not by itself proof of a performance improvement, as the results of the pipeline-binding PR you linked also illustrate.

A, B and C

A and B look like reasonable candidates to start with. Please keep the state tracking lightweight and allocation-free on the draw path. For buffer bindings, the comparisons need to cover the actual GPU buffer, binding slot, offset and index format, rather than only the Babylon buffer object.

For C, I would separate skipping redundant setBindGroup calls from sharing the Scene bind group. These are independent changes with different correctness and performance considerations, and separating them would make the results easier to assess.

Sharing group 0 is worth investigating, but “per effect” alone is not a sufficient cache key: the actual Scene buffer and compatible bind-group layout also matter. Please account for multiple scenes/cameras, buffer replacement, custom shader layouts and device recreation. The expected reduction in bind-group objects should be measured for the workload rather than assumed to apply to every shader configuration.

The invalidation boundaries you listed are important, including new render passes, new bundle encoders, executeBundles and the scissored clear quad. Please cover those paths, along with non-compatibility mode and snapshot recording/replay, so an optimization of the default path does not introduce regressions elsewhere.

D and the larger changes

I would consider D, but as a separate change. Babylon already avoids the pipeline-cache lookup when the derived state is unchanged, so the opportunity here is to avoid unnecessary state derivation, not to remove a lookup that currently happens on every draw.

One detail to be careful with: _setVertexState() also builds the vertex-buffer list used by _draw(). Different meshes can use the same pipeline layout while requiring different buffers. Reusing the pipeline must not leave the previous mesh’s buffer list selected. Blend-state arrays are also mutated in place, so reference comparisons alone will not reliably detect changes.

A bind-group split or persistent storage for world matrices would need a separate design discussion. I would not rule them out for core in principle, but they affect shader processing, resource ownership and interactions with instancing and custom shaders. They should not be bundled into these smaller PRs.

Measurements and scenes

web-engines-compare is a useful starting point. However, its CPU time per draw is the whole frame’s CPU time divided by the draw count, including culling, sorting, material binding and shadow preparation. It should not be interpreted as the isolated cost of _draw(), and we still need profiling to establish where most of the difference comes from.

Please also benchmark with engine.compatibilityMode = false, alongside the default true configuration, and report the two modes separately. Non-compatibility mode can reuse per-draw render bundles, bypassing much of the repeated command encoding. This would help establish how much of the CPU cost can already be avoided with the existing fast path, both in the benchmark and in your application. It is not a substitute for measuring improvements to the default path: keep compatibility mode enabled as the primary baseline for the encoder-call elision proposals, and distinguish bundle creation from steady-state reuse in the non-compatibility results.

Draw order also matters for B: PlayCanvas’s default opaque sort groups by material and then mesh, whereas Babylon’s comparator does not group these meshes by geometry within a material. The same set of geometries therefore does not imply the same sequence of buffer switches.

Besides the default benchmark configuration, the most useful cases would be:

  • One shared geometry versus many geometries, with material-grouped and alternating-material draws.
  • Shadows on and off, and static versus moving meshes.
  • A representative application scene with mixed materials and render-target/post-process transitions, rather than only the repeated-box case.

The alternating build order and pixel comparisons you proposed are good. Please collect detailed call counters separately from the timing runs so the instrumentation does not distort a small gain, and report run-to-run variation as well as the average.

One correction to the supplied probe: its fixed camera distance does not fit the grid in a narrow or portrait canvas. Some boxes will be culled, and the draws < 2 * N guard can then reject every frame without printing a result. Please use aspect-aware camera fitting, as the benchmark does, and report incomplete draw counts explicitly.

So, yes to investigating these improvements, with isolated PRs and measured gains. I would keep the encoder-call elision, Scene-group sharing, pipeline dirty tracking and larger binding redesign as separate steps.

Thanks @Evgeni_Popov, we followed your plan and measured before writing any code. Short version: in our measurements A and B would save very little, and the profile pointed somewhere else. Details below; please tell us if you read the numbers differently.

1. Base matrix (9.30.0, 4,000 boxes, 9 samples per cell, timing and counters in separate runs). µs per draw = frame CPU / draws, mean ± SD over the samples; NCM is engine.compatibilityMode = false:

scene draws WebGPU compat WebGPU NCM WebGL2
default 8,001 8.49 ± 0.87 8.05 ± 1.53 6.19 ± 0.62
shared geometry 8,001 8.02 ± 1.20 7.89 ± 1.77 5.05 ± 0.33
grouped materials 8,001 9.07 ± 1.21 7.70 ± 1.03 5.67 ± 0.73
no shadows 4,001 10.96 ± 2.14 8.09 ± 1.35 6.16 ± 1.51
moving 8,001 11.04 ± 1.70 8.66 ± 0.77 7.04 ± 1.60

The machine was not idle during these runs, hence the spread. Portrait 500×900 with the aspect-aware framing you suggested: 8,001 draws, 0 incomplete frames.

Counters (compat): setPipeline is repeated on 7,998 / 8,001 draws in every scene; index / vertex buffer repeats only show up with shared geometry (~1 % otherwise).

NCM: 2 executeBundles per frame and 0 bundles created inside the timing windows, so these are steady-state reuse numbers (we did not time bundle creation). It is 2–26 % faster than compat depending on the scene: 5 % in the default one, and within the spread for default and shared geometry.

2. CPU profile (V8, compat, default scene, 12 s): setPipeline stays under 1.2 % self, setBindGroup 5.1 %, setVertexBuffer 2.9 %, setIndexBuffer 1.8 %. The big items are per-mesh scene work: _setDefaultAutoExtendShadowProjectionMatrix 9.6 %, _getInstancesRenderList 7.8 %, _updateOwnerKeyed 6.4 %. So A has a ceiling around 1 %, and B only pays off with shared geometry.

3. A real app scene (our streaming world: ~710 draws per frame, thin instances, a texture streamer, driven along a fixed route in real time at 1423×889). All encoder calls together are ~5 % of frame CPU. NCM measured 28.9 ms per frame against 32.2 ms in compat, but a repeat compat run drifted to 43.7 ms (another full-screen window was open), so we cannot call that one yet; we will repeat it on an idle machine.

What did stand out: Material._markAllSubMeshesAsTexturesDirty at 6.4 % self time (its body is the loop of _markAllSubMeshesAsDirty). Every texture swap on a material walks every mesh, submesh and draw wrapper of the scene, although material.meshMap already knows which meshes use it (useMaterialMeshMap is on by default). A streaming world swaps textures all the time, so this grows with scene size × swaps.

4. Proposal, instead of A/B: walk meshMap in _markAllSubMeshesAsDirty (and in markDirty / resetDrawCache, which have the same loop), keeping the exact inner checks (getMaterial(true, passId) === this, the material context):

  • meshes that render this material through a MultiMaterial: also walk the meshMap of the scene’s multi-materials that contain it;
  • instances that act as regular meshes (_actAsRegularMesh) render with their own submeshes: walk mesh.instances too;
  • the scene’s default material (meshes with no material) and useMaterialMeshMap: false: keep today’s full scan;
  • per-pass materials are already in meshMap (setMaterialForRenderPass registers them).

Equivalence, written as a unit test in the repo (Materials/babylon.material.markDirtyMeshMap.test.ts, NullEngine), six cases: meshes and their instances, multi-materials, a per-pass material, the default material, an unused material, and a mesh removed from the scene. On current master five pass and one fails: the mesh removed from the scene but still holding the material, which the change now marks too (what you want when it comes back). With the change all six pass; a walk over meshMap alone fails three of them (instances, multi-materials, default material). The Materials suite stays green (417/417) and lint reports the same warnings as master. The full unit run shows two failures, both unrelated: a KHR_interactivity loader test that passes on re-run, and a UMD rollup test that times out at 5 s on clean master too.

Measured in our world (9.30.0, compat, 849 meshes, 243 materials, same route in real time, idle machine, full-screen window), swapping the method live and alternating 3 times in one session:

pass method ms inside _markAllSubMeshesAsDirty per frame frame CPU mean p95
1 full scan 1.323 27.66 46.2
2 meshMap 0.027 28.30 44.8
3 full scan 1.182 26.26 43.3
4 meshMap 0.020 25.06 35.5
5 full scan 1.200 26.21 44.3
6 meshMap 0.020 25.01 35.5

Same ~11.4k mark calls per pass. The marking itself drops from 1.24 to 0.02 ms per frame (−98 %). The frame mean moves by −0.6 ms on average, which is inside the run-to-run noise (the first pair even goes the other way); the last two pairs show −1.2 ms and a p95 about 8 ms lower, since bursts of texture swaps no longer walk the whole scene. It scales with meshes × swaps, so it matters more for big streamed scenes than this number suggests.

The change and its test are ready on a branch. If that sounds reasonable, I’ll open the PR. Critique is welcome: if you know a case this walk misses, or would rather see markDirty / resetDrawCache in a separate PR, we’ll adjust.

Prepared by Memo, the AI of our studio 53ON.

Thanks for following up with measurements and for being explicit about the noise and the limits of the results. I agree with prioritizing the material-invalidation work for your streaming workload rather than starting with A/B. The reduction in time spent in the marking routine is promising, while your qualification of the whole-frame improvement is appropriate.

The non-compatibility results are useful too, particularly the separate counters showing steady-state bundle reuse. They do not establish a large gain in the default/shared-geometry cases given the spread, but they help distinguish command-encoding overhead from the scene and material work that remains. I would also treat the V8 self-time profile as prioritization evidence rather than a strict upper bound on what A could save.

Please open a focused PR for the material-invalidation change. Before relying on meshMap as the candidate set, though, there is a correctness issue in the existing bookkeeping that the optimization needs to account for.

The map is not currently a complete usage index

_setMaterial() and setMaterialForRenderPass() both write the same meshMap[mesh.uniqueId] entry. Removing one assignment clears that entry without checking whether another assignment still uses the material. For example:

mesh.material = material;
mesh.setMaterialForRenderPass(passId, material);
mesh.setMaterialForRenderPass(passId, undefined);

After this sequence, mesh.material is still material, but its map entry is undefined. The current full scan can still find and dirty the main-pass draw wrapper; a traversal based only on this map would miss the mesh. Keeping the inner material/context checks is necessary, but cannot recover a mesh omitted from the candidate set.

The same problem occurs when:

  • The material is assigned to two render passes and one override is removed or replaced.
  • The regular material is changed while a render-pass override still references the old material.

This bookkeeping issue predates your proposal, but the new invalidation path would depend on an invariant it does not currently guarantee. Please include these assignment/removal transitions in the regression cases, not just initial per-pass assignment, and either maintain complete membership across those transitions or retain a correct fallback for the affected cases.

The instance, MultiMaterial and default-material cases you identified are also relevant. Please retain the existing pass-specific material resolution, material-context checks and dirty-blocking behavior. An empty map does not necessarily mean the material is unused, as the example above demonstrates.

Scope and behavior

For the first PR, I would focus on _markAllSubMeshesAsDirty(), which is the path supported by your streaming measurements. I would leave markDirty() and resetDrawCache() for follow-ups unless including them is necessary for the implementation. They have different effects on draw wrappers and deserve their own behavioral coverage rather than being changed only because their loops look similar.

The removed-from-scene case is not strictly an equivalence test: the current implementation only visits scene.meshes, while the proposed traversal also reaches a detached mesh through the map. Invalidating that mesh before it is re-added may be desirable, but it is a behavior change. I would keep the optimization behavior-preserving initially, or discuss and cover that change explicitly, including asset-container remove/add cycles, rather than treating a failure on current master as proof of equivalence.

Evidence for the PR

The reported reduction from about 1.24 ms to 0.02 ms in the marking routine is a useful motivation for reviewing the change. It is not a 98% frame-time improvement, and your post already makes that distinction. Likewise, the lower p95 values are encouraging, but a live route driven in real time can encounter different streaming work between runs even with similar call totals.

Please include a small reproducible benchmark with a fixed scene and texture-swap sequence, with timing instrumentation separated from detailed counters, alongside the application results. Cover material reassignment/disposal and some streaming churn as well: map entries can remain present with undefined values, so traversal cost should not be inferred solely from the current number of live users. Also keep the disabled-map path and the ordinary no-change rendering path free of unnecessary new work.

That would make this a worthwhile, well-bounded optimization to review. The main prerequisite is establishing that the optimized traversal reaches every draw wrapper the current scene scan would invalidate.

Thanks @Evgeni_Popov, that review changed the design. The PR is here: Material: skip submeshes that cannot resolve to the material when marking dirty by enriqxxx · Pull Request #19004 · BabylonJS/Babylon.js · GitHub

You were right about the bookkeeping, and there is a second gap: GaussianSplattingMeshBase stores its material without _setMaterial, so its meshes never enter meshMap. Our earlier walk would have missed them too. So the first PR does not use meshMap at all:

  • it keeps the scene.meshes walk with the same per-pass resolution, material-context checks and dirty blocking;
  • before resolving the passes of a submesh, it skips it if its rendering mesh cannot resolve to the material in any pass (its material and its render pass materials are neither this material nor a multi-material, and it has a material, so the default material cannot apply). The check reads the same slots as SubMesh.getMaterial;
  • only _markAllSubMeshesAsDirty(); markDirty() and resetDrawCache() are untouched.

Because it walks the same meshes, detached meshes and asset container cycles behave as today. The disabled-map path and dead map entries don’t matter, and the rendering path is untouched.

Regression cases (NullEngine): the transitions you listed (pass material set then removed, two passes with one removed, pass material replaced, mesh material changed while a pass keeps the old one), multi-materials as mesh and pass material, instances, the default material, a mesh that keeps its material outside meshMap, and removal / asset-container cycles. All nine pass on current master unchanged and with the change. A tenth case checks the optimization itself (fails on master by design).

Reproducible benchmark (in the PR description): fixed scene, fixed sequence of 2,000 texture swaps, timing without instrumentation, counters in a separate pass, plus streaming churn and material reassignment/disposal. A texture swap costs ~27 µs on the branch against ~132 µs on master, with identical marking calls and marked draw wrappers. scene.render() with no change stays within noise.

In our streaming world (same route as before, alternated live 3 times): the marking goes from 2.54 to 0.74 ms per frame (−71 %) with the same number of calls; frame CPU is lower in every pair (−1.7 ms on average, −4.4 %) and p95 about 11 ms lower. The machine was busier than for the numbers in #3 (master marks at 2.54 ms per frame here against 1.24 then), so compare within the session; the table is in the PR. The NCM repeat on an idle machine that we promised in #3 is still pending; we’ll post it when it is done.

This is about 5× in the benchmark, smaller than the meshMap walk would give (~85× on the marking loop alone), but it is exact by construction. If you want the O(users) walk later, it needs meshMap to be complete for every mesh type and a decision on meshes outside the scene; we can do that as a separate step. Critique welcome, as always.

Prepared by Memo, the AI of our studio 53ON.

Thanks for adapting the design and opening the PR. Keeping the existing scene.meshes traversal and rejecting impossible candidates is a much safer first step than depending on meshMap. The Gaussian-splatting example is another good reason not to make completeness of that map an implicit prerequisite. Keeping markDirty(), resetDrawCache() and detached-mesh behavior unchanged also keeps the scope clear.

I also read the subsequent update in 3cf96d3, not just the version described in this post. The conservative fallback for a customized getMaterialForRenderPass() addresses that case, and bounding the candidate scan by the draw-wrapper array addresses the removed high-ID override case raised in the review.

One remaining material-resolution case

There is still an equivalent issue one level above the mesh resolver: a customized SubMesh.getMaterial(). This is the method the existing invalidation loop calls, and Mesh.render() uses it to select the material too. Its result is not necessarily derivable from the rendering mesh’s material slots when that method is overridden.

For example, let a submesh subclass return material A from getMaterial(), while its rendering mesh has material B and no per-pass overrides. Prepare that submesh’s draw wrapper using A, then mark A’s textures dirty. The current scene scan calls the submesh resolver and marks A’s wrapper. With the PR, _mayRenderWithMaterial(A, ...) returns false from the mesh’s B assignment, so the submesh is skipped before its resolver is consulted. A’s existing defines remain clean.

Please preserve the original resolution path when the submesh’s getMaterial() is customized, just as you now do for a customized mesh getMaterialForRenderPass(), and add a regression using a submesh subclass. The test should prepare A’s wrapper, clear its dirty state, call A.markAsDirty(Material.TextureDirtyFlag), and assert that the wrapper becomes dirty even though the rendering mesh holds B. A submesh-owned candidate check would also be a reasonable way to keep this assumption close to the resolver, if that makes the implementation simpler.

Measurements and next step

The updated benchmark in your PR comment is still encouraging: about 130.8 to 34.5 microseconds per swap, or roughly 3.8 times faster for that workload. Please align the PR description’s headline numbers with the revision being evaluated; the earlier roughly 5-times result belongs to the previous implementation. I would keep the correctness fallback rather than trade it away for the approximately 5 microseconds you attributed to the method-identity check. If the application figures were collected with the previous implementation, please label them accordingly rather than assuming the same whole-frame benefit for the revised one.

The idle-machine non-compatibility repeat remains useful for the broader draw-submission discussion, but it need not expand this focused PR. It is separate from establishing that material invalidation reaches the same draw wrappers. An eventual O(users) traversal can likewise remain a separate proposal with explicit map-completeness and detached-mesh semantics.

This remains a worthwhile optimization. The remaining resolver case should be covered before calling the filtering behavior-preserving; after that, the normal PR checks and revision-matched measurements are the basis for deciding whether to merge.

Hi @Evgeni_Popov,

A short update on this thread, after #19004 was merged. This is a preview of work in progress, not finished work: we kept going on the per-draw cost of our streamed open world (cells loaded and unloaded while driving, thin-instanced foliage, two-cascade sun shadows, TAA, WebGPU with snapshot rendering in FAST mode), and two engine-side changes are already measured.

The average frame rate was already fine. What still broke the motion were hitches: every time the world changed what it draws (tiles, LODs, textures, about once per second while driving), the snapshot was recorded again, and that recording frame took 50-130 ms.

We count a hitch as a frame of 60 ms or more that is over 1.5× the previous frame, at least 200 ms after the previous hitch. Everything below is measured on the same route (Chromium 147, RTX 3080 Laptop GPU, 2560×1440), alternating the arms between rounds; each number says how many rounds it comes from.

1. Per-frame data out of every draw. A recorded snapshot replays draws whose uniforms were written when it was recorded. Three things change every frame for every draw: the cascade matrices of the shadow generator, the TAA jitter and the previous view-projection used for velocity. Keeping them current meant ~2,000 small buffer writes per frame, and the GPU process stalled behind them (a 128-byte write took 20 ms). We moved them to buffers that every draw already binds, one per light and one per view: the cascade matrices, split depths and blend factor into the light UBO (WGSL), and the jitter and previous view-projection into the scene UBO. A replay then reads this frame’s values with no writes per draw. Moving the cascades alone took the route from 50 to 16 hitches (one round) at the same image; moving the jitter added 2-5 % fps (two rounds); the previous view-projection is what keeps velocities right once draws are cached (point 2).

2. Cached draws when a snapshot records again. Recording again used to encode every draw of every pass (~70-80 ms in our scene). Now each recorded draw gets its own render bundle, kept with its draw context, and a mesh that opts in (mesh.cacheDrawCommands = true) replays its bundles while it is unchanged; it records again only after mesh.requestDrawCommandsUpdate(), material.requestDrawCommandsUpdate() (we call it when texture streaming swaps a texture), a material change, or a change in its material’s defines. Over one drive of the route, 51,600-54,400 draws were replayed from that cache and about 200 recorded.

3 rounds, alternated Before After
Hitches 48 · 40 · 32 (30.5 per minute) 3 · 4 · 2 (2.3 per minute)
Frames over 50 ms 63-75 3-8
Average fps 86.4 85.7
Image at still poses within the run-to-run noise
WebGPU errors 0 0

Note (Oct 21): the fps and hitch counts in this table are page-side frame times, measured uncapped with vsync off. They are not displayed frame rates and do not show smooth presentation; see the correction in #10.

The changes live in (1) the light and scene UBO layouts and a few WGSL includes, and (2) the WebGPU engine’s snapshot recording, Mesh.render and ShadowGenerator.

The other items from 64212 #24 are up: #19027 (the prepass and a custom tone-mapping post process), #19028 (the prepass after an active camera switch) and #19029 (the fade plugin; ShadowDepthWrapper does carry it into the shadow). The TAA fix with instances: #19023 / #19024.

Nice work on #19004 and the snapshot re-recording changes. Going from ~30 hitches a minute to ~2 is the kind of win users actually feel.

One thing I keep coming back to about the original benchmark: “the same scene in three engines” really means “the same draw count, each engine at its defaults.” That’s a fair thing to measure, but each engine’s defaults reflect different priorities. Babylon’s scene.performancePriority defaults to BackwardCompatible. Every mesh is re-evaluated every frame, and the directional light re-fits its shadow bounds over every caster each frame (that’s the 9.6% _setDefaultAutoExtendShadowProjectionMatrix in your profile). Each engine also has its own fast path, and the benchmark has to rule out the biggest one, instancing or batching, for the test to work at all.

Your own profile shows this: PlayCanvas’s encoder-side fixes would have been worth about 1% in Babylon, because Babylon spends its time somewhere else.

So it could be worth adding a second “tuned” column to web-engines-compare: same draw count, with each engine set up the way its own docs recommend. For Babylon that would be something like performancePriority = Aggressive, frozen materials, autoUpdateExtends = false with fixed shadow bounds, compatibilityMode = false, and maybe snapshot rendering for the static case. The defaults column shows what most apps get, and the tuned column shows the ceiling. The gap between the two is the part we can do something about, through cheaper defaults or better docs.

Happy to help put together a tuned Babylon adapter if people think it’s useful.

Thanks for the update, and for following through on #19004. Yes, both directions would be welcome for review in core. I would start with the shared-data changes, then review cached-draw reuse separately. The reduction in long frames is the interesting result here; an almost unchanged average frame rate does not diminish that benefit.

Shared data: the right direction, with view/pass ownership

The current code supports the motivation: the CSM matrices and split data are still effect uniforms, the reprojection TAA plugin writes jitter through each material UBO, and prepass binding sets the previous view-projection through the effect. Moving values shared by many draws out of their per-draw storage is worth pursuing independently of command caching.

One distinction is important: a render bundle records commands and resource bindings, not a frozen copy of uniform-buffer contents. Updating the GPU buffer already bound by a bundle is visible on replay. The improvement is therefore to share and update the right buffers without visiting every draw, while keeping their bound allocations valid, rather than to make recorded uniforms mutable for the first time.

I would describe the ownership as per view/pass and per shadow-generator/view, not simply once per scene or light per frame. Babylon can use several cameras, camera-specific shadow generators on one light, and separate scene UBOs for render targets and shadow passes. Two views must not overwrite the same allocation with different matrices before their recorded commands execute. The update path also needs to run during FAST replay, when ordinary mesh/material binding is skipped.

For the first PR, please keep the CPU layouts and shader declarations consistent across the affected UBO creation paths, including render-target and multiview variants. A WGSL-first optimization is reasonable, but it must preserve the existing GLSL/WebGL paths and GLSL materials on WebGPU. Jitter should apply only to the intended color rendering, not leak into shadow rendering or the unjittered velocity calculation. Previous view-projection history needs the right camera/view lifetime, including initialization, a camera that stops moving, camera cuts and history reset. Previous world matrices and instance/bone history remain separate per-object data.

The CSM and temporal-view changes could be separate PRs if they are independently useful; they do not need to become one large uniform-layout change.

Cached draws: build on the existing bundle cache

Babylon already has per-draw WebGPUDrawContext.fastBundle reuse in non-compatibility mode. Snapshot recording currently takes a different path and encodes draws into the snapshot’s bundle encoder instead of using that cached-bundle shortcut. Extending or sharing that machinery would be preferable to introducing a second independent cache. Please distinguish the cost saved by avoiding GPU command encoding from the cost saved by bypassing Mesh.render() and material binding; reusing a bundle alone does not eliminate the latter.

An opt-in is reasonable, but I would leave the exact cacheDrawCommands / requestDrawCommandsUpdate() API shape open until the invalidation contract is clear. Updating the contents of an already-bound buffer is different from changing a pipeline, binding a new texture or buffer, changing geometry or draw ranges, or changing instance counts. Engine-visible resource and pipeline changes should invalidate or update the cache appropriately; an explicit request can cover application-controlled state that the engine cannot infer. It should not require callers to guess which ordinary setters silently leave stale commands.

Please also make clear how an update reaches a FAST snapshot that is already playing: mesh evaluation is skipped there, so setting a flag that is checked only inside Mesh.render() cannot by itself refresh the recorded frame. Changes to visibility, LOD, streaming membership or draw order still need an updated snapshot draw list, even if most of its bundles can be reused. The cache must distinguish the actual draw/pass configuration, preserve surrounding viewport/scissor/stencil state and ordering, and release references when draw contexts or resources are reset/disposed or the device is recreated. Material plugins and render callbacks need an explicit supported behavior if the shortcut skips their normal binding hooks.

Evidence for the PRs

A small deterministic scene should exercise repeated snapshot resets while adding/removing meshes and swapping streamed textures, with a moving camera, CSM and TAA reprojection. Please compare the existing snapshot path, ordinary compatibilityMode = false without snapshots, and the proposed cached-recording path. That will show the extra benefit beyond the bundle cache already available.

For correctness, compare frame sequences and the velocity target, not only still poses: include camera and instance motion, moving shadows, a second camera/render target, and resize/history reset. For performance, keep the shared-data and command-cache results separate, then show the combined result. Report recording-frame duration, buffer-write calls/bytes, bundle creation/reuse and retained cache memory after streaming churn, alongside slow-frame counts and a tail frame-time percentile. Your relative-to-the-previous-frame hitch counter is useful, but can miss consecutive slow frames, so it should not be the only tail metric.

I would also avoid interpreting a 20 ms writeBuffer call as the cost of transferring 128 bytes without a trace identifying the cause; it can include backpressure or synchronization. The reduction in write calls is valuable evidence on its own. The three-round hitch result is encouraging; the single-round cascade result remains preliminary, and the timings are not something I have independently reproduced.

So yes: please bring the focused shared-data PRs first, then the cache-reuse PR with the lifecycle and invalidation rules spelled out. Keeping the prepass/shadow-fade reports and the instance-velocity fix separate is appropriate.

Thanks, that order makes sense. Here’s where we are and what’s coming.

What’s coming, in your order

  1. Shared data first, as two PRs: the cascades, then the temporal view data (jitter and previous view-projection), each keeping the GLSL/WebGL paths and the render-target and multiview layouts in step.
  2. Then the cached-draw reuse on its own, on top of the existing fastBundle path (each recorded draw already keeps its bundle in drawContext.fastBundle), with the invalidation rules written out.

We’re building the small deterministic scene you describe, with the three arms, so the numbers come from something anyone can run.

A correction, and what’s solved since #7
The fps and hitch counts in #7 are page-side frame times, measured with vsync and the frame-rate limit off. When we recorded the window and counted distinct frames, the screen was getting a new image about once per second (71 to 76 distinct frames in 81 s) while the page reported ~87 fps. The page was queuing its WebGPU work about 1.15 s ahead of the GPU (submit to onSubmittedWorkDone), so yes, the 20 ms writeBuffer was that backpressure, not the bytes. With vsync on, as people normally run it, the page doesn’t get that far ahead (about 24 ms from submit to done), so it mostly bites uncapped runs like ours.

  • Frames in flight bounded (a frame starts only while fewer than 4 submitted frames are still on the GPU) plus a 60 fps cap: ~55 distinct frames per second on screen, worst gap 75 ms, none over 100 ms.
  • Missing pipelines compile in the background (createRenderPipelineAsync), and their draws wait until the pipeline is ready instead of stalling the frame on the shader compile: the 100+ ms frames from compiles are gone.

Both are small opt-ins on WebGPUEngine (maxFramesInFlight and asyncPipelineCompilation, off by default) and will come as their own PRs too.

What’s still open, and what we’ll take on next

  1. The last hitches, about 2 to 3 a minute on screen. They come from the frames where the snapshot records again:
    • Draws that change every frame (animated birds, road splines whose index ranges move, post-processes) get re-encoded at every recording. The plan is to keep their bundles when only their buffer contents change.
    • Streaming loads that land in the same frame. The plan is to hand loaded data back within a per-frame budget instead of all at once.
  2. The PRs above: shared data (two), cached-draw reuse, maxFramesInFlight and asyncPipelineCompilation, plus the fixes for #19028 (camera switch) and #19029 (flat varying for the fade).
  3. The deterministic scene with the three arms, reporting what reaches the screen next to the page-side numbers, plus tail percentiles.
  4. GPU side: occlusion and GPU culling for everything, so fewer draws reach the GPU.
  5. Then the image: far shadows from distance fields, ambient occlusion, screen-space global illumination, reflections and motion blur, each as an opt-in module on the frame graph, measured on and off.

Video
The latest video is at the top of the thread.

Thanks for making that correction explicit. It changes how we should read the earlier results: the approximately 87 FPS and page-side hitch counts in post 7 were not evidence of smooth presentation. Please carry that qualification into the benchmark summary so those figures are not later quoted as displayed frame rates. The new capture results are encouraging, but I have not independently reproduced them.

Frame pacing and what the measurements mean

queue.onSubmittedWorkDone() measures completion of previously submitted queue work, not when a frame reaches the display. Submit-to-promise-resolution time includes queued work and callback delivery; it is not an isolated GPU frame duration or an input-to-screen latency measurement. Counting distinct images in a recording is a useful additional observation, but the capture itself can drop or duplicate frames. A rendered sequence number and capture timestamps, ideally cross-checked against a browser trace, would make that comparison much stronger.

I would consider a focused, off-by-default frames-in-flight limiter, but first compare the FPS cap alone, the limiter alone, and both under the same conditions. Babylon already has engine.maxFPS, so there is no need for another FPS-cap API. Keep normal browser/VSync operation as the primary case and the uncapped/browser-flag experiment separately labeled; the latter is useful for diagnosing backpressure, not representative by itself.

The limiter should integrate with frame admission rather than serialize every frame with a queue-wide wait or leave half a frame begun. Its accounting must cover the engine’s submission boundaries, including intermediate flushes: a queue submission is not necessarily one rendered frame. Please cover stop/restart, background/resume and device loss, and make sure old completion callbacks cannot revive a stopped loop or affect a new device. Four outstanding frames is a candidate setting to measure, not a universal optimum; lower queue depth can improve latency at a throughput cost.

Async pipelines: extend the existing path, and handle incomplete frames

This is also worth a separate discussion/PR. Babylon already exposes WebGPUEngine.createRenderPipelineAsync() and the pipeline cache’s preWarmPipeline(). Please build on those rather than a second compilation cache, and compare automatic handling of unexpected misses with prewarming known streaming content before making it visible.

The important new behavior is what happens while a pipeline is pending. If the draw is omitted instead of blocking, that is a visible behavior change, even behind an opt-in. In particular, snapshot recording must not finalize a frame missing that draw and then replay the incomplete snapshot indefinitely when compilation finishes. Required shadow, depth/velocity and post-process passes need coherent readiness behavior too. Pending requests should be deduplicated for the actual pipeline configuration, errors surfaced, and completions ignored safely after disposal/device replacement. I would describe this as asynchronous pipeline creation rather than assume every shader-compilation cost has moved off the main thread.

One distinction for the cached-draw work

Animated geometry can reuse a bundle when only the contents of already-bound buffers change. Moving an index range is different: drawIndexed(count, ..., firstIndex, ...) records those arguments. That requires re-encoding or a suitable indirect draw whose argument buffer is updated correctly. The current setIndirectData() shortcut checks only the instance count unless an update is forced, so an unchanged instance count must not prevent a changed start/count from reaching the GPU. Please include that road-spline case explicitly. Post-process history-buffer swaps similarly need the correct recorded bindings, not just fresh uniform values.

The agreed shared-data and bundle-reuse split still makes sense. I would keep streaming handoff budgets and the larger culling/rendering roadmap independent of those engine PRs, with each benefit measured separately rather than attributing the combined result to command caching.

On the tuned benchmark

@Pryme8, a separate, documented tuned configuration would be useful alongside the defaults, with static and moving workloads kept distinct. I would not call it a ceiling or apply the switches blindly. ScenePerformancePriority.Aggressive disables frustum clipping and automatic color clearing and enables retained rendering state; Mesh.render() also freezes its internal instance/render data on that path. It is not the same as freezeActiveMeshes(), and fixed shadow bounds or frozen materials each bring their own workload assumptions. Verify the image and actual submitted draw counts, and document which dynamic behavior remains supported.

Also, the earlier roughly 1% observation concerned setPipeline self-time in one profile, not a demonstrated upper bound on all encoder-side optimizations. Keeping that distinction, and separating CPU submission, queue completion and captured presentation, will make both the tuned comparison and these new PRs much easier to evaluate.

1 Like

Ok, Ill take a look into that today after work.

Thanks, Evgeni. I’ve added that qualification below the table in #7.

Here are the first two PRs, in the order you suggested: shared per-view data first, then the cached draws.

  • #19037, CSM cascades. They live in a uniform buffer owned by the generator, one per camera the cascades are computed for, written once per computation and also during a FAST replay. In our deterministic test scene, a FAST replay with a moving camera now matches normal rendering frame for frame, where 9.31.3 drifts by up to 67.9/255. writeBuffer drops from 302 calls to 7 per frame.
  • #19038, temporal view data. The previous view-projection and the TAA jitter move to the scene uniform buffer of each pass, and the camera owns the history. A FAST replay matches normal rendering on the canvas, color and velocity targets, and a second view no longer corrupts the velocity history.

Each description has the full comparison and one design question for you. The cached-draw PR comes next, with the road and bird cases you described. After it comes the limiter comparison: maxFPS alone, the limiter alone and both, with vsync as the main case.

For context, these come from a streamed cell world of about 1 × 1 km: 3D Tiles 1.1, 64 cells of 128 m and 16 of 256 m, plus HLOD. Measured today at the start of the drive, at 1424 × 896, it has about 510 enabled meshes, 60.9k instances culled on the GPU in 465 groups, about 510 draw calls per frame and 317 world textures.

Just so it’s clear: this is still a work in progress, not the final result. We’re not at the numbers we want yet, and we’ll keep at it until we get there.

Prepared by Mema, the AI of our studio 53ON (Claude in the 53ON harness, with MemoriaBios, our long-term memory), and reviewed by me.

1 Like

Thanks for adding the timing qualification and opening the two PRs. The split makes sense, and the write-count reductions and deterministic comparisons are encouraging. I’ll keep the detailed implementation feedback on the PRs.

For the camera-cut question in #19038, I prefer an explicit history reset rather than a movement threshold. The application knows when it makes a cut; distance alone cannot distinguish one from legitimate motion. When used with TAA, resetting the view history should be coordinated with discarding the accumulated color history.

Please keep the FAST results scoped to what was tested: improving shared view data does not yet make the complete TAA pipeline replay correctly. Otherwise, the planned order still looks good: these shared-data changes, cached draws, then the separate limiter comparison.

Edited the first post with two new videos: the route as it runs now, and a short walk through the same world. We’ll share several tools here soon.

What would you like to see in the next progress video? Any suggestion is welcome.

Prepared by Mema, the AI of our studio 53ON (Claude in the 53ON harness, with MemoriaBios, our long-term memory), and reviewed by me.

Opened #19065: a mesh no longer keeps a Vector3 per vertex when its positions are its geometry’s; picking and collisions use the geometry’s points, shared by its clones. In a test scene of 200 meshes (20 geometries and their clones), the heap snapshot goes from 2.55 M to 0.31 M nodes, the JS heap from 57 to 21 MB, and a forced full GC pauses about a third as long. The images are byte-identical on WebGPU and WebGL2. The full comparison is in the description.

Also from this thread, each isolated and measured on its own: #19059 (KTX2: no copy of the file for the worker, and the decoded levels freed after the upload; in our app, full GCs went from 30.2 to 17.0 per minute) is merged, and #19060 (pipeline names and plugin declarations as flat strings; 13% fewer heap nodes in our app) has the test fix Evgeni asked for.

Prepared by Mema, the AI of our studio 53ON (Claude in the 53ON harness, with MemoriaBios, our long-term memory), and reviewed by me.

1 Like

A small one next to #19059, on the KTX2 decoding workers. To keep them through a streaming burst instead of creating them again, an app can raise AutoReleaseWorkerPool.DefaultOptions.idleTimeElapsedBeforeRelease, which KTX2 and Draco use for their pools. A time setTimeout cannot hold (more than 2^31 − 1 ms) does not do that: setTimeout wraps it around, and Infinity or 2^31 ms run the timer at once, so the pool terminates each worker as soon as it is idle, and the next texture creates and initializes a new one.

#19083 schedules the release only for a time setTimeout holds, so with a longer one the workers stay until the pool is disposed, and the option’s doc says so.

In this Playground a pool of one worker runs 3 tasks 200 ms apart, on 9.33.0: with 1000 or 30,000 ms it creates 1 worker; with 2^31 ms or Infinity it creates 3, each one terminated right after its task, with WebGPU and WebGL2 alike: https://playground.babylonjs.com/#J5QB8K#0

Prepared by Mema, the AI of our studio 53ON (Claude in the 53ON harness, with MemoriaBios, our long-term memory), and reviewed by me.

Thanks for keeping these changes isolated and measured. #19059, #19060 and #19065 are now merged. Reducing retained objects and decoder allocations is useful progress on streaming stalls, even though it is separate from draw-submission overhead.

The timer-overflow case in #19083 is a real issue, and documenting the retention behavior makes sense. Keeping workers alive trades initialization cost for retained worker/WASM memory, so a finite timeout remains useful when streaming pauses. With Infinity, applications should understand that workers remain until the pool is explicitly disposed. I’ll keep implementation feedback on the PR.

The limiter comparison from #11, before its PR: engine.maxFPS alone, a frames-in-flight limit alone, and both together, under the same conditions, with vsync as the main case.

Setup. Chromium 147, RTX 3080 Laptop GPU, a 240 Hz screen, 1280×720, on 9.33.0 and on our branch (the limit is WebGPUEngine.maxFramesInFlight: a frame starts only while fewer than N frames are still on the GPU). A full-screen WGSL shader whose GPU cost is set per run (about 14 ms of GPU per frame, and about 58 ms), with 4 ms of CPU work per frame. Each rendered frame paints its number in binary; the window is recorded with Windows Graphics Capture (up to 240 images a second, lossless) and every recorded image is read back, so the screen side counts frames by their number: shown, never shown, out of order. Two rounds in alternating order, 10 s per arm, the machine checked quiet before and during each measure.

With vsync (the browser as players run it):

GPU ~14 ms a frame: frames per second (page / new on screen) queue latency p50 (ms) to the screen p50 (ms) GPU ~58 ms a frame: frames per second (page / new on screen) queue latency p50 (ms) to the screen p50 (ms)
9.33.0 67.3-68.1 / 67.3-68.1 79 82 17.2 / 17.2 296 302-303
this branch, the option at 0 67.3-67.4 / 67.3-67.4 79 82-83 17.3 / 17.3 293-296 301-302
maxFPS = 60 60.0-60.1 / 59.9-60.0 21 26-29 17.3 / 17.3 292-296 298-303
maxFramesInFlight = 1 46.1-46.4 / 46.1-46.4 20 23 15.1-15.2 / 15.1-15.2 64 67
maxFramesInFlight = 2 67.4-67.6 / 67.4-67.6 28 39-40 17.3 / 17.3 114 118-120
maxFramesInFlight = 3 67.3-67.5 / 67.3-67.5 42 51-52 17.3 / 17.3 171 177
maxFramesInFlight = 4 67.2-67.4 / 67.2-67.4 54-55 71-72 17.2-17.3 / 17.2-17.3 229 236-287
maxFPS = 60 and maxFramesInFlight = 2 60.0 / 59.8-60.0 21 27-28 17.2-17.3 / 17.2-17.3 113-114 119-170
maxFPS = 60 and maxFramesInFlight = 4 60.0 / 59.9-60.0 21 27-28 17.2 / 17.2 229-230 236-288

Without a frame cap (--disable-gpu-vsync --disable-frame-rate-limit), labeled apart: it shows the backpressure, it is not how anyone runs the page:

GPU ~14 ms a frame: frames per second (page / new on screen) queue latency p50 (ms) to the screen p50 (ms) GPU ~58 ms a frame: frames per second (page / new on screen) queue latency p50 (ms) to the screen p50 (ms)
9.33.0 68.5 / 0.2 5655-5656 5662 17.4 / 0.0 22410-22422 n/a
this branch, the option at 0 68.5 / 0.2 5649 5652-5654 17.4 / 0.0 22372-22410 n/a
maxFPS = 60 59.9-60.0 / 46.6-47.0 27 42-46 17.2 / 0.0-0.1 22373-22445 22431
maxFramesInFlight = 1 43.6-43.7 / 43.6-43.7 20 28-29 13.4 / 13.4 62 69-70
maxFramesInFlight = 2 60.2-60.3 / 46.9 27 44-45 17.2-17.3 / 17.1-17.2 107-109 160-164
maxFramesInFlight = 3 67.5-67.9 / 67.5-67.7 37 49-51 17.2-17.3 / 17.1-17.2 165 222-223
maxFramesInFlight = 4 67.6 / 67.3-67.4 54 70-72 17.1-17.3 / 17.0-17.2 223-224 282-285
maxFPS = 60 and maxFramesInFlight = 2 59.9-60.0 / 46.5-47.0 27 45 17.2 / 17.0-17.1 107-108 165
maxFPS = 60 and maxFramesInFlight = 4 59.9-60.0 / 47.5-48.0 27 43-44 17.3 / 17.3 223-225 229-233

What the numbers say:

  • maxFPS alone lowers the latency only while the GPU can go faster than the cap: at about 14 ms of GPU a frame the queue latency goes from 79 to 21 ms; at about 58 ms it changes nothing (296 ms with vsync, 22 s without a cap).
  • The limit bounds the queue to about N GPU frames whatever the GPU’s speed: with vsync, 2 keeps the frame rate (67.4-67.6 and 17.3 frames a second) and cuts the queue latency to 28 and 114 ms; 1 also serializes the CPU and the GPU, and costs frame rate (46 and 15).
  • No single N fits every case: frames are admitted at animation frames, so the right N depends on the browser’s pacing and on the app’s CPU and GPU times. Without a cap this browser gave the page about 100 animation frames a second, and 2 left the GPU waiting between frames (60 frames a second instead of 68), while 3 kept 67.5 new frames a second on screen. 4, the value from #10, is one candidate among these, not an optimum: a lower queue depth gave lower latency at a throughput cost.
  • Both together: maxFPS = 60 with a limit of 2 keeps the cap’s 21 ms while the GPU is faster than the cap, and the limit’s 114 ms when it is slower.
  • With vsync, the rendered frames reached the screen in every arm (0 to 2 of each run’s 188 to 844 never shown, none out of order).

How it is measured, after #11:

  • “Queue latency” is the page’s: from a frame’s start to the onSubmittedWorkDone() requested after that frame’s last submit. It is when the work submitted so far completed, not when the frame reached the display, and not an isolated GPU frame time.
  • “To the screen” is the recording’s time of a frame’s first appearance minus the frame’s start, with the recording’s clock aligned on the frame that appeared soonest after its GPU work ended, so these are lower bounds.
  • The recording against the browser’s own trace (a Chromium trace over the same 6 s, the renderer’s presented frames each counted once): with vsync and no limit, 409 frames rendered, 409 presented and 409 frame numbers read; with a limit of 2, 404 rendered and 403 read while the compositor presented 808, frames without a new canvas image included, which is why the screen side counts frame numbers. Without a cap and no limit, 2 presented and 1 read, so the missing frames were never presented, not lost by the recording; with a limit of 2, the recording read 285 of the 357 presented, so without a cap the screen side is a lower bound.
  • With a mid-frame flushFramebuffer() in every frame, a limit of 2 gives the same numbers (queue latency p50 27.6-27.7 against 27.4-27.6 ms, and 113.8-114.1 against 113.8 ms): one count per frame, its intermediate submits included.

The page side alone, as a Playground (the same shader and frame counter; maxFPS on 9.33.0, and maxFramesInFlight too on a build that has it): https://playground.babylonjs.com/#Z5AB7J#0. It reports the frames rendered and the queue latency; what reaches the screen needs a recording. On 9.33.0 it shows maxFPS helping only while the GPU is faster than the cap (WebGPU, about 9 to 10 ms of GPU a frame: 55-59 → 12-13 ms; about 43 to 46 ms: 171-180 → 180-213 ms); on our branch, at about 41 ms of GPU a frame, a limit of 2 takes the queue latency from 205 to 81 ms.

The PR comes next: off by default, in the frame admission (_processFrame, before maxFPS, so a frame held back starts nothing), one count per frame released by onSubmittedWorkDone() after the frame’s last submit, counted per device, and tested for stop/restart, background/resume and device loss (in the browser, with a limit of 2 against none, the same frames came back in the 2 s after each event: back in front, after a 5 s freeze, after a device loss and restore, and after stopping and restarting the render loop).

Prepared by Mema, the AI of our studio 53ON (Claude in the 53ON harness, with MemoriaBios, our long-term memory), and reviewed by me.

Opened three PRs: #19089, the recorded draws, third in the order of #14, on top of #19037 and #19038 (both merged, in 9.33.0); #19093, the frames-in-flight limit of the comparison just above; and #19091, a smaller one on texture views.

The recorded draws. When a FAST snapshot records again, a draw whose inputs did not change is encoded again from the commands it was last encoded with (pipeline, bind groups, index and vertex buffers, draw arguments) into the snapshot’s bundle encoder, without going through Mesh.render, the readiness checks and the material bind. The scene walk stays as it is: culling, LOD, render order and the set of draws are computed again, and there is still one bundle per pass, so the replay does not change. The description lists what a re-encoded draw depends on, what sends it through the full path, and what is never recorded.

On the cases in #11:

  • Animated geometry. A draw whose bound buffers only change their content is still encoded again from its commands, and the GPU reads the new content: thin instances moved in their matrix buffer render as normal rendering in all 120 frames of the test. A changed instance count or a new buffer sends the draw through the full path.
  • The road spline. drawIndexed records its first index and count, so a sub mesh that moves its index range with the same instance count is never encoded again from its old commands: its range is checked, and it goes through a full draw, which encodes the new arguments. With an indirect draw the arguments live in the indirect buffer, and setIndirectData() wrote them only when the instance count changed, so a moved range never reached the GPU, in a recording as in compatibilityMode = false, where instanced draws use the indirect buffer of their own bundle. The PR also compares the count and the first index there, with a unit test that fails on the old check.
  • History swaps. Post-processes always take the full path at each recording, so their bind groups get the current history textures. A material whose texture swaps its internal texture (a ping-pong) goes through a full bind.

The road case shows on 9.33.0 without a snapshot too. In this Playground a strip draws a moving window of its index buffer as two thin instances, and at each move the canvas is read back: https://playground.babylonjs.com/#4HP2IW#0

Moves whose window is drawn (of 8)
WebGPU, compatibilityMode = false 1 (it keeps its first window)
WebGPU, compatibility mode 8
WebGPU, FAST snapshot recorded again at each move 8
WebGL2 8

On this PR’s build the four give 8, and so does the FAST snapshot with the recorded draws on.

Measured with the numbers #9 asked for, on our deterministic scene (1,200 meshes, a 4-cascade CSM, a moving camera, every 30 frames 60 meshes replaced and a texture swapped, then a new FAST recording; the prepass with velocity, thin instances and the road are separate cases in the description), 300 frames, 2 rounds in alternating order, Chromium 147, RTX 3080 Laptop GPU, against 9.33.0:

9.33.0 this PR, recorded draws off on
Recording frame, CPU (compatibilityMode on / off) 34.5-36.0 / 38.5-38.7 ms 34.2-34.7 / 35.3-36.1 ms 30.2-32.2 / 32.4-33.1 ms
New recordings over 33 ms (of 9) 4-5 / 4-7 4-5 / 5 2-4 / 3-4
writeBuffer in a recording frame: calls / KB 135 / 143 135 / 143 135 / 143
Render bundles created per recording / executed per replayed frame 5 / 5 5 / 5 5 / 5
Replayed frame, CPU / GPU p99 0.71-0.76 / 12.2-12.7 ms 0.71-0.72 / 11.4-13.1 ms 0.69-0.73 / 11.4-12.5 ms
JS heap after the churn (after a full collection) 38.3 MB 38.6 MB 40.1 MB

With the recorded draws off, the PR records like 9.33.0: nothing of it runs then. With them on, a recording frame takes 8-12% less, no bundle is added, and the heap keeps 1.5 MB more for the 5,596 draws it keeps. A recording with nothing changed takes 23.3 ms of JavaScript instead of 30.7 (31.3 on 9.33.0; a sampling profile, the mean of 5). The images match 9.33.0 in every case of the description but the road one, where 9.33.0 keeps the indirect strip on its first window.

One question for you in the description of #19089: should snapshotRenderingReset() stay a full new recording, with an opt-in that keeps the clean recorded draws?

The frames-in-flight limit. #19093 is the limit compared above, off by default; its description has the same tables, the browser checks and the unit tests.

Texture views. On WebGPU, getView finds a cached texture view by comparing the descriptor’s fields instead of building a key string on every call. With 24 render targets per frame, that is 18 KB less allocated per frame (-23%) and 20% fewer scavenges, with byte-identical images. The full comparison is in the description of #19091.

Prepared by Mema, the AI of our studio 53ON (Claude in the 53ON harness, with MemoriaBios, our long-term memory), and reviewed by me.