Skip to content

Commit 41cb513

Browse files
committed
add gpu picking
1 parent 1e73312 commit 41cb513

File tree

15 files changed

+926
-26
lines changed

15 files changed

+926
-26
lines changed

Cargo.toml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1324,6 +1324,16 @@ description = "Shows how to rumble a gamepad using force feedback"
13241324
category = "Input"
13251325
wasm = false
13261326

1327+
[[example]]
1328+
name = "gpu_picking"
1329+
path = "examples/input/gpu_picking.rs"
1330+
1331+
[package.metadata.example.gpu_picking]
1332+
name = "GPU picking"
1333+
description = "Mouse picking using the gpu"
1334+
category = "Input"
1335+
wasm = true
1336+
13271337
[[example]]
13281338
name = "keyboard_input"
13291339
path = "examples/input/keyboard_input.rs"
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// This shader shows how to enable the gpu picking feature for a material
2+
3+
// You'll need the mesh binding because that's where the entity index is
4+
#import bevy_pbr::mesh_bindings
5+
6+
@group(1) @binding(0)
7+
var<uniform> color: vec4<f32>;
8+
9+
// Gpu picking uses multiple fragment output
10+
struct FragmentOutput {
11+
@location(0) color: vec4<f32>,
12+
// You can detect the feature with this flag
13+
#ifdef GPU_PICKING
14+
@location(1) mesh_id: u32,
15+
#endif
16+
};
17+
18+
@fragment
19+
fn fragment(
20+
#import bevy_pbr::mesh_vertex_output
21+
) -> FragmentOutput {
22+
var out: FragmentOutput;
23+
out.color = color;
24+
// make sure to output the entity index for gpu picking to work correctly
25+
#ifdef GPU_PICKING
26+
out.mesh_id = mesh.id;
27+
#endif
28+
return out;
29+
}

crates/bevy_core_pipeline/src/core_3d/main_opaque_pass_3d_node.rs

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use crate::{
77
use bevy_ecs::{prelude::*, query::QueryItem};
88
use bevy_render::{
99
camera::ExtractedCamera,
10+
picking::{ExtractedGpuPickingCamera, VisibleMeshIdTextures},
1011
render_graph::{NodeRunError, RenderGraphContext, ViewNode},
1112
render_phase::RenderPhase,
1213
render_resource::{
@@ -34,8 +35,10 @@ impl ViewNode for MainOpaquePass3dNode {
3435
Option<&'static DepthPrepass>,
3536
Option<&'static NormalPrepass>,
3637
Option<&'static MotionVectorPrepass>,
38+
Option<&'static ExtractedGpuPickingCamera>,
3739
Option<&'static SkyboxPipelineId>,
3840
Option<&'static SkyboxBindGroup>,
41+
Option<&'static VisibleMeshIdTextures>,
3942
&'static ViewUniformOffset,
4043
);
4144

@@ -53,8 +56,10 @@ impl ViewNode for MainOpaquePass3dNode {
5356
depth_prepass,
5457
normal_prepass,
5558
motion_vector_prepass,
59+
gpu_picking_camera,
5660
skybox_pipeline,
5761
skybox_bind_group,
62+
mesh_id_textures,
5863
view_uniform_offset,
5964
): QueryItem<Self::ViewQuery>,
6065
world: &World,
@@ -64,21 +69,34 @@ impl ViewNode for MainOpaquePass3dNode {
6469
#[cfg(feature = "trace")]
6570
let _main_opaque_pass_3d_span = info_span!("main_opaque_pass_3d").entered();
6671

72+
let mut color_attachments = vec![Some(target.get_color_attachment(Operations {
73+
load: match camera_3d.clear_color {
74+
ClearColorConfig::Default => LoadOp::Clear(world.resource::<ClearColor>().0.into()),
75+
ClearColorConfig::Custom(color) => LoadOp::Clear(color.into()),
76+
ClearColorConfig::None => LoadOp::Load,
77+
},
78+
store: true,
79+
}))];
80+
81+
if gpu_picking_camera.is_some() {
82+
if let Some(mesh_id_textures) = mesh_id_textures {
83+
color_attachments.push(Some(mesh_id_textures.get_color_attachment(Operations {
84+
load: match camera_3d.clear_color {
85+
ClearColorConfig::None => LoadOp::Load,
86+
// TODO clear this earlier?
87+
_ => LoadOp::Clear(VisibleMeshIdTextures::clear_color()),
88+
},
89+
store: true,
90+
})));
91+
}
92+
}
93+
6794
// Setup render pass
6895
let mut render_pass = render_context.begin_tracked_render_pass(RenderPassDescriptor {
6996
label: Some("main_opaque_pass_3d"),
7097
// NOTE: The opaque pass loads the color
7198
// buffer as well as writing to it.
72-
color_attachments: &[Some(target.get_color_attachment(Operations {
73-
load: match camera_3d.clear_color {
74-
ClearColorConfig::Default => {
75-
LoadOp::Clear(world.resource::<ClearColor>().0.into())
76-
}
77-
ClearColorConfig::Custom(color) => LoadOp::Clear(color.into()),
78-
ClearColorConfig::None => LoadOp::Load,
79-
},
80-
store: true,
81-
}))],
99+
color_attachments: &color_attachments,
82100
depth_stencil_attachment: Some(RenderPassDepthStencilAttachment {
83101
view: &depth.view,
84102
// NOTE: The opaque main pass loads the depth buffer and possibly overwrites it

crates/bevy_core_pipeline/src/core_3d/main_transparent_pass_3d_node.rs

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use crate::core_3d::Transparent3d;
22
use bevy_ecs::{prelude::*, query::QueryItem};
33
use bevy_render::{
44
camera::ExtractedCamera,
5+
picking::{ExtractedGpuPickingCamera, VisibleMeshIdTextures},
56
render_graph::{NodeRunError, RenderGraphContext, ViewNode},
67
render_phase::RenderPhase,
78
render_resource::{LoadOp, Operations, RenderPassDepthStencilAttachment, RenderPassDescriptor},
@@ -21,12 +22,16 @@ impl ViewNode for MainTransparentPass3dNode {
2122
&'static RenderPhase<Transparent3d>,
2223
&'static ViewTarget,
2324
&'static ViewDepthTexture,
25+
Option<&'static ExtractedGpuPickingCamera>,
26+
Option<&'static VisibleMeshIdTextures>,
2427
);
2528
fn run(
2629
&self,
2730
graph: &mut RenderGraphContext,
2831
render_context: &mut RenderContext,
29-
(camera, transparent_phase, target, depth): QueryItem<Self::ViewQuery>,
32+
(camera, transparent_phase, target, depth, gpu_picking_camera, mesh_id_textures): QueryItem<
33+
Self::ViewQuery,
34+
>,
3035
world: &World,
3136
) -> Result<(), NodeRunError> {
3237
let view_entity = graph.view_entity();
@@ -37,13 +42,27 @@ impl ViewNode for MainTransparentPass3dNode {
3742
#[cfg(feature = "trace")]
3843
let _main_transparent_pass_3d_span = info_span!("main_transparent_pass_3d").entered();
3944

45+
let mut color_attachments = vec![Some(target.get_color_attachment(Operations {
46+
load: LoadOp::Load,
47+
store: true,
48+
}))];
49+
50+
if gpu_picking_camera.is_some() {
51+
if let Some(mesh_id_textures) = mesh_id_textures {
52+
color_attachments.push(Some(mesh_id_textures.get_color_attachment(
53+
Operations {
54+
// The texture is already cleared in the opaque pass
55+
load: LoadOp::Load,
56+
store: true,
57+
},
58+
)));
59+
}
60+
}
61+
4062
let mut render_pass = render_context.begin_tracked_render_pass(RenderPassDescriptor {
4163
label: Some("main_transparent_pass_3d"),
4264
// NOTE: The transparent pass loads the color buffer as well as overwriting it where appropriate.
43-
color_attachments: &[Some(target.get_color_attachment(Operations {
44-
load: LoadOp::Load,
45-
store: true,
46-
}))],
65+
color_attachments: &color_attachments,
4766
depth_stencil_attachment: Some(RenderPassDepthStencilAttachment {
4867
view: &depth.view,
4968
// NOTE: For the transparent pass we load the depth buffer. There should be no

crates/bevy_core_pipeline/src/core_3d/mod.rs

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ pub mod graph {
1414
pub const MAIN_OPAQUE_PASS: &str = "main_opaque_pass";
1515
pub const MAIN_TRANSPARENT_PASS: &str = "main_transparent_pass";
1616
pub const END_MAIN_PASS: &str = "end_main_pass";
17+
pub const ENTITY_INDEX_BUFFER_COPY: &str = "entity_index_buffer_copy";
1718
pub const BLOOM: &str = "bloom";
1819
pub const TONEMAPPING: &str = "tonemapping";
1920
pub const FXAA: &str = "fxaa";
@@ -35,6 +36,7 @@ use bevy_ecs::prelude::*;
3536
use bevy_render::{
3637
camera::{Camera, ExtractedCamera},
3738
extract_component::ExtractComponentPlugin,
39+
picking::{ExtractedGpuPickingCamera, VisibleMeshIdTextures, MESH_ID_TEXTURE_FORMAT},
3840
prelude::Msaa,
3941
render_graph::{EmptyNode, RenderGraphApp, ViewNodeRunner},
4042
render_phase::{
@@ -93,6 +95,9 @@ impl Plugin for Core3dPlugin {
9395
prepare_prepass_textures
9496
.in_set(RenderSet::Prepare)
9597
.after(bevy_render::view::prepare_windows),
98+
prepare_entity_textures
99+
.in_set(RenderSet::Prepare)
100+
.after(bevy_render::view::prepare_windows),
96101
sort_phase_system::<Opaque3d>.in_set(RenderSet::PhaseSort),
97102
sort_phase_system::<AlphaMask3d>.in_set(RenderSet::PhaseSort),
98103
sort_phase_system::<Transparent3d>.in_set(RenderSet::PhaseSort),
@@ -479,3 +484,63 @@ pub fn prepare_prepass_textures(
479484
});
480485
}
481486
}
487+
488+
/// Create the required textures based on the camera size
489+
pub fn prepare_entity_textures(
490+
mut commands: Commands,
491+
mut texture_cache: ResMut<TextureCache>,
492+
msaa: Res<Msaa>,
493+
render_device: Res<RenderDevice>,
494+
views_3d: Query<
495+
(Entity, &ExtractedCamera, Option<&ExtractedGpuPickingCamera>),
496+
(With<RenderPhase<Opaque3d>>, With<RenderPhase<AlphaMask3d>>),
497+
>,
498+
) {
499+
for (entity, camera, gpu_picking_camera) in &views_3d {
500+
if gpu_picking_camera.is_none() {
501+
continue;
502+
}
503+
504+
let Some(physical_target_size) = camera.physical_target_size else {
505+
continue;
506+
};
507+
508+
let size = Extent3d {
509+
depth_or_array_layers: 1,
510+
width: physical_target_size.x,
511+
height: physical_target_size.y,
512+
};
513+
514+
let descriptor = TextureDescriptor {
515+
label: None,
516+
size,
517+
mip_level_count: 1,
518+
sample_count: 1,
519+
dimension: TextureDimension::D2,
520+
format: MESH_ID_TEXTURE_FORMAT,
521+
usage: TextureUsages::RENDER_ATTACHMENT | TextureUsages::COPY_SRC,
522+
view_formats: &[],
523+
};
524+
525+
let mesh_id_textures = VisibleMeshIdTextures {
526+
main: texture_cache.get(
527+
&render_device,
528+
TextureDescriptor {
529+
label: Some("main_entity_texture"),
530+
..descriptor
531+
},
532+
),
533+
sampled: (msaa.samples() > 1).then(|| {
534+
texture_cache.get(
535+
&render_device,
536+
TextureDescriptor {
537+
label: Some("main_entity_texture_sampled"),
538+
sample_count: msaa.samples(),
539+
..descriptor
540+
},
541+
)
542+
}),
543+
};
544+
commands.entity(entity).insert(mesh_id_textures);
545+
}
546+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
use bevy_app::Plugin;
2+
use bevy_ecs::{query::QueryItem, world::World};
3+
use bevy_render::{
4+
picking::{CurrentBufferIndex, ExtractedGpuPickingCamera, VisibleMeshIdTextures},
5+
render_graph::{RenderGraphApp, RenderGraphContext, ViewNode, ViewNodeRunner},
6+
renderer::RenderContext,
7+
RenderApp,
8+
};
9+
10+
use crate::core_3d::CORE_3D;
11+
12+
#[derive(Default)]
13+
pub struct EntityIndexBufferCopyNode;
14+
impl ViewNode for EntityIndexBufferCopyNode {
15+
type ViewQuery = (
16+
&'static VisibleMeshIdTextures,
17+
&'static ExtractedGpuPickingCamera,
18+
);
19+
20+
fn run(
21+
&self,
22+
_graph: &mut RenderGraphContext,
23+
render_context: &mut RenderContext,
24+
(mesh_id_textures, gpu_picking_camera): QueryItem<Self::ViewQuery>,
25+
world: &World,
26+
) -> Result<(), bevy_render::render_graph::NodeRunError> {
27+
let current_buffer_index = world.resource::<CurrentBufferIndex>();
28+
gpu_picking_camera.run_node(
29+
render_context.command_encoder(),
30+
&mesh_id_textures.main.texture,
31+
current_buffer_index,
32+
);
33+
Ok(())
34+
}
35+
}
36+
37+
pub struct EntityIndexBufferCopyPlugin;
38+
impl Plugin for EntityIndexBufferCopyPlugin {
39+
fn build(&self, app: &mut bevy_app::App) {
40+
let Ok(render_app) = app.get_sub_app_mut(RenderApp) else { return; };
41+
42+
// 3D
43+
use crate::core_3d::graph::node::*;
44+
render_app
45+
.add_render_graph_node::<ViewNodeRunner<EntityIndexBufferCopyNode>>(
46+
CORE_3D,
47+
ENTITY_INDEX_BUFFER_COPY,
48+
)
49+
.add_render_graph_edge(CORE_3D, UPSCALING, ENTITY_INDEX_BUFFER_COPY);
50+
}
51+
}

crates/bevy_core_pipeline/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ pub mod clear_color;
66
pub mod contrast_adaptive_sharpening;
77
pub mod core_2d;
88
pub mod core_3d;
9+
pub mod entity_index_buffer_copy;
910
pub mod fullscreen_vertex_shader;
1011
pub mod fxaa;
1112
pub mod msaa_writeback;
@@ -40,6 +41,7 @@ use crate::{
4041
contrast_adaptive_sharpening::CASPlugin,
4142
core_2d::Core2dPlugin,
4243
core_3d::Core3dPlugin,
44+
entity_index_buffer_copy::EntityIndexBufferCopyPlugin,
4345
fullscreen_vertex_shader::FULLSCREEN_SHADER_HANDLE,
4446
fxaa::FxaaPlugin,
4547
msaa_writeback::MsaaWritebackPlugin,
@@ -79,6 +81,7 @@ impl Plugin for CorePipelinePlugin {
7981
BloomPlugin,
8082
FxaaPlugin,
8183
CASPlugin,
84+
EntityIndexBufferCopyPlugin,
8285
));
8386
}
8487
}

0 commit comments

Comments
 (0)