mirror of
https://github.com/bevyengine/bevy
synced 2025-01-08 19:29:04 +00:00
5c884c5a15
# Objective - Implement the foundations of automatic batching/instancing of draw commands as the next step from #89 - NOTE: More performance improvements will come when more data is managed and bound in ways that do not require rebinding such as mesh, material, and texture data. ## Solution - The core idea for batching of draw commands is to check whether any of the information that has to be passed when encoding a draw command changes between two things that are being drawn according to the sorted render phase order. These should be things like the pipeline, bind groups and their dynamic offsets, index/vertex buffers, and so on. - The following assumptions have been made: - Only entities with prepared assets (pipelines, materials, meshes) are queued to phases - View bindings are constant across a phase for a given draw function as phases are per-view - `batch_and_prepare_render_phase` is the only system that performs this batching and has sole responsibility for preparing the per-object data. As such the mesh binding and dynamic offsets are assumed to only vary as a result of the `batch_and_prepare_render_phase` system, e.g. due to having to split data across separate uniform bindings within the same buffer due to the maximum uniform buffer binding size. - Implement `GpuArrayBuffer` for `Mesh2dUniform` to store Mesh2dUniform in arrays in GPU buffers rather than each one being at a dynamic offset in a uniform buffer. This is the same optimisation that was made for 3D not long ago. - Change batch size for a range in `PhaseItem`, adding API for getting or mutating the range. This is more flexible than a size as the length of the range can be used in place of the size, but the start and end can be otherwise whatever is needed. - Add an optional mesh bind group dynamic offset to `PhaseItem`. This avoids having to do a massive table move just to insert `GpuArrayBufferIndex` components. ## Benchmarks All tests have been run on an M1 Max on AC power. `bevymark` and `many_cubes` were modified to use 1920x1080 with a scale factor of 1. I run a script that runs a separate Tracy capture process, and then runs the bevy example with `--features bevy_ci_testing,trace_tracy` and `CI_TESTING_CONFIG=../benchmark.ron` with the contents of `../benchmark.ron`: ```rust ( exit_after: Some(1500) ) ``` ...in order to run each test for 1500 frames. The recent changes to `many_cubes` and `bevymark` added reproducible random number generation so that with the same settings, the same rng will occur. They also added benchmark modes that use a fixed delta time for animations. Combined this means that the same frames should be rendered both on main and on the branch. The graphs compare main (yellow) to this PR (red). ### 3D Mesh `many_cubes --benchmark` <img width="1411" alt="Screenshot 2023-09-03 at 23 42 10" src="https://github.com/bevyengine/bevy/assets/302146/2088716a-c918-486c-8129-090b26fd2bc4"> The mesh and material are the same for all instances. This is basically the best case for the initial batching implementation as it results in 1 draw for the ~11.7k visible meshes. It gives a ~30% reduction in median frame time. The 1000th frame is identical using the flip tool: ![flip many_cubes-main-mesh3d many_cubes-batching-mesh3d 67ppd ldr](https://github.com/bevyengine/bevy/assets/302146/2511f37a-6df8-481a-932f-706ca4de7643) ``` Mean: 0.000000 Weighted median: 0.000000 1st weighted quartile: 0.000000 3rd weighted quartile: 0.000000 Min: 0.000000 Max: 0.000000 Evaluation time: 0.4615 seconds ``` ### 3D Mesh `many_cubes --benchmark --material-texture-count 10` <img width="1404" alt="Screenshot 2023-09-03 at 23 45 18" src="https://github.com/bevyengine/bevy/assets/302146/5ee9c447-5bd2-45c6-9706-ac5ff8916daf"> This run uses 10 different materials by varying their textures. The materials are randomly selected, and there is no sorting by material bind group for opaque 3D so any batching is 'random'. The PR produces a ~5% reduction in median frame time. If we were to sort the opaque phase by the material bind group, then this should be a lot faster. This produces about 10.5k draws for the 11.7k visible entities. This makes sense as randomly selecting from 10 materials gives a chance that two adjacent entities randomly select the same material and can be batched. The 1000th frame is identical in flip: ![flip many_cubes-main-mesh3d-mtc10 many_cubes-batching-mesh3d-mtc10 67ppd ldr](https://github.com/bevyengine/bevy/assets/302146/2b3a8614-9466-4ed8-b50c-d4aa71615dbb) ``` Mean: 0.000000 Weighted median: 0.000000 1st weighted quartile: 0.000000 3rd weighted quartile: 0.000000 Min: 0.000000 Max: 0.000000 Evaluation time: 0.4537 seconds ``` ### 3D Mesh `many_cubes --benchmark --vary-per-instance` <img width="1394" alt="Screenshot 2023-09-03 at 23 48 44" src="https://github.com/bevyengine/bevy/assets/302146/f02a816b-a444-4c18-a96a-63b5436f3b7f"> This run varies the material data per instance by randomly-generating its colour. This is the worst case for batching and that it performs about the same as `main` is a good thing as it demonstrates that the batching has minimal overhead when dealing with ~11k visible mesh entities. The 1000th frame is identical according to flip: ![flip many_cubes-main-mesh3d-vpi many_cubes-batching-mesh3d-vpi 67ppd ldr](https://github.com/bevyengine/bevy/assets/302146/ac5f5c14-9bda-4d1a-8219-7577d4aac68c) ``` Mean: 0.000000 Weighted median: 0.000000 1st weighted quartile: 0.000000 3rd weighted quartile: 0.000000 Min: 0.000000 Max: 0.000000 Evaluation time: 0.4568 seconds ``` ### 2D Mesh `bevymark --benchmark --waves 160 --per-wave 1000 --mode mesh2d` <img width="1412" alt="Screenshot 2023-09-03 at 23 59 56" src="https://github.com/bevyengine/bevy/assets/302146/cb02ae07-237b-4646-ae9f-fda4dafcbad4"> This spawns 160 waves of 1000 quad meshes that are shaded with ColorMaterial. Each wave has a different material so 160 waves currently should result in 160 batches. This results in a 50% reduction in median frame time. Capturing a screenshot of the 1000th frame main vs PR gives: ![flip bevymark-main-mesh2d bevymark-batching-mesh2d 67ppd ldr](https://github.com/bevyengine/bevy/assets/302146/80102728-1217-4059-87af-14d05044df40) ``` Mean: 0.001222 Weighted median: 0.750432 1st weighted quartile: 0.453494 3rd weighted quartile: 0.969758 Min: 0.000000 Max: 0.990296 Evaluation time: 0.4255 seconds ``` So they seem to produce the same results. I also double-checked the number of draws. `main` does 160000 draws, and the PR does 160, as expected. ### 2D Mesh `bevymark --benchmark --waves 160 --per-wave 1000 --mode mesh2d --material-texture-count 10` <img width="1392" alt="Screenshot 2023-09-04 at 00 09 22" src="https://github.com/bevyengine/bevy/assets/302146/4358da2e-ce32-4134-82df-3ab74c40849c"> This generates 10 textures and generates materials for each of those and then selects one material per wave. The median frame time is reduced by 50%. Similar to the plain run above, this produces 160 draws on the PR and 160000 on `main` and the 1000th frame is identical (ignoring the fps counter text overlay). ![flip bevymark-main-mesh2d-mtc10 bevymark-batching-mesh2d-mtc10 67ppd ldr](https://github.com/bevyengine/bevy/assets/302146/ebed2822-dce7-426a-858b-b77dc45b986f) ``` Mean: 0.002877 Weighted median: 0.964980 1st weighted quartile: 0.668871 3rd weighted quartile: 0.982749 Min: 0.000000 Max: 0.992377 Evaluation time: 0.4301 seconds ``` ### 2D Mesh `bevymark --benchmark --waves 160 --per-wave 1000 --mode mesh2d --vary-per-instance` <img width="1396" alt="Screenshot 2023-09-04 at 00 13 53" src="https://github.com/bevyengine/bevy/assets/302146/b2198b18-3439-47ad-919a-cdabe190facb"> This creates unique materials per instance by randomly-generating the material's colour. This is the worst case for 2D batching. Somehow, this PR manages a 7% reduction in median frame time. Both main and this PR issue 160000 draws. The 1000th frame is the same: ![flip bevymark-main-mesh2d-vpi bevymark-batching-mesh2d-vpi 67ppd ldr](https://github.com/bevyengine/bevy/assets/302146/a2ec471c-f576-4a36-a23b-b24b22578b97) ``` Mean: 0.001214 Weighted median: 0.937499 1st weighted quartile: 0.635467 3rd weighted quartile: 0.979085 Min: 0.000000 Max: 0.988971 Evaluation time: 0.4462 seconds ``` ### 2D Sprite `bevymark --benchmark --waves 160 --per-wave 1000 --mode sprite` <img width="1396" alt="Screenshot 2023-09-04 at 12 21 12" src="https://github.com/bevyengine/bevy/assets/302146/8b31e915-d6be-4cac-abf5-c6a4da9c3d43"> This just spawns 160 waves of 1000 sprites. There should be and is no notable difference between main and the PR. ### 2D Sprite `bevymark --benchmark --waves 160 --per-wave 1000 --mode sprite --material-texture-count 10` <img width="1389" alt="Screenshot 2023-09-04 at 12 36 08" src="https://github.com/bevyengine/bevy/assets/302146/45fe8d6d-c901-4062-a349-3693dd044413"> This spawns the sprites selecting a texture at random per instance from the 10 generated textures. This has no significant change vs main and shouldn't. ### 2D Sprite `bevymark --benchmark --waves 160 --per-wave 1000 --mode sprite --vary-per-instance` <img width="1401" alt="Screenshot 2023-09-04 at 12 29 52" src="https://github.com/bevyengine/bevy/assets/302146/762c5c60-352e-471f-8dbe-bbf10e24ebd6"> This sets the sprite colour as being unique per instance. This can still all be drawn using one batch. There should be no difference but the PR produces median frame times that are 4% higher. Investigation showed no clear sources of cost, rather a mix of give and take that should not happen. It seems like noise in the results. ### Summary | Benchmark | % change in median frame time | | ------------- | ------------- | | many_cubes | 🟩 -30% | | many_cubes 10 materials | 🟩 -5% | | many_cubes unique materials | 🟩 ~0% | | bevymark mesh2d | 🟩 -50% | | bevymark mesh2d 10 materials | 🟩 -50% | | bevymark mesh2d unique materials | 🟩 -7% | | bevymark sprite | 🟥 2% | | bevymark sprite 10 materials | 🟥 0.6% | | bevymark sprite unique materials | 🟥 4.1% | --- ## Changelog - Added: 2D and 3D mesh entities that share the same mesh and material (same textures, same data) are now batched into the same draw command for better performance. --------- Co-authored-by: robtfm <50659922+robtfm@users.noreply.github.com> Co-authored-by: Nicola Papale <nico@nicopap.ch>
648 lines
22 KiB
Rust
648 lines
22 KiB
Rust
use bevy_app::{App, Plugin};
|
|
use bevy_asset::{Asset, AssetApp, AssetEvent, AssetId, AssetServer, Assets, Handle};
|
|
use bevy_core_pipeline::{
|
|
core_2d::Transparent2d,
|
|
tonemapping::{DebandDither, Tonemapping},
|
|
};
|
|
use bevy_derive::{Deref, DerefMut};
|
|
use bevy_ecs::{
|
|
prelude::*,
|
|
query::ROQueryItem,
|
|
system::{
|
|
lifetimeless::{Read, SRes},
|
|
SystemParamItem,
|
|
},
|
|
};
|
|
use bevy_log::error;
|
|
use bevy_render::{
|
|
mesh::{Mesh, MeshVertexBufferLayout},
|
|
prelude::Image,
|
|
render_asset::{prepare_assets, RenderAssets},
|
|
render_phase::{
|
|
AddRenderCommand, DrawFunctions, PhaseItem, RenderCommand, RenderCommandResult,
|
|
RenderPhase, SetItemPipeline, TrackedRenderPass,
|
|
},
|
|
render_resource::{
|
|
AsBindGroup, AsBindGroupError, BindGroup, BindGroupId, BindGroupLayout,
|
|
OwnedBindingResource, PipelineCache, RenderPipelineDescriptor, Shader, ShaderRef,
|
|
SpecializedMeshPipeline, SpecializedMeshPipelineError, SpecializedMeshPipelines,
|
|
},
|
|
renderer::RenderDevice,
|
|
texture::FallbackImage,
|
|
view::{ExtractedView, InheritedVisibility, Msaa, ViewVisibility, Visibility, VisibleEntities},
|
|
Extract, ExtractSchedule, Render, RenderApp, RenderSet,
|
|
};
|
|
use bevy_transform::components::{GlobalTransform, Transform};
|
|
use bevy_utils::{FloatOrd, HashMap, HashSet};
|
|
use std::hash::Hash;
|
|
use std::marker::PhantomData;
|
|
|
|
use crate::{
|
|
DrawMesh2d, Mesh2dHandle, Mesh2dPipeline, Mesh2dPipelineKey, Mesh2dTransforms,
|
|
SetMesh2dBindGroup, SetMesh2dViewBindGroup,
|
|
};
|
|
|
|
/// Materials are used alongside [`Material2dPlugin`] and [`MaterialMesh2dBundle`]
|
|
/// to spawn entities that are rendered with a specific [`Material2d`] type. They serve as an easy to use high level
|
|
/// way to render [`Mesh2dHandle`] entities with custom shader logic.
|
|
///
|
|
/// Material2ds must implement [`AsBindGroup`] to define how data will be transferred to the GPU and bound in shaders.
|
|
/// [`AsBindGroup`] can be derived, which makes generating bindings straightforward. See the [`AsBindGroup`] docs for details.
|
|
///
|
|
/// # Example
|
|
///
|
|
/// Here is a simple Material2d implementation. The [`AsBindGroup`] derive has many features. To see what else is available,
|
|
/// check out the [`AsBindGroup`] documentation.
|
|
/// ```
|
|
/// # use bevy_sprite::{Material2d, MaterialMesh2dBundle};
|
|
/// # use bevy_ecs::prelude::*;
|
|
/// # use bevy_reflect::TypePath;
|
|
/// # use bevy_render::{render_resource::{AsBindGroup, ShaderRef}, texture::Image, color::Color};
|
|
/// # use bevy_asset::{Handle, AssetServer, Assets, Asset};
|
|
///
|
|
/// #[derive(AsBindGroup, Debug, Clone, Asset, TypePath)]
|
|
/// pub struct CustomMaterial {
|
|
/// // Uniform bindings must implement `ShaderType`, which will be used to convert the value to
|
|
/// // its shader-compatible equivalent. Most core math types already implement `ShaderType`.
|
|
/// #[uniform(0)]
|
|
/// color: Color,
|
|
/// // Images can be bound as textures in shaders. If the Image's sampler is also needed, just
|
|
/// // add the sampler attribute with a different binding index.
|
|
/// #[texture(1)]
|
|
/// #[sampler(2)]
|
|
/// color_texture: Handle<Image>,
|
|
/// }
|
|
///
|
|
/// // All functions on `Material2d` have default impls. You only need to implement the
|
|
/// // functions that are relevant for your material.
|
|
/// impl Material2d for CustomMaterial {
|
|
/// fn fragment_shader() -> ShaderRef {
|
|
/// "shaders/custom_material.wgsl".into()
|
|
/// }
|
|
/// }
|
|
///
|
|
/// // Spawn an entity using `CustomMaterial`.
|
|
/// fn setup(mut commands: Commands, mut materials: ResMut<Assets<CustomMaterial>>, asset_server: Res<AssetServer>) {
|
|
/// commands.spawn(MaterialMesh2dBundle {
|
|
/// material: materials.add(CustomMaterial {
|
|
/// color: Color::RED,
|
|
/// color_texture: asset_server.load("some_image.png"),
|
|
/// }),
|
|
/// ..Default::default()
|
|
/// });
|
|
/// }
|
|
/// ```
|
|
/// In WGSL shaders, the material's binding would look like this:
|
|
///
|
|
/// ```wgsl
|
|
/// struct CustomMaterial {
|
|
/// color: vec4<f32>,
|
|
/// }
|
|
///
|
|
/// @group(1) @binding(0) var<uniform> material: CustomMaterial;
|
|
/// @group(1) @binding(1) var color_texture: texture_2d<f32>;
|
|
/// @group(1) @binding(2) var color_sampler: sampler;
|
|
/// ```
|
|
pub trait Material2d: AsBindGroup + Asset + Clone + Sized {
|
|
/// Returns this material's vertex shader. If [`ShaderRef::Default`] is returned, the default mesh vertex shader
|
|
/// will be used.
|
|
fn vertex_shader() -> ShaderRef {
|
|
ShaderRef::Default
|
|
}
|
|
|
|
/// Returns this material's fragment shader. If [`ShaderRef::Default`] is returned, the default mesh fragment shader
|
|
/// will be used.
|
|
fn fragment_shader() -> ShaderRef {
|
|
ShaderRef::Default
|
|
}
|
|
|
|
/// Customizes the default [`RenderPipelineDescriptor`].
|
|
#[allow(unused_variables)]
|
|
#[inline]
|
|
fn specialize(
|
|
descriptor: &mut RenderPipelineDescriptor,
|
|
layout: &MeshVertexBufferLayout,
|
|
key: Material2dKey<Self>,
|
|
) -> Result<(), SpecializedMeshPipelineError> {
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// Adds the necessary ECS resources and render logic to enable rendering entities using the given [`Material2d`]
|
|
/// asset type (which includes [`Material2d`] types).
|
|
pub struct Material2dPlugin<M: Material2d>(PhantomData<M>);
|
|
|
|
impl<M: Material2d> Default for Material2dPlugin<M> {
|
|
fn default() -> Self {
|
|
Self(Default::default())
|
|
}
|
|
}
|
|
|
|
impl<M: Material2d> Plugin for Material2dPlugin<M>
|
|
where
|
|
M::Data: PartialEq + Eq + Hash + Clone,
|
|
{
|
|
fn build(&self, app: &mut App) {
|
|
app.init_asset::<M>();
|
|
|
|
if let Ok(render_app) = app.get_sub_app_mut(RenderApp) {
|
|
render_app
|
|
.add_render_command::<Transparent2d, DrawMaterial2d<M>>()
|
|
.init_resource::<ExtractedMaterials2d<M>>()
|
|
.init_resource::<RenderMaterials2d<M>>()
|
|
.init_resource::<SpecializedMeshPipelines<Material2dPipeline<M>>>()
|
|
.add_systems(
|
|
ExtractSchedule,
|
|
(extract_materials_2d::<M>, extract_material_meshes_2d::<M>),
|
|
)
|
|
.add_systems(
|
|
Render,
|
|
(
|
|
prepare_materials_2d::<M>
|
|
.in_set(RenderSet::PrepareAssets)
|
|
.after(prepare_assets::<Image>),
|
|
queue_material2d_meshes::<M>
|
|
.in_set(RenderSet::QueueMeshes)
|
|
.after(prepare_materials_2d::<M>),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
fn finish(&self, app: &mut App) {
|
|
if let Ok(render_app) = app.get_sub_app_mut(RenderApp) {
|
|
render_app.init_resource::<Material2dPipeline<M>>();
|
|
}
|
|
}
|
|
}
|
|
|
|
fn extract_material_meshes_2d<M: Material2d>(
|
|
mut commands: Commands,
|
|
mut previous_len: Local<usize>,
|
|
query: Extract<Query<(Entity, &ViewVisibility, &Handle<M>)>>,
|
|
) {
|
|
let mut values = Vec::with_capacity(*previous_len);
|
|
for (entity, view_visibility, material) in &query {
|
|
if view_visibility.get() {
|
|
// NOTE: Material2dBindGroupId is inserted here to avoid a table move. Upcoming changes
|
|
// to use SparseSet for render world entity storage will do this automatically.
|
|
values.push((
|
|
entity,
|
|
(material.clone_weak(), Material2dBindGroupId::default()),
|
|
));
|
|
}
|
|
}
|
|
*previous_len = values.len();
|
|
commands.insert_or_spawn_batch(values);
|
|
}
|
|
|
|
/// Render pipeline data for a given [`Material2d`]
|
|
#[derive(Resource)]
|
|
pub struct Material2dPipeline<M: Material2d> {
|
|
pub mesh2d_pipeline: Mesh2dPipeline,
|
|
pub material2d_layout: BindGroupLayout,
|
|
pub vertex_shader: Option<Handle<Shader>>,
|
|
pub fragment_shader: Option<Handle<Shader>>,
|
|
marker: PhantomData<M>,
|
|
}
|
|
|
|
pub struct Material2dKey<M: Material2d> {
|
|
pub mesh_key: Mesh2dPipelineKey,
|
|
pub bind_group_data: M::Data,
|
|
}
|
|
|
|
impl<M: Material2d> Eq for Material2dKey<M> where M::Data: PartialEq {}
|
|
|
|
impl<M: Material2d> PartialEq for Material2dKey<M>
|
|
where
|
|
M::Data: PartialEq,
|
|
{
|
|
fn eq(&self, other: &Self) -> bool {
|
|
self.mesh_key == other.mesh_key && self.bind_group_data == other.bind_group_data
|
|
}
|
|
}
|
|
|
|
impl<M: Material2d> Clone for Material2dKey<M>
|
|
where
|
|
M::Data: Clone,
|
|
{
|
|
fn clone(&self) -> Self {
|
|
Self {
|
|
mesh_key: self.mesh_key,
|
|
bind_group_data: self.bind_group_data.clone(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<M: Material2d> Hash for Material2dKey<M>
|
|
where
|
|
M::Data: Hash,
|
|
{
|
|
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
|
self.mesh_key.hash(state);
|
|
self.bind_group_data.hash(state);
|
|
}
|
|
}
|
|
|
|
impl<M: Material2d> Clone for Material2dPipeline<M> {
|
|
fn clone(&self) -> Self {
|
|
Self {
|
|
mesh2d_pipeline: self.mesh2d_pipeline.clone(),
|
|
material2d_layout: self.material2d_layout.clone(),
|
|
vertex_shader: self.vertex_shader.clone(),
|
|
fragment_shader: self.fragment_shader.clone(),
|
|
marker: PhantomData,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<M: Material2d> SpecializedMeshPipeline for Material2dPipeline<M>
|
|
where
|
|
M::Data: PartialEq + Eq + Hash + Clone,
|
|
{
|
|
type Key = Material2dKey<M>;
|
|
|
|
fn specialize(
|
|
&self,
|
|
key: Self::Key,
|
|
layout: &MeshVertexBufferLayout,
|
|
) -> Result<RenderPipelineDescriptor, SpecializedMeshPipelineError> {
|
|
let mut descriptor = self.mesh2d_pipeline.specialize(key.mesh_key, layout)?;
|
|
if let Some(vertex_shader) = &self.vertex_shader {
|
|
descriptor.vertex.shader = vertex_shader.clone();
|
|
}
|
|
|
|
if let Some(fragment_shader) = &self.fragment_shader {
|
|
descriptor.fragment.as_mut().unwrap().shader = fragment_shader.clone();
|
|
}
|
|
descriptor.layout = vec![
|
|
self.mesh2d_pipeline.view_layout.clone(),
|
|
self.material2d_layout.clone(),
|
|
self.mesh2d_pipeline.mesh_layout.clone(),
|
|
];
|
|
|
|
M::specialize(&mut descriptor, layout, key)?;
|
|
Ok(descriptor)
|
|
}
|
|
}
|
|
|
|
impl<M: Material2d> FromWorld for Material2dPipeline<M> {
|
|
fn from_world(world: &mut World) -> Self {
|
|
let asset_server = world.resource::<AssetServer>();
|
|
let render_device = world.resource::<RenderDevice>();
|
|
let material2d_layout = M::bind_group_layout(render_device);
|
|
|
|
Material2dPipeline {
|
|
mesh2d_pipeline: world.resource::<Mesh2dPipeline>().clone(),
|
|
material2d_layout,
|
|
vertex_shader: match M::vertex_shader() {
|
|
ShaderRef::Default => None,
|
|
ShaderRef::Handle(handle) => Some(handle),
|
|
ShaderRef::Path(path) => Some(asset_server.load(path)),
|
|
},
|
|
fragment_shader: match M::fragment_shader() {
|
|
ShaderRef::Default => None,
|
|
ShaderRef::Handle(handle) => Some(handle),
|
|
ShaderRef::Path(path) => Some(asset_server.load(path)),
|
|
},
|
|
marker: PhantomData,
|
|
}
|
|
}
|
|
}
|
|
|
|
type DrawMaterial2d<M> = (
|
|
SetItemPipeline,
|
|
SetMesh2dViewBindGroup<0>,
|
|
SetMaterial2dBindGroup<M, 1>,
|
|
SetMesh2dBindGroup<2>,
|
|
DrawMesh2d,
|
|
);
|
|
|
|
pub struct SetMaterial2dBindGroup<M: Material2d, const I: usize>(PhantomData<M>);
|
|
impl<P: PhaseItem, M: Material2d, const I: usize> RenderCommand<P>
|
|
for SetMaterial2dBindGroup<M, I>
|
|
{
|
|
type Param = SRes<RenderMaterials2d<M>>;
|
|
type ViewWorldQuery = ();
|
|
type ItemWorldQuery = Read<Handle<M>>;
|
|
|
|
#[inline]
|
|
fn render<'w>(
|
|
_item: &P,
|
|
_view: (),
|
|
material2d_handle: ROQueryItem<'_, Self::ItemWorldQuery>,
|
|
materials: SystemParamItem<'w, '_, Self::Param>,
|
|
pass: &mut TrackedRenderPass<'w>,
|
|
) -> RenderCommandResult {
|
|
let material2d = materials.into_inner().get(&material2d_handle.id()).unwrap();
|
|
pass.set_bind_group(I, &material2d.bind_group, &[]);
|
|
RenderCommandResult::Success
|
|
}
|
|
}
|
|
|
|
const fn tonemapping_pipeline_key(tonemapping: Tonemapping) -> Mesh2dPipelineKey {
|
|
match tonemapping {
|
|
Tonemapping::None => Mesh2dPipelineKey::TONEMAP_METHOD_NONE,
|
|
Tonemapping::Reinhard => Mesh2dPipelineKey::TONEMAP_METHOD_REINHARD,
|
|
Tonemapping::ReinhardLuminance => Mesh2dPipelineKey::TONEMAP_METHOD_REINHARD_LUMINANCE,
|
|
Tonemapping::AcesFitted => Mesh2dPipelineKey::TONEMAP_METHOD_ACES_FITTED,
|
|
Tonemapping::AgX => Mesh2dPipelineKey::TONEMAP_METHOD_AGX,
|
|
Tonemapping::SomewhatBoringDisplayTransform => {
|
|
Mesh2dPipelineKey::TONEMAP_METHOD_SOMEWHAT_BORING_DISPLAY_TRANSFORM
|
|
}
|
|
Tonemapping::TonyMcMapface => Mesh2dPipelineKey::TONEMAP_METHOD_TONY_MC_MAPFACE,
|
|
Tonemapping::BlenderFilmic => Mesh2dPipelineKey::TONEMAP_METHOD_BLENDER_FILMIC,
|
|
}
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
pub fn queue_material2d_meshes<M: Material2d>(
|
|
transparent_draw_functions: Res<DrawFunctions<Transparent2d>>,
|
|
material2d_pipeline: Res<Material2dPipeline<M>>,
|
|
mut pipelines: ResMut<SpecializedMeshPipelines<Material2dPipeline<M>>>,
|
|
pipeline_cache: Res<PipelineCache>,
|
|
msaa: Res<Msaa>,
|
|
render_meshes: Res<RenderAssets<Mesh>>,
|
|
render_materials: Res<RenderMaterials2d<M>>,
|
|
mut material2d_meshes: Query<(
|
|
&Handle<M>,
|
|
&mut Material2dBindGroupId,
|
|
&Mesh2dHandle,
|
|
&Mesh2dTransforms,
|
|
)>,
|
|
mut views: Query<(
|
|
&ExtractedView,
|
|
&VisibleEntities,
|
|
Option<&Tonemapping>,
|
|
Option<&DebandDither>,
|
|
&mut RenderPhase<Transparent2d>,
|
|
)>,
|
|
) where
|
|
M::Data: PartialEq + Eq + Hash + Clone,
|
|
{
|
|
if material2d_meshes.is_empty() {
|
|
return;
|
|
}
|
|
|
|
for (view, visible_entities, tonemapping, dither, mut transparent_phase) in &mut views {
|
|
let draw_transparent_pbr = transparent_draw_functions.read().id::<DrawMaterial2d<M>>();
|
|
|
|
let mut view_key = Mesh2dPipelineKey::from_msaa_samples(msaa.samples())
|
|
| Mesh2dPipelineKey::from_hdr(view.hdr);
|
|
|
|
if !view.hdr {
|
|
if let Some(tonemapping) = tonemapping {
|
|
view_key |= Mesh2dPipelineKey::TONEMAP_IN_SHADER;
|
|
view_key |= tonemapping_pipeline_key(*tonemapping);
|
|
}
|
|
if let Some(DebandDither::Enabled) = dither {
|
|
view_key |= Mesh2dPipelineKey::DEBAND_DITHER;
|
|
}
|
|
}
|
|
for visible_entity in &visible_entities.entities {
|
|
let Ok((
|
|
material2d_handle,
|
|
mut material2d_bind_group_id,
|
|
mesh2d_handle,
|
|
mesh2d_uniform,
|
|
)) = material2d_meshes.get_mut(*visible_entity)
|
|
else {
|
|
continue;
|
|
};
|
|
let Some(material2d) = render_materials.get(&material2d_handle.id()) else {
|
|
continue;
|
|
};
|
|
let Some(mesh) = render_meshes.get(&mesh2d_handle.0) else {
|
|
continue;
|
|
};
|
|
let mesh_key =
|
|
view_key | Mesh2dPipelineKey::from_primitive_topology(mesh.primitive_topology);
|
|
|
|
let pipeline_id = pipelines.specialize(
|
|
&pipeline_cache,
|
|
&material2d_pipeline,
|
|
Material2dKey {
|
|
mesh_key,
|
|
bind_group_data: material2d.key.clone(),
|
|
},
|
|
&mesh.layout,
|
|
);
|
|
|
|
let pipeline_id = match pipeline_id {
|
|
Ok(id) => id,
|
|
Err(err) => {
|
|
error!("{}", err);
|
|
continue;
|
|
}
|
|
};
|
|
|
|
*material2d_bind_group_id = material2d.get_bind_group_id();
|
|
let mesh_z = mesh2d_uniform.transform.translation.z;
|
|
transparent_phase.add(Transparent2d {
|
|
entity: *visible_entity,
|
|
draw_function: draw_transparent_pbr,
|
|
pipeline: pipeline_id,
|
|
// NOTE: Back-to-front ordering for transparent with ascending sort means far should have the
|
|
// lowest sort key and getting closer should increase. As we have
|
|
// -z in front of the camera, the largest distance is -far with values increasing toward the
|
|
// camera. As such we can just use mesh_z as the distance
|
|
sort_key: FloatOrd(mesh_z),
|
|
// Batching is done in batch_and_prepare_render_phase
|
|
batch_range: 0..1,
|
|
dynamic_offset: None,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Component, Clone, Copy, Default, PartialEq, Eq, Deref, DerefMut)]
|
|
pub struct Material2dBindGroupId(Option<BindGroupId>);
|
|
|
|
/// Data prepared for a [`Material2d`] instance.
|
|
pub struct PreparedMaterial2d<T: Material2d> {
|
|
pub bindings: Vec<OwnedBindingResource>,
|
|
pub bind_group: BindGroup,
|
|
pub key: T::Data,
|
|
}
|
|
|
|
impl<T: Material2d> PreparedMaterial2d<T> {
|
|
pub fn get_bind_group_id(&self) -> Material2dBindGroupId {
|
|
Material2dBindGroupId(Some(self.bind_group.id()))
|
|
}
|
|
}
|
|
|
|
#[derive(Resource)]
|
|
pub struct ExtractedMaterials2d<M: Material2d> {
|
|
extracted: Vec<(AssetId<M>, M)>,
|
|
removed: Vec<AssetId<M>>,
|
|
}
|
|
|
|
impl<M: Material2d> Default for ExtractedMaterials2d<M> {
|
|
fn default() -> Self {
|
|
Self {
|
|
extracted: Default::default(),
|
|
removed: Default::default(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Stores all prepared representations of [`Material2d`] assets for as long as they exist.
|
|
#[derive(Resource, Deref, DerefMut)]
|
|
pub struct RenderMaterials2d<T: Material2d>(HashMap<AssetId<T>, PreparedMaterial2d<T>>);
|
|
|
|
impl<T: Material2d> Default for RenderMaterials2d<T> {
|
|
fn default() -> Self {
|
|
Self(Default::default())
|
|
}
|
|
}
|
|
|
|
/// This system extracts all created or modified assets of the corresponding [`Material2d`] type
|
|
/// into the "render world".
|
|
pub fn extract_materials_2d<M: Material2d>(
|
|
mut commands: Commands,
|
|
mut events: Extract<EventReader<AssetEvent<M>>>,
|
|
assets: Extract<Res<Assets<M>>>,
|
|
) {
|
|
let mut changed_assets = HashSet::default();
|
|
let mut removed = Vec::new();
|
|
for event in events.read() {
|
|
match event {
|
|
AssetEvent::Added { id } | AssetEvent::Modified { id } => {
|
|
changed_assets.insert(*id);
|
|
}
|
|
AssetEvent::Removed { id } => {
|
|
changed_assets.remove(id);
|
|
removed.push(*id);
|
|
}
|
|
|
|
AssetEvent::LoadedWithDependencies { .. } => {
|
|
// TODO: handle this
|
|
}
|
|
}
|
|
}
|
|
|
|
let mut extracted_assets = Vec::new();
|
|
for id in changed_assets.drain() {
|
|
if let Some(asset) = assets.get(id) {
|
|
extracted_assets.push((id, asset.clone()));
|
|
}
|
|
}
|
|
|
|
commands.insert_resource(ExtractedMaterials2d {
|
|
extracted: extracted_assets,
|
|
removed,
|
|
});
|
|
}
|
|
|
|
/// All [`Material2d`] values of a given type that should be prepared next frame.
|
|
pub struct PrepareNextFrameMaterials<M: Material2d> {
|
|
assets: Vec<(AssetId<M>, M)>,
|
|
}
|
|
|
|
impl<M: Material2d> Default for PrepareNextFrameMaterials<M> {
|
|
fn default() -> Self {
|
|
Self {
|
|
assets: Default::default(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// This system prepares all assets of the corresponding [`Material2d`] type
|
|
/// which where extracted this frame for the GPU.
|
|
pub fn prepare_materials_2d<M: Material2d>(
|
|
mut prepare_next_frame: Local<PrepareNextFrameMaterials<M>>,
|
|
mut extracted_assets: ResMut<ExtractedMaterials2d<M>>,
|
|
mut render_materials: ResMut<RenderMaterials2d<M>>,
|
|
render_device: Res<RenderDevice>,
|
|
images: Res<RenderAssets<Image>>,
|
|
fallback_image: Res<FallbackImage>,
|
|
pipeline: Res<Material2dPipeline<M>>,
|
|
) {
|
|
let queued_assets = std::mem::take(&mut prepare_next_frame.assets);
|
|
for (id, material) in queued_assets {
|
|
match prepare_material2d(
|
|
&material,
|
|
&render_device,
|
|
&images,
|
|
&fallback_image,
|
|
&pipeline,
|
|
) {
|
|
Ok(prepared_asset) => {
|
|
render_materials.insert(id, prepared_asset);
|
|
}
|
|
Err(AsBindGroupError::RetryNextUpdate) => {
|
|
prepare_next_frame.assets.push((id, material));
|
|
}
|
|
}
|
|
}
|
|
|
|
for removed in std::mem::take(&mut extracted_assets.removed) {
|
|
render_materials.remove(&removed);
|
|
}
|
|
|
|
for (handle, material) in std::mem::take(&mut extracted_assets.extracted) {
|
|
match prepare_material2d(
|
|
&material,
|
|
&render_device,
|
|
&images,
|
|
&fallback_image,
|
|
&pipeline,
|
|
) {
|
|
Ok(prepared_asset) => {
|
|
render_materials.insert(handle, prepared_asset);
|
|
}
|
|
Err(AsBindGroupError::RetryNextUpdate) => {
|
|
prepare_next_frame.assets.push((handle, material));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn prepare_material2d<M: Material2d>(
|
|
material: &M,
|
|
render_device: &RenderDevice,
|
|
images: &RenderAssets<Image>,
|
|
fallback_image: &FallbackImage,
|
|
pipeline: &Material2dPipeline<M>,
|
|
) -> Result<PreparedMaterial2d<M>, AsBindGroupError> {
|
|
let prepared = material.as_bind_group(
|
|
&pipeline.material2d_layout,
|
|
render_device,
|
|
images,
|
|
fallback_image,
|
|
)?;
|
|
Ok(PreparedMaterial2d {
|
|
bindings: prepared.bindings,
|
|
bind_group: prepared.bind_group,
|
|
key: prepared.data,
|
|
})
|
|
}
|
|
|
|
/// A component bundle for entities with a [`Mesh2dHandle`] and a [`Material2d`].
|
|
#[derive(Bundle, Clone)]
|
|
pub struct MaterialMesh2dBundle<M: Material2d> {
|
|
pub mesh: Mesh2dHandle,
|
|
pub material: Handle<M>,
|
|
pub transform: Transform,
|
|
pub global_transform: GlobalTransform,
|
|
/// User indication of whether an entity is visible
|
|
pub visibility: Visibility,
|
|
// Inherited visibility of an entity.
|
|
pub inherited_visibility: InheritedVisibility,
|
|
// Indication of whether an entity is visible in any view.
|
|
pub view_visibility: ViewVisibility,
|
|
}
|
|
|
|
impl<M: Material2d> Default for MaterialMesh2dBundle<M> {
|
|
fn default() -> Self {
|
|
Self {
|
|
mesh: Default::default(),
|
|
material: Default::default(),
|
|
transform: Default::default(),
|
|
global_transform: Default::default(),
|
|
visibility: Default::default(),
|
|
inherited_visibility: Default::default(),
|
|
view_visibility: Default::default(),
|
|
}
|
|
}
|
|
}
|