Repository navigation
Cold Specialization - #17567
Cold Specialization#17567
Conversation
pcwalton
left a comment
There was a problem hiding this comment.
A couple of comments to start with. I'll have more later when I take a closer look.
| .render_lightmaps | ||
| .get(&entity) | ||
| .map(|lightmap| lightmap.slab_index); | ||
| self.shared.lightmap_slab_index = lightmap_slab_index; |
There was a problem hiding this comment.
Check pass ordering here. Are we sure that render_lightmaps is populated before this runs?
There was a problem hiding this comment.
Okay, will check. I also think that Lightmap needs to be added to the invalidation logic.
There was a problem hiding this comment.
Looks like we're good, as RenderLightmaps is populated during the extraction phase, and RenderMeshInstanceGpuBuilder::update is called during the collection subphase of the render phase.
pcwalton
left a comment
There was a problem hiding this comment.
This is a more thorough review. I mostly just had some simplification suggestions that you can do if you want. This is great stuff.
| .render_lightmaps | ||
| .get(&entity) | ||
| .map(|lightmap| lightmap.slab_index); | ||
| self.shared.lightmap_slab_index = lightmap_slab_index; |
There was a problem hiding this comment.
Looks like we're good, as RenderLightmaps is populated during the extraction phase, and RenderMeshInstanceGpuBuilder::update is called during the collection subphase of the render phase.
|
@tychedelia when you get a chance could you please finish up the migration guide? |
This reverts commit 2ea5e9b.
This reverts commit 2ea5e9b.
This PR makes Bevy keep entities in bins from frame to frame if they haven't changed. This reduces the time spent in `queue_material_meshes` and related functions to near zero for static geometry. This patch uses the same change tick technique that #17567 uses to detect when meshes have changed in such a way as to require re-binning. In order to quickly find the relevant bin for an entity when that entity has changed, we introduce a new type of cache, the *bin key cache*. This cache stores a mapping from main world entity ID to cached bin key, as well as the tick of the most recent change to the entity. As we iterate through the visible entities in `queue_material_meshes`, we check the cache to see whether the entity needs to be re-binned. If it doesn't, then we mark it as clean in the `valid_cached_entity_bin_keys` bit set. If it does, then we insert it into the correct bin, and then mark the entity as clean. At the end, all entities not marked as clean are removed from the bins. This patch has a dramatic effect on the rendering performance of most benchmarks, as it effectively eliminates `queue_material_meshes` from the profile. Note, however, that it generally simultaneously regresses `batch_and_prepare_binned_render_phase` by a bit (not by enough to outweigh the win, however). I believe that's because, before this patch, `queue_material_meshes` put the bins in the CPU cache for `batch_and_prepare_binned_render_phase` to use, while with this patch, `batch_and_prepare_binned_render_phase` must load the bins into the CPU cache itself. On Caldera, this reduces the time spent in `queue_material_meshes` from 5+ ms to 0.2ms-0.3ms. Note that benchmarking on that scene is very noisy right now because of #17535. 
# Cold Specialization ## Objective An ongoing part of our quest to retain everything in the render world, cold-specialization aims to cache pipeline specialization so that pipeline IDs can be recomputed only when necessary, rather than every frame. This approach reduces redundant work in stable scenes, while still accommodating scenarios in which materials, views, or visibility might change, as well as unlocking future optimization work like retaining render bins. ## Solution Queue systems are split into a specialization system and queue system, the former of which only runs when necessary to compute a new pipeline id. Pipelines are invalidated using a combination of change detection and ECS ticks. ### The difficulty with change detection Detecting “what changed” can be tricky because pipeline specialization depends not only on the entity’s components (e.g., mesh, material, etc.) but also on which view (camera) it is rendering in. In other words, the cache key for a given pipeline id is a view entity/render entity pair. As such, it's not sufficient simply to react to change detection in order to specialize -- an entity could currently be out of view or could be rendered in the future in camera that is currently disabled or hasn't spawned yet. ### Why ticks? Ticks allow us to ensure correctness by allowing us to compare the last time a view or entity was updated compared to the cached pipeline id. This ensures that even if an entity was out of view or has never been seen in a given camera before we can still correctly determine whether it needs to be re-specialized or not. ## Testing TODO: Tested a bunch of different examples, need to test more. ## Migration Guide TODO - `AssetEvents` has been moved into the `PostUpdate` schedule. --------- Co-authored-by: Patrick Walton <pcwalton@mimiga.net>
This PR makes Bevy keep entities in bins from frame to frame if they haven't changed. This reduces the time spent in `queue_material_meshes` and related functions to near zero for static geometry. This patch uses the same change tick technique that bevyengine#17567 uses to detect when meshes have changed in such a way as to require re-binning. In order to quickly find the relevant bin for an entity when that entity has changed, we introduce a new type of cache, the *bin key cache*. This cache stores a mapping from main world entity ID to cached bin key, as well as the tick of the most recent change to the entity. As we iterate through the visible entities in `queue_material_meshes`, we check the cache to see whether the entity needs to be re-binned. If it doesn't, then we mark it as clean in the `valid_cached_entity_bin_keys` bit set. If it does, then we insert it into the correct bin, and then mark the entity as clean. At the end, all entities not marked as clean are removed from the bins. This patch has a dramatic effect on the rendering performance of most benchmarks, as it effectively eliminates `queue_material_meshes` from the profile. Note, however, that it generally simultaneously regresses `batch_and_prepare_binned_render_phase` by a bit (not by enough to outweigh the win, however). I believe that's because, before this patch, `queue_material_meshes` put the bins in the CPU cache for `batch_and_prepare_binned_render_phase` to use, while with this patch, `batch_and_prepare_binned_render_phase` must load the bins into the CPU cache itself. On Caldera, this reduces the time spent in `queue_material_meshes` from 5+ ms to 0.2ms-0.3ms. Note that benchmarking on that scene is very noisy right now because of bevyengine#17535. 
|
Thank you to everyone involved with the authoring or reviewing of this PR! This work is relatively important and needs release notes! Head over to bevyengine/bevy-website#1989 if you'd like to help out. |
…ntities # Objective Fixes bevyengine#25163. A 2D scene mixing blended `Mesh2d` entities with sprites starts blinking out for single frames once the scene has been despawned and respawned a few times, even though nothing in it moves. It never happens on the first spawn. `queue_material2d_meshes` is the only system that removes items from the retained sorted `Transparent2d` phase (and from the binned 2D phases), but it returns early when `render_material_instances` is empty — which is exactly the frame the last entity using that material type is despawned. Those items then stay in the phase forever: `removed_entities` and `removed_renderables` are per-frame lists, so by the next frame there is nothing left to act on. A leftover item also keeps the `batch_range` it was last batched with, because `batch_and_prepare_sorted_render_phase` only rewrites the range of items that still have a `RenderMesh2dInstance`. And `SortedRenderPhase::render_range` draws an item and then advances by `batch_range.len()`, assuming the batch it just drew covers that many following items: ```rust if batch_range.is_empty() { index += 1; } else { draw_function.draw(world, render_pass, view, item)?; index += batch_range.len(); } ``` So an item left behind by a batch of three steps over the two live items sitting behind it, and they are never drawn. Which items those are depends on the order among equal sort keys, which changes every frame, so it reads as random flicker rather than a permanently missing object. The early return predates the dequeue loop: it was added in bevyengine#17567, when this system only ever added items, and the removal logic landed later in bevyengine#23083 on top of it. `queue_material_meshes` on the 3D side dequeues unconditionally and has no such early return. ## Solution Keep the fast path where it is still valid — with no entity using the material there is nothing to queue — but move it below the dequeue loop and make it `continue` instead of `return`, so items of despawned entities always leave the phase. ## Testing Measured with a static scene (nothing moves, the camera never changes) of 7 permanent sprites, 7 more permanent sprites sorting before the churn, and 3 blended `Mesh2d` quads sharing one mesh and one `ColorMaterial` that are despawned and respawned every 30 frames. Instead of comparing pixels, a system in `RenderSystems::Cleanup` walks the phase the way `render_range` does and counts items that end up never drawn. Over 240 frames on 0.19.0: the phase grows from 17 to 26 items, 12 of them belonging to despawned entities, and 102 frames drop at least one live item — 157 drops in total, every one of them a permanent sprite that should never blink. With this change the phase stays at 14 items, no items of despawned entities are left in it, and nothing is dropped. The sprites that sort before the churn are never affected either way, which is what points at the phase order rather than at the display. macOS 15 on Apple Silicon, Metal.
…25163) # Objective Fixes bevyengine#25163. `queue_material2d_meshes` is the only system that removes items from the retained 2D phases, but it returns early when `render_material_instances` is empty — the very frame the last entity of that material type is despawned. Those items stay in the phase forever, keeping the `batch_range` they were last batched with, and `SortedRenderPhase::render_range` advances by `batch_range.len()` after each draw, so a leftover batch leader steps over the live items behind it. Which items those are depends on the order among equal sort keys, and that changes every frame, so it reads as flicker. The early return predates the dequeue loop: bevyengine#17567 added it when this system only queued, bevyengine#23083 added removal on top of it. The 3D `queue_material_meshes` dequeues unconditionally. ## Solution Keep the fast path — with no entity using the material there is nothing to queue — but move it below the dequeue loop and make it `continue`. ## Testing Static scene: 3 blended `Mesh2d` quads sharing a mesh and material, respawned every 30 frames, next to permanent sprites. A system in `RenderSystems::Cleanup` walks the phase the way `render_range` does and counts items that end up never drawn. Over 240 frames on 0.19.0 the phase grows from 17 to 26 items and 102 frames drop a live sprite (157 drops). With this change the phase stays at 14 items and nothing is dropped. macOS on Apple Silicon, Metal.
…25163) # Objective Fixes bevyengine#25163. `queue_material2d_meshes` is the only system that takes items out of the retained 2D phases, and it returns early when `render_material_instances` is empty. That is the frame the last entity using that material type gets despawned, so its items never get removed and stay in the phase for good. They also keep the `batch_range` they had when they were last batched, since `batch_and_prepare_sorted_render_phase` only rewrites the range of items that still have a `RenderMesh2dInstance`. `render_range` advances the index by `batch_range.len()` after every draw, so an item left over from a batch of three hides the two live items behind it. With equal sort keys the order changes from frame to frame, which is why it shows up as flicker instead of something permanently missing. The early return is older than the dequeue loop (bevyengine#17567 added it back when the system only queued, bevyengine#23083 added the removal). The 3D `queue_material_meshes` doesn't have one. ## Solution Move the check below the dequeue loop and make it a `continue`. There is still nothing to queue when no entity uses the material, but removal now always happens. ## Testing 3 blended `Mesh2d` quads sharing a mesh and material, respawned every 30 frames, plus a few permanent sprites. Nothing in the scene moves. I counted items that never get drawn from a `RenderSystems::Cleanup` system that walks the phase the same way `render_range` does. 240 frames on 0.19.0: the phase grows 17 -> 26 items, 102 frames drop a live sprite, 157 drops in total. Same run with this patch: 14 items, no drops. Tested on macOS/Metal (Apple Silicon).
…25163) # Objective Fixes bevyengine#25163. `queue_material2d_meshes` is the only system that takes items out of the retained 2D phases, and it returns early when `render_material_instances` is empty. That is the frame the last entity using that material type gets despawned, so its items never get removed and stay in the phase for good. They also keep the `batch_range` they had when they were last batched, since `batch_and_prepare_sorted_render_phase` only rewrites the range of items that still have a `RenderMesh2dInstance`. `render_range` advances the index by `batch_range.len()` after every draw, so an item left over from a batch of three hides the two live items behind it. With equal sort keys the order changes from frame to frame, which is why it shows up as flicker instead of something permanently missing. The early return is older than the dequeue loop (bevyengine#17567 added it back when the system only queued, bevyengine#23083 added the removal). The 3D `queue_material_meshes` doesn't have one. ## Solution Move the check below the dequeue loop and make it a `continue`. There is still nothing to queue when no entity uses the material, but removal now always happens. ## Testing Static scene, nothing moves: 7 permanent sprites at the same z as the churn, 7 more permanent sprites sorting before it, and 3 blended `Mesh2d` quads sharing a mesh and material that get despawned and respawned every 30 frames. From a `RenderSystems::Cleanup` system I walk the phase the way `render_range` does and count the live items it steps over. 240 frames on 0.19.0: the phase ends up holding 26 items, 12 of which belong to entities that no longer exist (3 more per respawn, and they are never cleaned up), and 102 of those frames step over a live item, 157 in total. Every one is a permanent sprite; never a quad from the churn, never a sprite sorting ahead of it. One step usually costs a whole row on screen, because the item skipped is the leader of a batch of 7 sprites. Same run with this patch: 14 items in the phase, none of them dead, nothing stepped over.
…25163) # Objective Fixes bevyengine#25163. `queue_material2d_meshes` is the only system that takes items out of the retained 2D phases, and it returns early when `render_material_instances` is empty. That is the frame the last entity using that material type gets despawned, so its items never get removed and stay in the phase for good. They also keep the `batch_range` they had when they were last batched, since `batch_and_prepare_sorted_render_phase` only rewrites the range of items that still have a `RenderMesh2dInstance`. `render_range` advances the index by `batch_range.len()` after every draw, so an item left over from a batch of three hides the two live items behind it. With equal sort keys the order changes from frame to frame, which is why it shows up as flicker instead of something permanently missing. The early return is older than the dequeue loop (bevyengine#17567 added it back when the system only queued, bevyengine#23083 added the removal). The 3D `queue_material_meshes` doesn't have one. ## Solution Move the check below the dequeue loop and make it a `continue`. There is still nothing to queue when no entity uses the material, but removal now always happens.
…25163) (bevyengine#25253) # Objective Fixes bevyengine#25163. `queue_material2d_meshes` is the only system that takes items out of the retained 2D phases, and it returns early when `render_material_instances` is empty. That is the frame the last entity using that material type gets despawned, so its items never get removed and stay in the phase for good. They also keep the `batch_range` they had when they were last batched, since `batch_and_prepare_sorted_render_phase` only rewrites the range of items that still have a `RenderMesh2dInstance`. `render_range` advances the index by `batch_range.len()` after every draw, so an item left over from a batch of three hides the two live items behind it. With equal sort keys the order changes from frame to frame, which is why it shows up as flicker instead of something permanently missing. The early return is older than the dequeue loop (bevyengine#17567 added it back when the system only queued, bevyengine#23083 added the removal). The 3D `queue_material_meshes` doesn't have one. ## Solution Move the check below the dequeue loop and make it a `continue`. There is still nothing to queue when no entity uses the material, but removal now always happens. ## Testing In my own app after applying the patch tree shadows stopped flickering <img width="1717" height="1224" alt="image" src="https://github.com/user-attachments/assets/26022cbc-bc82-4894-9d43-5fffa311cedd" />
…25163) (bevyengine#25253) # Objective Fixes bevyengine#25163. `queue_material2d_meshes` is the only system that takes items out of the retained 2D phases, and it returns early when `render_material_instances` is empty. That is the frame the last entity using that material type gets despawned, so its items never get removed and stay in the phase for good. They also keep the `batch_range` they had when they were last batched, since `batch_and_prepare_sorted_render_phase` only rewrites the range of items that still have a `RenderMesh2dInstance`. `render_range` advances the index by `batch_range.len()` after every draw, so an item left over from a batch of three hides the two live items behind it. With equal sort keys the order changes from frame to frame, which is why it shows up as flicker instead of something permanently missing. The early return is older than the dequeue loop (bevyengine#17567 added it back when the system only queued, bevyengine#23083 added the removal). The 3D `queue_material_meshes` doesn't have one. ## Solution Move the check below the dequeue loop and make it a `continue`. There is still nothing to queue when no entity uses the material, but removal now always happens. ## Testing In my own app after applying the patch tree shadows stopped flickering <img width="1717" height="1224" alt="image" src="https://github.com/user-attachments/assets/26022cbc-bc82-4894-9d43-5fffa311cedd" />
…gine#25926) bevyengine#17567 introduced a bug where we always queue alpha masked meshes in the AlphaMask3d phase, even when they're intended to be rendered as deferred. This means we end up drawing the alpha masked mesh in the deferred prepass, shading it, and then it gets redrawn again in the forward pass. I fixed the system to skip queuing into the AlphaMask3d phase when it's intended for deferred, mirroring what we do in the opaque phase in the same file. Tested in a branch of solari I'm working on that supports alpha masks. Before the fix, it would render with solari, then re-render in the forward pass and overwrite the pixels. With this PR, it looks correct, as solari is the only one to render it. (bug found and fixed by AI, with me checking that it makes sense)
#17567 introduced a bug where we always queue alpha masked meshes in the AlphaMask3d phase, even when they're intended to be rendered as deferred. This means we end up drawing the alpha masked mesh in the deferred prepass, shading it, and then it gets redrawn again in the forward pass. I fixed the system to skip queuing into the AlphaMask3d phase when it's intended for deferred, mirroring what we do in the opaque phase in the same file. Tested in a branch of solari I'm working on that supports alpha masks. Before the fix, it would render with solari, then re-render in the forward pass and overwrite the pixels. With this PR, it looks correct, as solari is the only one to render it. (bug found and fixed by AI, with me checking that it makes sense)
Cold Specialization
Objective
An ongoing part of our quest to retain everything in the render world, cold-specialization aims to cache pipeline specialization so that pipeline IDs can be recomputed only when necessary, rather than every frame. This approach reduces redundant work in stable scenes, while still accommodating scenarios in which materials, views, or visibility might change, as well as unlocking future optimization work like retaining render bins.
Solution
Queue systems are split into a specialization system and queue system, the former of which only runs when necessary to compute a new pipeline id. Pipelines are invalidated using a combination of change detection and ECS ticks.
The difficulty with change detection
Detecting “what changed” can be tricky because pipeline specialization depends not only on the entity’s components (e.g., mesh, material, etc.) but also on which view (camera) it is rendering in. In other words, the cache key for a given pipeline id is a view entity/render entity pair. As such, it's not sufficient simply to react to change detection in order to specialize -- an entity could currently be out of view or could be rendered in the future in camera that is currently disabled or hasn't spawned yet.
Why ticks?
Ticks allow us to ensure correctness by allowing us to compare the last time a view or entity was updated compared to the cached pipeline id. This ensures that even if an entity was out of view or has never been seen in a given camera before we can still correctly determine whether it needs to be re-specialized or not.
Testing
TODO: Tested a bunch of different examples, need to test more.
Migration Guide
TODO
AssetEventshas been moved into thePostUpdateschedule.