mirror of
https://github.com/bevyengine/bevy
synced 2024-11-23 05:03:47 +00:00
c5963b4fd5
# Objective - Make use of storage buffers, where they are available, for clustered forward bindings to support far more point lights in a scene - Fixes #3605 - Based on top of #4079 This branch on an M1 Max can keep 60fps with about 2150 point lights of radius 1m in the Sponza scene where I've been testing. The bottleneck is mostly assigning lights to clusters which grows faster than linearly (I think 1000 lights was about 1.5ms and 5000 was 7.5ms). I have seen papers and presentations leveraging compute shaders that can get this up to over 1 million. That said, I think any further optimisations should probably be done in a separate PR. ## Solution - Add `RenderDevice` to the `Material` and `SpecializedMaterial` trait `::key()` functions to allow setting flags on the keys depending on feature/limit availability - Make `GpuPointLights` and `ViewClusterBuffers` into enums containing `UniformVec` and `StorageBuffer` variants. Implement the necessary API on them to make usage the same for both cases, and the only difference is at initialisation time. - Appropriate shader defs in the shader code to handle the two cases ## Context on some decisions / open questions - I'm using `max_storage_buffers_per_shader_stage >= 3` as a check to see if storage buffers are supported. I was thinking about diving into 'binding resource management' but it feels like we don't have enough use cases to understand the problem yet, and it is mostly a separate concern to this PR, so I think it should be handled separately. - Should `ViewClusterBuffers` and `ViewClusterBindings` be merged, duplicating the count variables into the enum variants? Co-authored-by: Carter Anderson <mcanders1@gmail.com>
137 lines
4.2 KiB
Rust
137 lines
4.2 KiB
Rust
use bevy::{
|
|
ecs::system::{lifetimeless::SRes, SystemParamItem},
|
|
pbr::{MaterialPipeline, SpecializedMaterial},
|
|
prelude::*,
|
|
reflect::TypeUuid,
|
|
render::{
|
|
mesh::MeshVertexBufferLayout,
|
|
render_asset::{PrepareAssetError, RenderAsset},
|
|
render_resource::{
|
|
std140::{AsStd140, Std140},
|
|
*,
|
|
},
|
|
renderer::RenderDevice,
|
|
},
|
|
};
|
|
|
|
fn main() {
|
|
App::new()
|
|
.add_plugins(DefaultPlugins)
|
|
.add_plugin(MaterialPlugin::<CustomMaterial>::default())
|
|
.add_startup_system(setup)
|
|
.run();
|
|
}
|
|
|
|
/// set up a simple 3D scene
|
|
fn setup(
|
|
mut commands: Commands,
|
|
mut meshes: ResMut<Assets<Mesh>>,
|
|
mut materials: ResMut<Assets<CustomMaterial>>,
|
|
) {
|
|
// cube
|
|
commands.spawn().insert_bundle(MaterialMeshBundle {
|
|
mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
|
|
transform: Transform::from_xyz(0.0, 0.5, 0.0),
|
|
material: materials.add(CustomMaterial {
|
|
color: Color::GREEN,
|
|
}),
|
|
..default()
|
|
});
|
|
|
|
// camera
|
|
commands.spawn_bundle(PerspectiveCameraBundle {
|
|
transform: Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
|
|
..default()
|
|
});
|
|
}
|
|
|
|
#[derive(Debug, Clone, TypeUuid)]
|
|
#[uuid = "4ee9c363-1124-4113-890e-199d81b00281"]
|
|
pub struct CustomMaterial {
|
|
color: Color,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct GpuCustomMaterial {
|
|
_buffer: Buffer,
|
|
bind_group: BindGroup,
|
|
}
|
|
|
|
impl RenderAsset for CustomMaterial {
|
|
type ExtractedAsset = CustomMaterial;
|
|
type PreparedAsset = GpuCustomMaterial;
|
|
type Param = (SRes<RenderDevice>, SRes<MaterialPipeline<Self>>);
|
|
fn extract_asset(&self) -> Self::ExtractedAsset {
|
|
self.clone()
|
|
}
|
|
|
|
fn prepare_asset(
|
|
extracted_asset: Self::ExtractedAsset,
|
|
(render_device, material_pipeline): &mut SystemParamItem<Self::Param>,
|
|
) -> Result<Self::PreparedAsset, PrepareAssetError<Self::ExtractedAsset>> {
|
|
let color = Vec4::from_slice(&extracted_asset.color.as_linear_rgba_f32());
|
|
let buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
|
|
contents: color.as_std140().as_bytes(),
|
|
label: None,
|
|
usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
|
|
});
|
|
let bind_group = render_device.create_bind_group(&BindGroupDescriptor {
|
|
entries: &[BindGroupEntry {
|
|
binding: 0,
|
|
resource: buffer.as_entire_binding(),
|
|
}],
|
|
label: None,
|
|
layout: &material_pipeline.material_layout,
|
|
});
|
|
|
|
Ok(GpuCustomMaterial {
|
|
_buffer: buffer,
|
|
bind_group,
|
|
})
|
|
}
|
|
}
|
|
|
|
impl SpecializedMaterial for CustomMaterial {
|
|
type Key = ();
|
|
|
|
fn key(_: &<CustomMaterial as RenderAsset>::PreparedAsset) -> Self::Key {}
|
|
|
|
fn specialize(
|
|
_pipeline: &MaterialPipeline<Self>,
|
|
descriptor: &mut RenderPipelineDescriptor,
|
|
_: Self::Key,
|
|
_layout: &MeshVertexBufferLayout,
|
|
) -> Result<(), SpecializedMeshPipelineError> {
|
|
descriptor.vertex.entry_point = "main".into();
|
|
descriptor.fragment.as_mut().unwrap().entry_point = "main".into();
|
|
Ok(())
|
|
}
|
|
|
|
fn vertex_shader(asset_server: &AssetServer) -> Option<Handle<Shader>> {
|
|
Some(asset_server.load("shaders/custom_material.vert"))
|
|
}
|
|
|
|
fn fragment_shader(asset_server: &AssetServer) -> Option<Handle<Shader>> {
|
|
Some(asset_server.load("shaders/custom_material.frag"))
|
|
}
|
|
|
|
fn bind_group(render_asset: &<Self as RenderAsset>::PreparedAsset) -> &BindGroup {
|
|
&render_asset.bind_group
|
|
}
|
|
|
|
fn bind_group_layout(render_device: &RenderDevice) -> BindGroupLayout {
|
|
render_device.create_bind_group_layout(&BindGroupLayoutDescriptor {
|
|
entries: &[BindGroupLayoutEntry {
|
|
binding: 0,
|
|
visibility: ShaderStages::FRAGMENT,
|
|
ty: BindingType::Buffer {
|
|
ty: BufferBindingType::Uniform,
|
|
has_dynamic_offset: false,
|
|
min_binding_size: BufferSize::new(Vec4::std140_size_static() as u64),
|
|
},
|
|
count: None,
|
|
}],
|
|
label: None,
|
|
})
|
|
}
|
|
}
|