From 9e744954f78edd4565e3ffaf808df51d9396f049 Mon Sep 17 00:00:00 2001 From: Vecvec Date: Fri, 6 Nov 2026 08:20:32 +1300 Subject: [PATCH] [wgpu-core] Ray tracing pipelines (#10144) Co-authored-by: Connor Fitzgerald --- examples/features/src/ray_aabb_compute/mod.rs | 1 + examples/features/src/ray_cube_compute/mod.rs | 1 + .../features/src/ray_cube_fragment/mod.rs | 2 +- examples/features/src/ray_cube_normals/mod.rs | 1 + examples/features/src/ray_scene/mod.rs | 1 + examples/features/src/ray_shadows/mod.rs | 1 + .../features/src/ray_traced_triangle/mod.rs | 3 + .../standalone/custom_backend/src/custom.rs | 7 + naga/src/compact/mod.rs | 8 + player/src/lib.rs | 141 +++ tests/tests/wgpu-gpu/binding_array/tlas.rs | 2 + tests/tests/wgpu-gpu/ray_tracing/as_aabb.rs | 1 + tests/tests/wgpu-gpu/ray_tracing/as_build.rs | 1 + .../wgpu-gpu/ray_tracing/as_use_after_free.rs | 1 + tests/tests/wgpu-gpu/ray_tracing/mod.rs | 3 + tests/tests/wgpu-gpu/ray_tracing/pipelines.rs | 1047 +++++++++++++++++ tests/tests/wgpu-gpu/ray_tracing/scene/mod.rs | 1 + wgpu-core-remote-types/src/id.rs | 1 + wgpu-core-remote/src/id.rs | 1 + wgpu-core/src/binding_model.rs | 52 +- wgpu-core/src/command/encoder_command.rs | 7 + wgpu-core/src/command/mod.rs | 39 +- wgpu-core/src/command/pass.rs | 2 +- wgpu-core/src/command/ray_tracing.rs | 125 +- wgpu-core/src/command/ray_tracing_pass.rs | 992 ++++++++++++++++ .../src/command/ray_tracing_pass_commands.rs | 47 + wgpu-core/src/device/queue.rs | 19 +- wgpu-core/src/device/ray_tracing.rs | 278 ++++- wgpu-core/src/device/resource.rs | 13 +- wgpu-core/src/device/trace.rs | 22 + wgpu-core/src/device/trace/record.rs | 99 +- wgpu-core/src/lib.rs | 1 + wgpu-core/src/lock/rank.rs | 4 + wgpu-core/src/pipeline.rs | 4 + wgpu-core/src/ray_tracing.rs | 54 +- wgpu-core/src/ray_tracing_pipeline.rs | 369 ++++++ wgpu-core/src/resource.rs | 15 + wgpu-core/src/track/mod.rs | 6 +- wgpu-core/src/validation.rs | 160 ++- wgpu-hal/src/vulkan/adapter.rs | 1 + wgpu-hal/src/vulkan/conv.rs | 4 + wgpu-hal/src/vulkan/device.rs | 9 + wgpu-hal/src/vulkan/mod.rs | 4 + wgpu-types/src/limits.rs | 4 - wgpu-types/src/markers.rs | 2 + wgpu/src/api/blas.rs | 17 +- wgpu/src/api/command_encoder.rs | 22 + wgpu/src/api/compute_pipeline.rs | 1 + wgpu/src/api/device.rs | 11 + wgpu/src/api/mod.rs | 4 + wgpu/src/api/ray_tracing_pass.rs | 112 ++ wgpu/src/api/ray_tracing_pipeline.rs | 143 +++ wgpu/src/api/render_pipeline.rs | 1 + wgpu/src/backend/custom.rs | 2 + wgpu/src/backend/webgpu.rs | 78 ++ wgpu/src/backend/wgpu_core.rs | 179 +++ wgpu/src/dispatch.rs | 29 + 57 files changed, 4106 insertions(+), 49 deletions(-) create mode 100644 tests/tests/wgpu-gpu/ray_tracing/pipelines.rs create mode 100644 wgpu-core/src/command/ray_tracing_pass.rs create mode 100644 wgpu-core/src/command/ray_tracing_pass_commands.rs create mode 100644 wgpu-core/src/ray_tracing_pipeline.rs create mode 100644 wgpu/src/api/ray_tracing_pass.rs create mode 100644 wgpu/src/api/ray_tracing_pipeline.rs diff --git a/examples/features/src/ray_aabb_compute/mod.rs b/examples/features/src/ray_aabb_compute/mod.rs index fd028ddff..fbe9f1665 100644 --- a/examples/features/src/ray_aabb_compute/mod.rs +++ b/examples/features/src/ray_aabb_compute/mod.rs @@ -292,6 +292,7 @@ impl crate::framework::Example for Example { )), 0, 0xff, + 0, )); let mut encoder = diff --git a/examples/features/src/ray_cube_compute/mod.rs b/examples/features/src/ray_cube_compute/mod.rs index ee4223060..d9f55679a 100644 --- a/examples/features/src/ray_cube_compute/mod.rs +++ b/examples/features/src/ray_cube_compute/mod.rs @@ -343,6 +343,7 @@ impl crate::framework::Example for Example { )), 0, 0xff, + 0, )); } } diff --git a/examples/features/src/ray_cube_fragment/mod.rs b/examples/features/src/ray_cube_fragment/mod.rs index 8debb7e5a..1da244ccf 100644 --- a/examples/features/src/ray_cube_fragment/mod.rs +++ b/examples/features/src/ray_cube_fragment/mod.rs @@ -307,7 +307,7 @@ impl crate::framework::Example for Example { .try_into() .unwrap(); - *instance = Some(wgpu::TlasInstance::new(&self.blas, transform, 0, 0xff)); + *instance = Some(wgpu::TlasInstance::new(&self.blas, transform, 0, 0xff, 0)); } } } diff --git a/examples/features/src/ray_cube_normals/mod.rs b/examples/features/src/ray_cube_normals/mod.rs index 4d3173438..630606106 100644 --- a/examples/features/src/ray_cube_normals/mod.rs +++ b/examples/features/src/ray_cube_normals/mod.rs @@ -334,6 +334,7 @@ impl crate::framework::Example for Example { )), 0, 0xff, + 0, )); } } diff --git a/examples/features/src/ray_scene/mod.rs b/examples/features/src/ray_scene/mod.rs index 98785331c..8496aa6ec 100644 --- a/examples/features/src/ray_scene/mod.rs +++ b/examples/features/src/ray_scene/mod.rs @@ -487,6 +487,7 @@ impl crate::framework::Example for Example { transform, blas_index as u32, 0xff, + 0, )); } } diff --git a/examples/features/src/ray_shadows/mod.rs b/examples/features/src/ray_shadows/mod.rs index fe91cebf7..adac15fee 100644 --- a/examples/features/src/ray_shadows/mod.rs +++ b/examples/features/src/ray_shadows/mod.rs @@ -223,6 +223,7 @@ impl crate::framework::Example for Example { [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], 0, 0xFF, + 0, )); let mut encoder = diff --git a/examples/features/src/ray_traced_triangle/mod.rs b/examples/features/src/ray_traced_triangle/mod.rs index 063fec5b5..34a242fa7 100644 --- a/examples/features/src/ray_traced_triangle/mod.rs +++ b/examples/features/src/ray_traced_triangle/mod.rs @@ -165,6 +165,7 @@ impl crate::framework::Example for Example { .unwrap(), 0, 0xff, + 0, )); tlas[1] = Some(TlasInstance::new( @@ -180,6 +181,7 @@ impl crate::framework::Example for Example { .unwrap(), 0, 0xff, + 0, )); tlas[2] = Some(TlasInstance::new( @@ -195,6 +197,7 @@ impl crate::framework::Example for Example { .unwrap(), 0, 0xff, + 0, )); let uniforms = { diff --git a/examples/standalone/custom_backend/src/custom.rs b/examples/standalone/custom_backend/src/custom.rs index 6298de32c..374349525 100644 --- a/examples/standalone/custom_backend/src/custom.rs +++ b/examples/standalone/custom_backend/src/custom.rs @@ -191,6 +191,13 @@ impl DeviceInterface for CustomDevice { wgpu::custom::DispatchComputePipeline::custom(CustomComputePipeline(module.0.clone())) } + fn create_ray_tracing_pipeline( + &self, + _desc: &wgpu::RayTracingPipelineDescriptor<'_>, + ) -> wgpu::custom::DispatchRayTracingPipeline { + unimplemented!() + } + unsafe fn create_pipeline_cache( &self, _desc: &wgpu::PipelineCacheDescriptor<'_>, diff --git a/naga/src/compact/mod.rs b/naga/src/compact/mod.rs index fda7e6124..bf513595e 100644 --- a/naga/src/compact/mod.rs +++ b/naga/src/compact/mod.rs @@ -135,6 +135,11 @@ pub fn compact(module: &mut crate::Module, keep_unused: KeepUnused) { if let Some(task_payload) = e.task_payload { module_tracer.global_variables_used.insert(task_payload); } + if let Some(incoming_ray_payload) = e.incoming_ray_payload { + module_tracer + .global_variables_used + .insert(incoming_ray_payload); + } if let Some(ref mesh_info) = e.mesh_info { module_tracer .global_variables_used @@ -381,6 +386,9 @@ pub fn compact(module: &mut crate::Module, keep_unused: KeepUnused) { if let Some(ref mut task_payload) = entry.task_payload { module_map.globals.adjust(task_payload); } + if let Some(ref mut incoming_ray_payload) = entry.incoming_ray_payload { + module_map.globals.adjust(incoming_ray_payload); + } if let Some(ref mut mesh_info) = entry.mesh_info { module_map.globals.adjust(&mut mesh_info.output_variable); module_map.types.adjust(&mut mesh_info.vertex_output_type); diff --git a/player/src/lib.rs b/player/src/lib.rs index c008ffb5f..323639c4c 100644 --- a/player/src/lib.rs +++ b/player/src/lib.rs @@ -54,6 +54,10 @@ pub struct Player { wgc::id::PointerId, Arc, >, + ray_tracing_pipelines: HashMap< + wgc::id::PointerId, + Arc, + >, pipeline_caches: HashMap< wgc::id::PointerId, Arc, @@ -83,6 +87,7 @@ impl Default for Player { render_bundles: HashMap::new(), render_pipelines: HashMap::new(), compute_pipelines: HashMap::new(), + ray_tracing_pipelines: HashMap::new(), pipeline_caches: HashMap::new(), query_sets: HashMap::new(), buffers: HashMap::new(), @@ -207,6 +212,15 @@ impl Player { let bgl = pipeline.get_bind_group_layout(index); self.bind_group_layouts.insert(id, bgl); } + Action::GetRayTracingPipelineBindGroupLayout { + id, + pipeline, + index, + } => { + let pipeline = self.resolve_ray_tracing_pipeline_id(pipeline); + let (bgl, _error) = pipeline.get_bind_group_layout(index); + self.bind_group_layouts.insert(id, bgl); + } Action::DropBindGroupLayout(id) => { self.bind_group_layouts .remove(&id) @@ -341,6 +355,16 @@ impl Player { .remove(&id) .expect("invalid render pipeline"); } + Action::CreateRayTracingPipeline { id, desc } => { + let descriptor = self.resolve_ray_tracing_pipeline_descriptor(desc); + let (rt_pipeline, _error) = device.create_ray_tracing_pipeline(descriptor); + self.ray_tracing_pipelines.insert(id, rt_pipeline); + } + Action::DropRayTracingPipeline(id) => { + self.ray_tracing_pipelines + .remove(&id) + .expect("invalid ray tracing pipeline"); + } Action::CreatePipelineCache { id, desc } => { let (cache, _error) = unsafe { device.create_pipeline_cache(&desc) }; self.pipeline_caches.insert(id, cache); @@ -573,6 +597,16 @@ impl Player { .clone() } + fn resolve_ray_tracing_pipeline_id( + &self, + id: wgc::id::PointerId, + ) -> Arc { + self.ray_tracing_pipelines + .get(&id) + .expect("invalid ray tracing pipeline") + .clone() + } + fn resolve_pipeline_cache_id( &self, id: wgc::id::PointerId, @@ -715,6 +749,61 @@ impl Player { } } + fn resolve_ray_tracing_pipeline_descriptor<'a>( + &self, + desc: wgc::device::trace::TraceRayTracingPipelineDescriptor<'a>, + ) -> wgc::ray_tracing_pipeline::RayTracingPipelineDescriptor<'a> { + let layout = desc.layout.map(|id| self.resolve_pipeline_layout_id(id)); + + wgc::ray_tracing_pipeline::RayTracingPipelineDescriptor { + label: desc.label, + layout, + cache: desc.cache.map(|id| self.resolve_pipeline_cache_id(id)), + ray_generation: wgc::pipeline::ProgrammableStageDescriptor { + module: self.resolve_shader_module_id(desc.ray_generation.module), + entry_point: desc.ray_generation.entry_point, + constants: desc.ray_generation.constants, + zero_initialize_workgroup_memory: desc + .ray_generation + .zero_initialize_workgroup_memory, + }, + miss: wgc::pipeline::ProgrammableStageDescriptor { + module: self.resolve_shader_module_id(desc.miss.module), + entry_point: desc.miss.entry_point, + constants: desc.miss.constants, + zero_initialize_workgroup_memory: desc.miss.zero_initialize_workgroup_memory, + }, + intersections: desc + .intersections + .into_iter() + .map(|intersections| match intersections { + wgc::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle { + closest_hit, + any_hit, + } => wgc::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle { + closest_hit: wgc::pipeline::ProgrammableStageDescriptor { + module: self.resolve_shader_module_id(closest_hit.module), + entry_point: closest_hit.entry_point, + constants: closest_hit.constants, + zero_initialize_workgroup_memory: closest_hit + .zero_initialize_workgroup_memory, + }, + any_hit: any_hit.map(|any_hit| { + wgc::pipeline::ProgrammableStageDescriptor { + module: self.resolve_shader_module_id(any_hit.module), + entry_point: any_hit.entry_point, + constants: any_hit.constants, + zero_initialize_workgroup_memory: any_hit + .zero_initialize_workgroup_memory, + } + }), + }, + }) + .collect(), + max_recursion_depth: desc.max_recursion_depth, + } + } + fn resolve_bind_group_descriptor<'a>( &self, desc: wgc::device::trace::TraceBindGroupDescriptor<'a>, @@ -905,6 +994,9 @@ impl Player { occlusion_query_set: occlusion_query_set.map(|qs| self.resolve_query_set_id(qs)), multiview_mask, }, + Command::RunRayTracingPass { pass } => Command::RunRayTracingPass { + pass: self.resolve_ray_tracing_pass(pass), + }, Command::BuildAccelerationStructures { blas, tlas } => { Command::BuildAccelerationStructures { blas: blas @@ -996,6 +1088,30 @@ impl Player { } } + fn resolve_ray_tracing_pass( + &self, + pass: BasePass, Infallible>, + ) -> BasePass, Infallible> { + let BasePass { + label, + error, + commands, + dynamic_offsets, + string_data, + } = pass; + + BasePass { + label, + error, + commands: commands + .into_iter() + .map(|cmd| self.resolve_ray_tracing_command(cmd)) + .collect(), + dynamic_offsets, + string_data, + } + } + fn resolve_compute_command( &self, command: wgc::command::ComputeCommand, @@ -1197,6 +1313,30 @@ impl Player { } } + fn resolve_ray_tracing_command( + &self, + command: wgc::command::RayTracingCommand, + ) -> wgc::command::RayTracingCommand { + use wgc::command::RayTracingCommand as C; + match command { + C::SetBindGroup { + index, + num_dynamic_offsets, + bind_group, + } => C::SetBindGroup { + index, + num_dynamic_offsets, + bind_group: bind_group.map(|bg| self.resolve_bind_group_id(bg)), + }, + C::SetPipeline(id) => C::SetPipeline(self.resolve_ray_tracing_pipeline_id(id)), + C::SetImmediate { offset, data } => C::SetImmediate { offset, data }, + C::TraceRays(groups) => C::TraceRays(groups), + C::PushDebugGroup { color, len } => C::PushDebugGroup { color, len }, + C::PopDebugGroup => C::PopDebugGroup, + C::InsertDebugMarker { color, len } => C::InsertDebugMarker { color, len }, + } + } + fn resolve_pass_timestamp_writes( &self, writes: wgc::command::PassTimestampWrites>, @@ -1329,6 +1469,7 @@ impl Player { transform: instance.transform, custom_data: instance.custom_data, mask: instance.mask, + intersection_index: instance.intersection_index, } } diff --git a/tests/tests/wgpu-gpu/binding_array/tlas.rs b/tests/tests/wgpu-gpu/binding_array/tlas.rs index 8ed4641c3..82c857b8c 100644 --- a/tests/tests/wgpu-gpu/binding_array/tlas.rs +++ b/tests/tests/wgpu-gpu/binding_array/tlas.rs @@ -131,12 +131,14 @@ async fn binding_array_tlas(ctx: TestingContext) { [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], 0, 0xff, + 0, )); tlas_b[0] = Some(wgpu::TlasInstance::new( &blas, [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], 0, 0xff, + 0, )); // Build BLAS and TLASes. diff --git a/tests/tests/wgpu-gpu/ray_tracing/as_aabb.rs b/tests/tests/wgpu-gpu/ray_tracing/as_aabb.rs index 0816e4cdf..c51cf0f6d 100644 --- a/tests/tests/wgpu-gpu/ray_tracing/as_aabb.rs +++ b/tests/tests/wgpu-gpu/ray_tracing/as_aabb.rs @@ -86,6 +86,7 @@ fn aabb_blas_build_and_trace(ctx: TestingContext) { [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], 0, 0xFF, + 0, )); let mut encoder = ctx diff --git a/tests/tests/wgpu-gpu/ray_tracing/as_build.rs b/tests/tests/wgpu-gpu/ray_tracing/as_build.rs index 88010133f..63e391fc1 100644 --- a/tests/tests/wgpu-gpu/ray_tracing/as_build.rs +++ b/tests/tests/wgpu-gpu/ray_tracing/as_build.rs @@ -556,6 +556,7 @@ fn build_with_transform(ctx: TestingContext) { [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], 0, 0xFF, + 0, )); let mut encoder_build = ctx diff --git a/tests/tests/wgpu-gpu/ray_tracing/as_use_after_free.rs b/tests/tests/wgpu-gpu/ray_tracing/as_use_after_free.rs index 365b10386..824f00108 100644 --- a/tests/tests/wgpu-gpu/ray_tracing/as_use_after_free.rs +++ b/tests/tests/wgpu-gpu/ray_tracing/as_use_after_free.rs @@ -64,6 +64,7 @@ fn acceleration_structure_use_after_free(ctx: TestingContext) { [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], 0, 0xFF, + 0, )); // Actually build the BLAS. diff --git a/tests/tests/wgpu-gpu/ray_tracing/mod.rs b/tests/tests/wgpu-gpu/ray_tracing/mod.rs index 8219569b2..9dc32b298 100644 --- a/tests/tests/wgpu-gpu/ray_tracing/mod.rs +++ b/tests/tests/wgpu-gpu/ray_tracing/mod.rs @@ -16,6 +16,7 @@ mod as_build; mod as_create; mod as_use_after_free; mod limits; +mod pipelines; mod scene; mod shader; @@ -27,6 +28,7 @@ pub fn all_tests(tests: &mut Vec) { limits::all_tests(tests); scene::all_tests(tests); shader::all_tests(tests); + pipelines::all_tests(tests); } fn acceleration_structure_limits() -> wgpu::Limits { @@ -84,6 +86,7 @@ impl AsBuildContext { [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], 0, 0xFF, + 0, )); Self { diff --git a/tests/tests/wgpu-gpu/ray_tracing/pipelines.rs b/tests/tests/wgpu-gpu/ray_tracing/pipelines.rs new file mode 100644 index 000000000..d87965baa --- /dev/null +++ b/tests/tests/wgpu-gpu/ray_tracing/pipelines.rs @@ -0,0 +1,1047 @@ +use std::sync::mpsc; + +use wgpu::{ + BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry, + CommandEncoderDescriptor, Features, Limits, PipelineLayoutDescriptor, + RayTracingIntersectionDescriptor, RayTracingPassDescriptor, RayTracingPipelineDescriptor, + RayTracingStage, ShaderModuleDescriptor, ShaderStages, +}; +use wgpu_test::{ + apply, fail, gpu_test, GpuTestConfiguration, GpuTestInitializer, TestParameters, TestingContext, +}; +use wgpu_types::AccelerationStructureFlags; + +pub fn all_tests(tests: &mut Vec) { + tests.push(PIPELINE_CREATE_USE); + tests.push(RAY_TRACING_PASS_NO_FEATURE); + tests.push(PIPELINE_OUTPUT); + tests.push(PIPELINE_SWAP); + tests.push(MISMATCHED_INTERSECTION_TYPES); + tests.push(EMPTY_PIPELINE_USE); + tests.push(INTERSECTION_INDEX_BOUNDS); + tests.push(INTERSECTION_INDEX_NO_FEATURE); +} + +#[apply(gpu_test!)] +static PIPELINE_CREATE_USE: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .features(Features::EXPERIMENTAL_RAY_TRACING_PIPELINES) + .limits( + Limits::defaults() + .using_minimum_supported_acceleration_structure_values() + .using_minimum_supported_ray_tracing_pipeline_values(), + ), + ) + .run_sync(pipeline_create_use); + +fn pipeline_create_use(ctx: TestingContext) { + let mut as_ctx = super::AsBuildContext::new( + &ctx, + AccelerationStructureFlags::empty(), + AccelerationStructureFlags::empty(), + ); + + let mut encoder = ctx + .device + .create_command_encoder(&CommandEncoderDescriptor::default()); + + // Build the BLAS and the TLAS. + encoder.build_acceleration_structures([&as_ctx.blas_build_entry()], [&as_ctx.tlas]); + + ctx.queue.submit([encoder.finish()]); + + let ray_gen_source = " + enable wgpu_ray_tracing_pipeline; + + @group(0) @binding(0) var acc_struct: acceleration_structure; + + var payload: u32; + + @ray_generation + fn gen() { + traceRay(acc_struct, RayDesc(0u, 0xFFu, 0.001, 100.0, vec3f(0.0, 0.0, 0.0), vec3f(0.0, 0.0, 1.0)), &payload); + } + "; + + let ray_closest_source = " + enable wgpu_ray_tracing_pipeline; + + var payload: u32; + + @closest_hit + @incoming_payload(payload) + fn closest() { + + } + "; + + let ray_any_source = " + enable wgpu_ray_tracing_pipeline; + + var payload: u32; + + @any_hit + @incoming_payload(payload) + fn any() { + + } + "; + + let ray_miss_source = " + enable wgpu_ray_tracing_pipeline; + + var payload: u32; + + @miss + @incoming_payload(payload) + fn miss() { + + } + "; + + let ray_gen = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray generation shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_gen_source)), + }); + + let ray_closest = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray closest hit shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_closest_source)), + }); + + let ray_any = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray any hit shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_any_source)), + }); + + let ray_miss = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray miss shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_miss_source)), + }); + + let pipeline = ctx + .device + .create_ray_tracing_pipeline(&RayTracingPipelineDescriptor { + label: None, + layout: None, + ray_generation: RayTracingStage { + module: &ray_gen, + entry_point: None, + compilation_options: Default::default(), + }, + miss: RayTracingStage { + module: &ray_miss, + entry_point: None, + compilation_options: Default::default(), + }, + intersections: &[ + RayTracingIntersectionDescriptor::Triangle { + closest_hit: RayTracingStage { + module: &ray_closest, + entry_point: None, + compilation_options: Default::default(), + }, + any_hit: Some(RayTracingStage { + module: &ray_any, + entry_point: None, + compilation_options: Default::default(), + }), + }, + RayTracingIntersectionDescriptor::Triangle { + closest_hit: RayTracingStage { + module: &ray_closest, + entry_point: None, + compilation_options: Default::default(), + }, + any_hit: Some(RayTracingStage { + module: &ray_any, + entry_point: None, + compilation_options: Default::default(), + }), + }, + ], + max_recursion_depth: 1, + cache: None, + }); + + let bind_group = ctx.device.create_bind_group(&BindGroupDescriptor { + label: Some("ray tracing pipeline bind group"), + layout: &pipeline.get_bind_group_layout(0), + entries: &[BindGroupEntry { + binding: 0, + resource: as_ctx.tlas.as_binding(), + }], + }); + + let mut encoder = ctx.device.create_command_encoder(&Default::default()); + + { + let mut pass = encoder.begin_ray_tracing_pass(&RayTracingPassDescriptor::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.trace_rays(1, 1, 2); + } + + // Change the intersection index to the other valid one + as_ctx.tlas[0].as_mut().unwrap().intersection_index = 1; + + // Build the TLAS with the other index. + encoder.build_acceleration_structures([], [&as_ctx.tlas]); + + // Rerun with the new intersection index. + { + let mut pass = encoder.begin_ray_tracing_pass(&RayTracingPassDescriptor::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.trace_rays(1, 1, 2); + } + + ctx.queue.submit([encoder.finish()]); + + let mut encoder = ctx.device.create_command_encoder(&Default::default()); + + // Change the intersection index to be invalid. + as_ctx.tlas[0].as_mut().unwrap().intersection_index = 2; + + // Build the TLAS with the invalid index. + encoder.build_acceleration_structures([], [&as_ctx.tlas]); + + // Rerun with the new intersection index (should fail). + { + let mut pass = encoder.begin_ray_tracing_pass(&RayTracingPassDescriptor::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.trace_rays(1, 1, 2); + } + + fail( + &ctx.device, + || { + ctx.queue.submit([encoder.finish()]); + }, + None, + ); + + let mut encoder = ctx.device.create_command_encoder(&Default::default()); + + // check that an empty tlas is fine to use + as_ctx.tlas[0] = None; + + // Build the TLAS with the other index. + encoder.build_acceleration_structures([], [&as_ctx.tlas]); + + // Rerun with the new intersection index. + { + let mut pass = encoder.begin_ray_tracing_pass(&RayTracingPassDescriptor::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.trace_rays(1, 1, 2); + } + + ctx.queue.submit([encoder.finish()]); +} + +#[apply(gpu_test!)] +static RAY_TRACING_PASS_NO_FEATURE: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters(TestParameters::default()) + .run_sync(ray_tracing_pass_no_feature); + +fn ray_tracing_pass_no_feature(ctx: TestingContext) { + let mut encoder = ctx + .device + .create_command_encoder(&CommandEncoderDescriptor::default()); + + let pass = encoder.begin_ray_tracing_pass(&RayTracingPassDescriptor::default()); + drop(pass); + + fail(&ctx.device, || encoder.finish(), None); +} + +#[apply(gpu_test!)] +static PIPELINE_OUTPUT: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .features(Features::EXPERIMENTAL_RAY_TRACING_PIPELINES) + .limits( + Limits::defaults() + .using_minimum_supported_acceleration_structure_values() + .using_minimum_supported_ray_tracing_pipeline_values(), + ), + ) + .run_sync(pipeline_output); + +fn pipeline_output(ctx: TestingContext) { + let ray_gen_source = " + enable wgpu_ray_tracing_pipeline; + + var payload: u32; + + @group(0) @binding(0) + var out: u32; + + @ray_generation + fn gen() { + out = 1; + } + "; + + let ray_miss_source = " + enable wgpu_ray_tracing_pipeline; + + var payload: u32; + + @miss + @incoming_payload(payload) + fn miss() { + + } + "; + + let ray_gen = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray generation shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_gen_source)), + }); + + let ray_miss = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray miss shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_miss_source)), + }); + + let pipeline = ctx + .device + .create_ray_tracing_pipeline(&RayTracingPipelineDescriptor { + label: None, + layout: None, + ray_generation: RayTracingStage { + module: &ray_gen, + entry_point: None, + compilation_options: Default::default(), + }, + miss: RayTracingStage { + module: &ray_miss, + entry_point: None, + compilation_options: Default::default(), + }, + intersections: &[], + max_recursion_depth: 1, + cache: None, + }); + + let out_buffer = ctx.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: size_of::() as _, + usage: wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::STORAGE, + mapped_at_creation: false, + }); + + let readback = ctx.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: size_of::() as _, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + + let bind_group = ctx.device.create_bind_group(&BindGroupDescriptor { + label: Some("ray tracing pipeline bind group"), + layout: &pipeline.get_bind_group_layout(0), + entries: &[BindGroupEntry { + binding: 0, + resource: out_buffer.as_entire_binding(), + }], + }); + + let mut encoder = ctx.device.create_command_encoder(&Default::default()); + + { + let mut pass = encoder.begin_ray_tracing_pass(&RayTracingPassDescriptor::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.trace_rays(1, 1, 1); + } + + encoder.copy_buffer_to_buffer(&out_buffer, 0, &readback, 0, out_buffer.size()); + + ctx.queue.submit([encoder.finish()]); + + let (send, recv) = mpsc::channel(); + readback.map_async(wgpu::MapMode::Read, .., move |res| { + res.unwrap(); + send.send(()).unwrap() + }); + ctx.device + .poll(wgpu::PollType::wait_indefinitely()) + .unwrap(); + + recv.recv().unwrap(); + + let range = readback.get_mapped_range(..).unwrap(); + + assert_eq!(range[0], 1) +} + +#[apply(gpu_test!)] +static PIPELINE_SWAP: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .features(Features::EXPERIMENTAL_RAY_TRACING_PIPELINES) + .limits( + Limits::defaults() + .using_minimum_supported_acceleration_structure_values() + .using_minimum_supported_ray_tracing_pipeline_values(), + ), + ) + .run_sync(pipeline_swap); + +fn pipeline_swap(ctx: TestingContext) { + let as_ctx = super::AsBuildContext::new( + &ctx, + AccelerationStructureFlags::empty(), + AccelerationStructureFlags::empty(), + ); + + let mut encoder = ctx + .device + .create_command_encoder(&CommandEncoderDescriptor::default()); + + // Build the BLAS and the TLAS. + encoder.build_acceleration_structures([&as_ctx.blas_build_entry()], [&as_ctx.tlas]); + + ctx.queue.submit([encoder.finish()]); + + let ray_gen_source = " + enable wgpu_ray_tracing_pipeline; + + @group(0) @binding(0) var acc_struct: acceleration_structure; + + var payload: u32; + + @ray_generation + fn gen() { + traceRay(acc_struct, RayDesc(0u, 0xFFu, 0.001, 100.0, vec3f(0.0, 0.0, 0.0), vec3f(0.0, 0.0, 1.0)), &payload); + } + "; + + let ray_closest_source = " + enable wgpu_ray_tracing_pipeline; + + var payload: u32; + + @closest_hit + @incoming_payload(payload) + fn closest() { + + } + "; + + let ray_any_source = " + enable wgpu_ray_tracing_pipeline; + + var payload: u32; + + @any_hit + @incoming_payload(payload) + fn any() { + + } + "; + + let ray_miss_source = " + enable wgpu_ray_tracing_pipeline; + + var payload: u32; + + @miss + @incoming_payload(payload) + fn miss() { + + } + "; + + let ray_gen = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray generation shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_gen_source)), + }); + + let ray_closest = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray closest hit shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_closest_source)), + }); + + let ray_any = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray any hit shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_any_source)), + }); + + let ray_miss = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray miss shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_miss_source)), + }); + + let bgl = ctx + .device + .create_bind_group_layout(&BindGroupLayoutDescriptor { + label: None, + entries: &[BindGroupLayoutEntry { + binding: 0, + visibility: ShaderStages::RAY_GENERATION, + ty: wgpu::BindingType::AccelerationStructure { + vertex_return: false, + }, + count: None, + }], + }); + + let pipeline_layout = ctx + .device + .create_pipeline_layout(&PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + + let pipeline = ctx + .device + .create_ray_tracing_pipeline(&RayTracingPipelineDescriptor { + label: None, + layout: Some(&pipeline_layout), + ray_generation: RayTracingStage { + module: &ray_gen, + entry_point: None, + compilation_options: Default::default(), + }, + miss: RayTracingStage { + module: &ray_miss, + entry_point: None, + compilation_options: Default::default(), + }, + intersections: &[RayTracingIntersectionDescriptor::Triangle { + closest_hit: RayTracingStage { + module: &ray_closest, + entry_point: None, + compilation_options: Default::default(), + }, + any_hit: Some(RayTracingStage { + module: &ray_any, + entry_point: None, + compilation_options: Default::default(), + }), + }], + max_recursion_depth: 1, + cache: None, + }); + + let pipeline_to_swap = ctx + .device + .create_ray_tracing_pipeline(&RayTracingPipelineDescriptor { + label: None, + layout: Some(&pipeline_layout), + ray_generation: RayTracingStage { + module: &ray_gen, + entry_point: None, + compilation_options: Default::default(), + }, + miss: RayTracingStage { + module: &ray_miss, + entry_point: None, + compilation_options: Default::default(), + }, + intersections: &[], + max_recursion_depth: 1, + cache: None, + }); + + let bind_group = ctx.device.create_bind_group(&BindGroupDescriptor { + label: Some("ray tracing pipeline bind group"), + layout: &bgl, + entries: &[BindGroupEntry { + binding: 0, + resource: as_ctx.tlas.as_binding(), + }], + }); + + let mut encoder = ctx.device.create_command_encoder(&Default::default()); + + { + let mut pass = encoder.begin_ray_tracing_pass(&RayTracingPassDescriptor::default()); + pass.set_pipeline(&pipeline); + pass.set_pipeline(&pipeline_to_swap); + pass.set_bind_group(0, &bind_group, &[]); + pass.trace_rays(1, 1, 2); + } + + fail( + &ctx.device, + || { + ctx.queue.submit([encoder.finish()]); + }, + None, + ); +} + +#[apply(gpu_test!)] +static MISMATCHED_INTERSECTION_TYPES: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .features(Features::EXPERIMENTAL_RAY_TRACING_PIPELINES) + .limits( + Limits::defaults() + .using_minimum_supported_acceleration_structure_values() + .using_minimum_supported_ray_tracing_pipeline_values(), + ), + ) + .run_sync(mismatched_intersection_types); + +fn mismatched_intersection_types(ctx: TestingContext) { + // test that a tlas that needs an AABB intersection group in index 0 doesn't + // trace when used with a ray tracing pipeline that has a triangle intersection + // group in index 0. + + let aabb_buf = ctx.device.create_buffer(&wgpu::BufferDescriptor { + label: None, + usage: wgpu::BufferUsages::BLAS_INPUT, + size: wgpu::AABB_GEOMETRY_MIN_STRIDE, + mapped_at_creation: false, + }); + + let blas_size = wgpu::BlasAABBGeometrySizeDescriptor { + primitive_count: 1, + flags: wgpu::AccelerationStructureGeometryFlags::empty(), + }; + let blas = ctx.device.create_blas( + &wgpu::CreateBlasDescriptor { + label: Some("AABB BLAS"), + flags: AccelerationStructureFlags::PREFER_FAST_TRACE, + update_mode: wgpu::AccelerationStructureUpdateMode::Build, + }, + wgpu::BlasGeometrySizeDescriptors::AABBs { + descriptors: vec![blas_size.clone()], + }, + ); + + let mut tlas = ctx.device.create_tlas(&wgpu::CreateTlasDescriptor { + label: Some("TLAS"), + max_instances: 1, + flags: AccelerationStructureFlags::PREFER_FAST_TRACE, + update_mode: wgpu::AccelerationStructureUpdateMode::Build, + }); + tlas[0] = Some(wgpu::TlasInstance::new( + &blas, + [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], + 0, + 0xFF, + 0, + )); + + let mut encoder = ctx + .device + .create_command_encoder(&CommandEncoderDescriptor { + label: Some("build"), + }); + encoder.build_acceleration_structures( + [&wgpu::BlasBuildEntry { + blas: &blas, + geometry: wgpu::BlasGeometries::AabbGeometries(vec![wgpu::BlasAabbGeometry { + size: &blas_size, + stride: wgpu::AABB_GEOMETRY_MIN_STRIDE, + aabb_buffer: &aabb_buf, + primitive_offset: 0, + }]), + }], + [&tlas], + ); + ctx.queue.submit([encoder.finish()]); + + let ray_gen_source = " + enable wgpu_ray_tracing_pipeline; + + @group(0) @binding(0) var acc_struct: acceleration_structure; + + var payload: u32; + + @ray_generation + fn gen() { + traceRay(acc_struct, RayDesc(0u, 0xFFu, 0.001, 100.0, vec3f(0.0, 0.0, 0.0), vec3f(0.0, 0.0, 1.0)), &payload); + } + "; + + let ray_closest_source = " + enable wgpu_ray_tracing_pipeline; + + var payload: u32; + + @closest_hit + @incoming_payload(payload) + fn closest() { + + } + "; + + let ray_any_source = " + enable wgpu_ray_tracing_pipeline; + + var payload: u32; + + @any_hit + @incoming_payload(payload) + fn any() { + + } + "; + + let ray_miss_source = " + enable wgpu_ray_tracing_pipeline; + + var payload: u32; + + @miss + @incoming_payload(payload) + fn miss() { + + } + "; + + let ray_gen = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray generation shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_gen_source)), + }); + + let ray_closest = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray closest hit shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_closest_source)), + }); + + let ray_any = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray any hit shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_any_source)), + }); + + let ray_miss = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray miss shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_miss_source)), + }); + + let pipeline = ctx + .device + .create_ray_tracing_pipeline(&RayTracingPipelineDescriptor { + label: None, + layout: None, + ray_generation: RayTracingStage { + module: &ray_gen, + entry_point: None, + compilation_options: Default::default(), + }, + miss: RayTracingStage { + module: &ray_miss, + entry_point: None, + compilation_options: Default::default(), + }, + intersections: &[ + RayTracingIntersectionDescriptor::Triangle { + closest_hit: RayTracingStage { + module: &ray_closest, + entry_point: None, + compilation_options: Default::default(), + }, + any_hit: Some(RayTracingStage { + module: &ray_any, + entry_point: None, + compilation_options: Default::default(), + }), + }, + RayTracingIntersectionDescriptor::Triangle { + closest_hit: RayTracingStage { + module: &ray_closest, + entry_point: None, + compilation_options: Default::default(), + }, + any_hit: Some(RayTracingStage { + module: &ray_any, + entry_point: None, + compilation_options: Default::default(), + }), + }, + ], + max_recursion_depth: 1, + cache: None, + }); + + let bind_group = ctx.device.create_bind_group(&BindGroupDescriptor { + label: Some("ray tracing pipeline bind group"), + layout: &pipeline.get_bind_group_layout(0), + entries: &[BindGroupEntry { + binding: 0, + resource: tlas.as_binding(), + }], + }); + + let mut encoder = ctx.device.create_command_encoder(&Default::default()); + + { + let mut pass = encoder.begin_ray_tracing_pass(&RayTracingPassDescriptor::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.trace_rays(1, 1, 1); + } + + fail( + &ctx.device, + || { + ctx.queue.submit([encoder.finish()]); + }, + None, + ); +} + +#[apply(gpu_test!)] +static EMPTY_PIPELINE_USE: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .features(Features::EXPERIMENTAL_RAY_TRACING_PIPELINES) + .limits( + Limits::defaults() + .using_minimum_supported_acceleration_structure_values() + .using_minimum_supported_ray_tracing_pipeline_values(), + ), + ) + .run_sync(empty_pipeline_use); + +fn empty_pipeline_use(ctx: TestingContext) { + let mut as_ctx = super::AsBuildContext::new( + &ctx, + AccelerationStructureFlags::empty(), + AccelerationStructureFlags::empty(), + ); + + let mut encoder = ctx + .device + .create_command_encoder(&CommandEncoderDescriptor::default()); + + // Build the BLAS and the TLAS. + encoder.build_acceleration_structures([&as_ctx.blas_build_entry()], [&as_ctx.tlas]); + + ctx.queue.submit([encoder.finish()]); + + let ray_gen_source = " + enable wgpu_ray_tracing_pipeline; + + @group(0) @binding(0) var acc_struct: acceleration_structure; + + var payload: u32; + + @ray_generation + fn gen() { + traceRay(acc_struct, RayDesc(0u, 0xFFu, 0.001, 100.0, vec3f(0.0, 0.0, 0.0), vec3f(0.0, 0.0, 1.0)), &payload); + } + "; + + let ray_miss_source = " + enable wgpu_ray_tracing_pipeline; + + var payload: u32; + + @miss + @incoming_payload(payload) + fn miss() { + + } + "; + + let ray_gen = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray generation shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_gen_source)), + }); + + let ray_miss = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: Some("ray miss shader"), + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(ray_miss_source)), + }); + + let pipeline = ctx + .device + .create_ray_tracing_pipeline(&RayTracingPipelineDescriptor { + label: None, + layout: None, + ray_generation: RayTracingStage { + module: &ray_gen, + entry_point: None, + compilation_options: Default::default(), + }, + miss: RayTracingStage { + module: &ray_miss, + entry_point: None, + compilation_options: Default::default(), + }, + intersections: &[], + max_recursion_depth: 1, + cache: None, + }); + + let bind_group = ctx.device.create_bind_group(&BindGroupDescriptor { + label: Some("ray tracing pipeline bind group"), + layout: &pipeline.get_bind_group_layout(0), + entries: &[BindGroupEntry { + binding: 0, + resource: as_ctx.tlas.as_binding(), + }], + }); + + let mut encoder = ctx.device.create_command_encoder(&Default::default()); + + // check that an empty tlas is fine to use + as_ctx.tlas[0] = None; + + // Build the TLAS with the other index. + encoder.build_acceleration_structures([], [&as_ctx.tlas]); + + // Rerun with the new intersection index. + { + let mut pass = encoder.begin_ray_tracing_pass(&RayTracingPassDescriptor::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.trace_rays(1, 1, 2); + } + + ctx.queue.submit([encoder.finish()]); +} + +#[apply(gpu_test!)] +static INTERSECTION_INDEX_BOUNDS: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .features(Features::EXPERIMENTAL_RAY_TRACING_PIPELINES) + .limits( + Limits::defaults() + .using_minimum_supported_acceleration_structure_values() + .using_minimum_supported_ray_tracing_pipeline_values(), + ), + ) + .run_sync(intersection_index_bounds); + +fn intersection_index_bounds(ctx: TestingContext) { + // A TLAS instance with intersection index 1 can be traced only with a pipeline + // that has at least 2 intersection groups. + let mut as_ctx = super::AsBuildContext::new( + &ctx, + AccelerationStructureFlags::empty(), + AccelerationStructureFlags::empty(), + ); + as_ctx.tlas[0].as_mut().unwrap().intersection_index = 1; + + let mut encoder = ctx + .device + .create_command_encoder(&CommandEncoderDescriptor::default()); + encoder.build_acceleration_structures([&as_ctx.blas_build_entry()], [&as_ctx.tlas]); + ctx.queue.submit([encoder.finish()]); + + let shader = ctx.device.create_shader_module(ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( + " + enable wgpu_ray_tracing_pipeline; + + @group(0) @binding(0) var acc_struct: acceleration_structure; + + var payload: u32; + var incoming_payload: u32; + + @ray_generation + fn gen() { + traceRay(acc_struct, RayDesc(0u, 0xFFu, 0.001, 100.0, vec3f(0.0, 0.0, 0.0), vec3f(0.0, 0.0, 1.0)), &payload); + } + + @closest_hit + @incoming_payload(incoming_payload) + fn closest() {} + + @miss + @incoming_payload(incoming_payload) + fn miss() {} + ", + )), + }); + + let stage = RayTracingStage { + module: &shader, + entry_point: None, + compilation_options: Default::default(), + }; + let intersection = RayTracingIntersectionDescriptor::Triangle { + closest_hit: stage.clone(), + any_hit: None, + }; + + let trace = |intersections: &[RayTracingIntersectionDescriptor]| { + let pipeline = ctx + .device + .create_ray_tracing_pipeline(&RayTracingPipelineDescriptor { + label: None, + layout: None, + ray_generation: stage.clone(), + miss: stage.clone(), + intersections, + max_recursion_depth: 1, + cache: None, + }); + let bind_group = ctx.device.create_bind_group(&BindGroupDescriptor { + label: None, + layout: &pipeline.get_bind_group_layout(0), + entries: &[BindGroupEntry { + binding: 0, + resource: as_ctx.tlas.as_binding(), + }], + }); + let mut encoder = ctx.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_ray_tracing_pass(&RayTracingPassDescriptor::default()); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.trace_rays(1, 1, 1); + } + encoder.finish() + }; + + ctx.queue + .submit([trace(&[intersection.clone(), intersection.clone()])]); + + fail( + &ctx.device, + || { + ctx.queue.submit([trace(&[intersection])]); + }, + Some("out of bounds of the length of the intersection array"), + ); +} + +#[apply(gpu_test!)] +static INTERSECTION_INDEX_NO_FEATURE: GpuTestConfiguration = GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .features(Features::EXPERIMENTAL_RAY_QUERY) + .limits(Limits::defaults().using_minimum_supported_acceleration_structure_values()) + .enable_noop(), + ) + .run_sync(intersection_index_no_feature); + +fn intersection_index_no_feature(ctx: TestingContext) { + // A non-zero intersection index requires `EXPERIMENTAL_RAY_TRACING_PIPELINES`. + let mut as_ctx = super::AsBuildContext::new( + &ctx, + AccelerationStructureFlags::empty(), + AccelerationStructureFlags::empty(), + ); + as_ctx.tlas[0].as_mut().unwrap().intersection_index = 1; + + let mut encoder = ctx + .device + .create_command_encoder(&CommandEncoderDescriptor::default()); + encoder.build_acceleration_structures([&as_ctx.blas_build_entry()], [&as_ctx.tlas]); + + fail( + &ctx.device, + || { + ctx.queue.submit([encoder.finish()]); + }, + Some("EXPERIMENTAL_RAY_TRACING_PIPELINES"), + ); +} diff --git a/tests/tests/wgpu-gpu/ray_tracing/scene/mod.rs b/tests/tests/wgpu-gpu/ray_tracing/scene/mod.rs index 519237840..1d8d6fc02 100644 --- a/tests/tests/wgpu-gpu/ray_tracing/scene/mod.rs +++ b/tests/tests/wgpu-gpu/ray_tracing/scene/mod.rs @@ -76,6 +76,7 @@ fn acceleration_structure_build(ctx: &TestingContext, use_index_buffer: bool) { )), 0, 0xff, + 0, )); } diff --git a/wgpu-core-remote-types/src/id.rs b/wgpu-core-remote-types/src/id.rs index 14972197c..57eef3148 100644 --- a/wgpu-core-remote-types/src/id.rs +++ b/wgpu-core-remote-types/src/id.rs @@ -212,6 +212,7 @@ ids! { pub type ShaderModuleId ShaderModule; pub type RenderPipelineId RenderPipeline; pub type ComputePipelineId ComputePipeline; + pub type RayTracingPipelineId RayTracingPipeline; pub type PipelineCacheId PipelineCache; pub type CommandEncoderId CommandEncoder; pub type CommandBufferId CommandBuffer; diff --git a/wgpu-core-remote/src/id.rs b/wgpu-core-remote/src/id.rs index bf1a9fc09..8c298edcf 100644 --- a/wgpu-core-remote/src/id.rs +++ b/wgpu-core-remote/src/id.rs @@ -15,6 +15,7 @@ impl wgpu_core::command::ReferenceType for IdReferences { type RenderPipeline = RenderPipelineId; type RenderBundle = RenderBundleId; type ComputePipeline = ComputePipelineId; + type RayTracingPipeline = RayTracingPipelineId; type Blas = BlasId; type Tlas = TlasId; } diff --git a/wgpu-core/src/binding_model.rs b/wgpu-core/src/binding_model.rs index 5bbf6b7f2..909d2e087 100644 --- a/wgpu-core/src/binding_model.rs +++ b/wgpu-core/src/binding_model.rs @@ -28,6 +28,7 @@ use crate::{ device::{bgl, Device, DeviceError, MissingDownlevelFlags, MissingFeatures}, init_tracker::{BufferInitTrackerAction, TextureInitTrackerAction}, pipeline::{ComputePipeline, RenderPipeline}, + ray_tracing_pipeline::RayTracingPipeline, resource::{ Buffer, DestroyedResourceError, ExternalTexture, InvalidOrDestroyedResourceError, InvalidResourceError, Labeled, MissingBufferUsageError, MissingTextureUsageError, @@ -407,6 +408,10 @@ pub(crate) struct PerStageBindingTypeCounter { vertex: Saturating, fragment: Saturating, compute: Saturating, + ray_generation: Saturating, + miss: Saturating, + any_hit: Saturating, + closest_hit: Saturating, } impl PerStageBindingTypeCounter { @@ -420,10 +425,29 @@ impl PerStageBindingTypeCounter { if stage.contains(wgt::ShaderStages::COMPUTE) { self.compute += count; } + if stage.contains(wgt::ShaderStages::RAY_GENERATION) { + self.ray_generation += count; + } + if stage.contains(wgt::ShaderStages::MISS) { + self.miss += count; + } + if stage.contains(wgt::ShaderStages::ANY_HIT) { + self.any_hit += count; + } + if stage.contains(wgt::ShaderStages::CLOSEST_HIT) { + self.closest_hit += count; + } } pub(crate) fn max(&self) -> (BindingZone, u32) { - let max_value = self.vertex.max(self.fragment.max(self.compute)); + let max_value = self.vertex.max( + self.fragment.max( + self.compute.max( + self.ray_generation + .max(self.miss.max(self.any_hit.max(self.closest_hit))), + ), + ), + ); let mut stage = wgt::ShaderStages::NONE; if max_value == self.vertex { stage |= wgt::ShaderStages::VERTEX @@ -434,6 +458,18 @@ impl PerStageBindingTypeCounter { if max_value == self.compute { stage |= wgt::ShaderStages::COMPUTE } + if max_value == self.ray_generation { + stage |= wgt::ShaderStages::RAY_GENERATION + } + if max_value == self.miss { + stage |= wgt::ShaderStages::MISS + } + if max_value == self.any_hit { + stage |= wgt::ShaderStages::ANY_HIT + } + if max_value == self.closest_hit { + stage |= wgt::ShaderStages::CLOSEST_HIT + } (BindingZone::Stage(stage), max_value.0) } @@ -1163,6 +1199,7 @@ pub(crate) enum ExclusivePipeline { None, Render(Weak), Compute(Weak), + RayTracing(Weak), } impl From<&Arc> for ExclusivePipeline { @@ -1177,6 +1214,12 @@ impl From<&Arc> for ExclusivePipeline { } } +impl From<&Arc> for ExclusivePipeline { + fn from(pipeline: &Arc) -> Self { + Self::RayTracing(Arc::downgrade(pipeline)) + } +} + impl fmt::Display for ExclusivePipeline { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { @@ -1195,6 +1238,13 @@ impl fmt::Display for ExclusivePipeline { f.write_str("ComputePipeline") } } + ExclusivePipeline::RayTracing(p) => { + if let Some(p) = p.upgrade() { + p.error_ident().fmt(f) + } else { + f.write_str("RayTracingPipeline") + } + } } } } diff --git a/wgpu-core/src/command/encoder_command.rs b/wgpu-core/src/command/encoder_command.rs index 092843e59..7406c9117 100644 --- a/wgpu-core/src/command/encoder_command.rs +++ b/wgpu-core/src/command/encoder_command.rs @@ -21,6 +21,7 @@ pub trait ReferenceType { type RenderPipeline: Clone + core::fmt::Debug; type RenderBundle: Clone + core::fmt::Debug; type ComputePipeline: Clone + core::fmt::Debug; + type RayTracingPipeline: Clone + core::fmt::Debug; type Blas: Clone + core::fmt::Debug; type Tlas: Clone + core::fmt::Debug; } @@ -51,6 +52,7 @@ impl ReferenceType for PointerReferences { type RenderPipeline = crate::id::PointerId; type RenderBundle = crate::id::PointerId; type ComputePipeline = crate::id::PointerId; + type RayTracingPipeline = crate::id::PointerId; type Blas = crate::id::PointerId; type Tlas = crate::id::PointerId; } @@ -66,6 +68,7 @@ impl ReferenceType for ArcReferences { type RenderPipeline = Arc; type RenderBundle = Arc; type ComputePipeline = Arc; + type RayTracingPipeline = Arc; type Blas = Arc; type Tlas = Arc; } @@ -85,6 +88,7 @@ attribute_alias! { R::RenderPipeline: serde::Serialize + for<'d> serde::Deserialize<'d>,\ R::RenderBundle: serde::Serialize + for<'d> serde::Deserialize<'d>,\ R::ComputePipeline: serde::Serialize + for<'d> serde::Deserialize<'d>,\ + R::RayTracingPipeline: serde::Serialize + for<'d> serde::Deserialize<'d>,\ R::Blas: serde::Serialize + for<'d> serde::Deserialize<'d>,\ R::Tlas: serde::Serialize + for<'d> serde::Deserialize<'d>,\ wgt::BufferTransition: serde::Serialize + for<'d> serde::Deserialize<'d>,\ @@ -144,6 +148,9 @@ pub enum Command { pass: crate::command::BasePass, Infallible>, timestamp_writes: Option>, }, + RunRayTracingPass { + pass: crate::command::BasePass, Infallible>, + }, RunRenderPass { pass: crate::command::BasePass, Infallible>, color_attachments: ColorAttachments, diff --git a/wgpu-core/src/command/mod.rs b/wgpu-core/src/command/mod.rs index fd58bccfd..d4c2e3a01 100644 --- a/wgpu-core/src/command/mod.rs +++ b/wgpu-core/src/command/mod.rs @@ -21,6 +21,8 @@ mod memory_init; mod pass; mod query; mod ray_tracing; +mod ray_tracing_pass; +mod ray_tracing_pass_commands; mod render; mod render_command; mod timestamp_writes; @@ -55,6 +57,11 @@ pub use self::{ draw::{DrawError, Rect, RenderCommandError}, encoder_command::{ArcCommand, ArcReferences, Command, ReferenceType}, query::{QueryError, QueryUseError, ResolveError, SimplifiedQueryType}, + ray_tracing_pass::{ + RayTracingBasePass, RayTracingPass, RayTracingPassDescriptor, RayTracingPassError, + RayTracingPassErrorInner, TraceRayError, + }, + ray_tracing_pass_commands::ArcRayTracingCommand, render::{ AttachmentError, AttachmentErrorLocation, ColorAttachmentError, ColorAttachments, LoadOp, PassChannel, RenderBasePass, RenderPass, RenderPassColorAttachment, @@ -80,7 +87,10 @@ pub(crate) use self::{ pub(crate) use allocator::CommandAllocator; /// cbindgen:ignore -pub use self::{compute_command::ComputeCommand, render_command::RenderCommand}; +pub use self::{ + compute_command::ComputeCommand, ray_tracing_pass_commands::RayTracingCommand, + render_command::RenderCommand, +}; pub use timestamp_writes::PassTimestampWrites; @@ -1114,6 +1124,7 @@ impl CommandEncoder { ArcCommand::RunRenderPass { .. } | ArcCommand::RunComputePass { .. } | ArcCommand::ResolveQuerySet { .. } + | ArcCommand::RunRayTracingPass { .. } ) { // Compute passes and render passes can accept either an // open or closed encoder. Resolving query sets needs to @@ -1203,6 +1214,22 @@ impl CommandEncoder { destination_offset, )?; } + ArcCommand::RunRayTracingPass { pass } => { + api_log!( + "Begin encoding ray tracing pass with '{}' label", + pass.label.as_deref().unwrap_or("") + ); + let res = ray_tracing_pass::encode_ray_tracing_pass(&mut state, pass); + match res.as_ref() { + Err(err) => { + api_log!("Finished encoding ray tracing pass ({err:?})") + } + Ok(_) => { + api_log!("Finished encoding ray tracing pass (success)") + } + } + res?; + } _ => unreachable!(), } } else { @@ -1287,7 +1314,8 @@ impl CommandEncoder { } ArcCommand::RunComputePass { .. } | ArcCommand::RunRenderPass { .. } - | ArcCommand::ResolveQuerySet { .. } => { + | ArcCommand::ResolveQuerySet { .. } + | ArcCommand::RunRayTracingPass { .. } => { unreachable!() } } @@ -1659,6 +1687,8 @@ pub enum CommandEncoderError { ComputePass(#[from] ComputePassError), #[error(transparent)] RenderPass(#[from] RenderPassError), + #[error(transparent)] + RayTracingPass(#[from] RayTracingPassError), } impl From for CommandEncoderError { @@ -1713,6 +1743,7 @@ impl WebGpuError for CommandEncoderError { Self::ResourceUsage(e) => e.webgpu_error_type(), Self::ComputePass(e) => e.webgpu_error_type(), Self::RenderPass(e) => e.webgpu_error_type(), + Self::RayTracingPass(e) => e.webgpu_error_type(), } } } @@ -2020,6 +2051,8 @@ pub enum PassErrorScope { SetPipelineRender, #[error("In a set_pipeline command")] SetPipelineCompute, + #[error("In a set_pipeline command")] + SetPipelineRayTracing, #[error("In a set_immediates command")] SetImmediate, #[error("In a set_vertex_buffer command")] @@ -2061,6 +2094,8 @@ pub enum PassErrorScope { PopDebugGroup, #[error("In a insert_debug_marker command")] InsertDebugMarker, + #[error("In a trace rays command")] + TraceRays, } /// Variant of `EncoderStateError` that includes the pass scope. diff --git a/wgpu-core/src/command/pass.rs b/wgpu-core/src/command/pass.rs index 70096c916..2ce50fd08 100644 --- a/wgpu-core/src/command/pass.rs +++ b/wgpu-core/src/command/pass.rs @@ -236,7 +236,7 @@ pub(super) fn flush_bindings_helper( .used .acceleration_structures .into_iter() - .map(|tlas| crate::ray_tracing::AsAction::UseTlas(tlas.clone())); + .map(|tlas| crate::ray_tracing::AsAction::BindTlas(tlas.clone())); state.base.as_actions.extend(used_resource); diff --git a/wgpu-core/src/command/ray_tracing.rs b/wgpu-core/src/command/ray_tracing.rs index 1657851ab..33e939982 100644 --- a/wgpu-core/src/command/ray_tracing.rs +++ b/wgpu-core/src/command/ray_tracing.rs @@ -62,7 +62,7 @@ impl super::CommandEncoder { |cmd_buf_data| -> Result<(), BuildAccelerationStructureError> { let device = &self.device; device.check_is_valid()?; - device.require_features(Features::EXPERIMENTAL_RAY_QUERY)?; + device.require_acceleration_structures()?; let mut build_command = AsBuild::with_capacity(blases.len(), tlases.len()); @@ -78,6 +78,8 @@ impl super::CommandEncoder { build_command.tlas_s_built.push(TlasBuild { tlas, dependencies: Vec::new(), + max_intersection_idx: None, + required_intersection_types: Vec::new(), }); } @@ -198,9 +200,7 @@ pub(crate) fn build_acceleration_structures( mut tlases: Vec>, ) -> Result<(), BuildAccelerationStructureError> { profiling::scope!("build_acceleration_structures"); - state - .device - .require_features(Features::EXPERIMENTAL_RAY_QUERY)?; + state.device.require_acceleration_structures()?; let mut build_command = AsBuild::with_capacity(blases.len(), tlases.len()); let mut input_barriers = Vec::>::new(); @@ -237,13 +237,29 @@ pub(crate) fn build_acceleration_structures( let mut dependencies = Vec::new(); let mut seen_dependencies = FastHashSet::::default(); + let mut required_intersection_types = Vec::new(); + let mut seen_intersection_types = + FastHashSet::::default(); + let mut instance_count = 0; - for instance in mem::take(&mut package.instances).into_iter().flatten() { + + let mut max_intersection_idx = None; + for (instance_idx, instance) in mem::take(&mut package.instances) + .into_iter() + .enumerate() + .flat_map(|(idx, instance)| instance.map(|inst| (idx, inst))) + { if instance.custom_data >= (1u32 << 24u32) { - return Err(BuildAccelerationStructureError::TlasInvalidCustomIndex( + return Err(BuildAccelerationStructureError::TlasInvalidCustomData( tlas.error_ident(), + instance_idx, )); } + + let max_intersection_idx = max_intersection_idx.get_or_insert(0); + + *max_intersection_idx = (*max_intersection_idx).max(instance.intersection_index); + let blas = instance.blas; let is_new_dependency = seen_dependencies.insert(blas.tracker_index()); @@ -251,13 +267,27 @@ pub(crate) fn build_acceleration_structures( state.tracker.blas_s.insert_single(blas.clone()); } + if instance.intersection_index >= (1u32 << 24u32) { + return Err( + BuildAccelerationStructureError::TlasInvalidIntersectionIndex( + tlas.error_ident(), + instance_idx, + instance.intersection_index, + ), + ); + } else if instance.intersection_index != 0 { + state + .device + .require_features(Features::EXPERIMENTAL_RAY_TRACING_PIPELINES)?; + } + state.device.raw().tlas_instance_to_bytes( hal::TlasInstance { transform: instance.transform, custom_data: instance.custom_data, mask: instance.mask, blas_address: blas.handle, - pipeline_intersection_data_offset: 0, + pipeline_intersection_data_offset: instance.intersection_index, }, &mut instance_buffer_staging_source, ); @@ -279,6 +309,24 @@ pub(crate) fn build_acceleration_structures( instance_count += 1; + let intersection_ty = crate::resource::TlasIntersectionType { + index: instance.intersection_index, + required_intersection_ty: match blas.sizes { + wgt::BlasGeometrySizeDescriptors::Triangles { .. } => { + crate::ray_tracing_pipeline::RayTracingIntersectionType::Triangle + } + wgt::BlasGeometrySizeDescriptors::AABBs { .. } => { + crate::ray_tracing_pipeline::RayTracingIntersectionType::AABB + } + }, + }; + + let new_intersection_ty = seen_intersection_types.insert(intersection_ty); + + if new_intersection_ty { + required_intersection_types.push(intersection_ty); + } + if is_new_dependency { dependencies.push(blas); } @@ -287,6 +335,8 @@ pub(crate) fn build_acceleration_structures( build_command.tlas_s_built.push(TlasBuild { tlas: tlas.clone(), dependencies, + max_intersection_idx, + required_intersection_types, }); if instance_count > tlas.max_instance_count { @@ -523,10 +573,14 @@ impl CommandBufferMutable { .tlas .dependencies .write() - .clone_from(&tlas_build.dependencies) + .clone_from(&tlas_build.dependencies); + *tlas_build.tlas.max_intersection_index.write() = + tlas_build.max_intersection_idx; + *tlas_build.tlas.required_intersection_types.write() = + tlas_build.required_intersection_types.clone(); } } - AsAction::UseTlas(tlas) => { + AsAction::BindTlas(tlas) => { let tlas_build_index = tlas.built_index.read(); let dependencies = tlas.dependencies.read(); @@ -550,6 +604,55 @@ impl CommandBufferMutable { blas.try_raw(snatch_guard)?; } } + AsAction::TraceTlas(tlas, intersection_types) => { + let current_max = tlas.max_intersection_index.read(); + + let max_intersection_len = u32::try_from(intersection_types.len()) + .expect("should be smaller than a u32"); + + if let Some(current_max) = *current_max { + if current_max >= max_intersection_len { + return Err(ValidateAsActionsError::TlasIntersectionInvalid( + tlas.error_ident(), + current_max, + max_intersection_len, + )); + } + } + drop(current_max); + + let required_intersection_types = tlas.required_intersection_types.read(); + + for intersection_ty in required_intersection_types.iter() { + let Ok(index) = usize::try_from(intersection_ty.index) else { + return Err( + ValidateAsActionsError::TlasInstancesIntersectionIndicesDiffer( + tlas.error_ident(), + intersection_ty.required_intersection_ty, + intersection_ty.index, + None, + ), + ); + }; + match intersection_types.get(index) { + Some(ty) => { + if *ty != intersection_ty.required_intersection_ty { + return Err(ValidateAsActionsError::TlasInstancesIntersectionIndicesDiffer(tlas.error_ident(), intersection_ty.required_intersection_ty, intersection_ty.index, Some(*ty))); + } + } + None => { + return Err( + ValidateAsActionsError::TlasInstancesIntersectionIndicesDiffer( + tlas.error_ident(), + intersection_ty.required_intersection_ty, + intersection_ty.index, + None, + ), + ); + } + } + } + } } } Ok(()) @@ -563,9 +666,11 @@ impl CommandBufferMutable { AsAction::Build(build) => { dependencies.extend(build.blas_s_built.iter().map(Arc::clone)); } - AsAction::UseTlas(tlas) => { + AsAction::BindTlas(tlas) => { dependencies.extend(tlas.dependencies.read().iter().map(Arc::clone)); } + // Any tlas traced against must also be bound. + AsAction::TraceTlas(..) => {} } } diff --git a/wgpu-core/src/command/ray_tracing_pass.rs b/wgpu-core/src/command/ray_tracing_pass.rs new file mode 100644 index 000000000..1fb424ea5 --- /dev/null +++ b/wgpu-core/src/command/ray_tracing_pass.rs @@ -0,0 +1,992 @@ +use core::{convert::Infallible, fmt}; + +use alloc::{borrow::Cow, boxed::Box, sync::Arc, vec::Vec}; + +use thiserror::Error; +use wgt::{ + error::{ErrorType, WebGpuError}, + BufferAddress, DynamicOffset, +}; + +use crate::{ + api_log, + binding_model::{BindError, BindGroup, ImmediateUploadError, LateMinBufferBindingSizeMismatch}, + command::{ + bind::{Binder, BinderError}, + memory_init::{fixup_discarded_surfaces, SurfacesInDiscardState}, + pass::{self, flush_bindings_helper, ImmediateState}, + pass_base, pass_try, + ray_tracing_pass_commands::ArcRayTracingCommand, + ArcCommand, BasePass, BindGroupStateChange, CommandEncoder, CommandEncoderError, + DebugGroupError, EncoderStateError, EncodingState, InnerCommandEncoder, MapPassErr, + PassErrorScope, PassStateError, StateChange, + }, + device::{Device, DeviceError, MissingDownlevelFlags, MissingFeatures}, + hal_label, id, impl_resource_type, + ray_tracing::AsAction, + ray_tracing_pipeline::RayTracingPipeline, + resource::{ + DestroyedResourceError, InvalidOrDestroyedResourceError, InvalidResourceError, Labeled, + MissingBufferUsageError, ParentDevice, + }, + track::{ResourceUsageCompatibilityError, Tracker}, + Label, +}; + +pub type RayTracingBasePass = BasePass; + +/// Very similar to [`super::compute::ComputePass`] +pub struct RayTracingPass { + /// All pass data & records is stored here. + base: RayTracingBasePass, + + /// Parent command encoder that this pass records commands into. + /// + /// Implications are the same as [`super::compute::ComputePass::parent`] + parent: Option>, + + device: Arc, + + current_bind_groups: BindGroupStateChange, + current_pipeline: StateChange>, +} + +impl_resource_type!(RayTracingPass); + +impl crate::storage::StorageItem for RayTracingPass { + type Marker = id::markers::RayTracingPassEncoder; +} + +impl fmt::Debug for RayTracingPass { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.parent { + Some(ref cmd_enc) => { + write!(f, "RayTracingPass {{ parent: {} }}", cmd_enc.error_ident()) + } + None => write!(f, "RayTracingPass {{ parent: None }}"), + } + } +} + +impl RayTracingPass { + /// If the parent command encoder is invalid, the returned pass will be invalid. + fn new( + parent: Arc, + desc: RayTracingPassDescriptor, + ) -> Result { + parent + .device + .require_features(wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES)?; + + let RayTracingPassDescriptor { label } = desc; + + Ok(Self { + base: BasePass::new(&label), + device: parent.device.clone(), + parent: Some(parent), + + current_bind_groups: BindGroupStateChange::new(), + current_pipeline: StateChange::new(), + }) + } + + fn new_invalid(parent: Arc, label: &Label, err: RayTracingPassError) -> Self { + Self { + base: BasePass::new_invalid(label, err), + device: parent.device.clone(), + parent: Some(parent), + current_bind_groups: BindGroupStateChange::new(), + current_pipeline: StateChange::new(), + } + } + + #[inline] + pub fn label(&self) -> Option<&str> { + self.base.label.as_deref() + } + + pub fn set_bind_group( + &mut self, + index: u32, + bind_group: Option>, + offsets: &[DynamicOffset], + ) { + if let Err(err) = self.set_bind_group_inner(index, bind_group, offsets) { + self.device + .handle_error(err, self.label(), "RayTracingPass::set_bind_group"); + } + } + + pub fn set_bind_group_inner( + &mut self, + index: u32, + bind_group: Option>, + offsets: &[DynamicOffset], + ) -> Result<(), PassStateError> { + let scope = PassErrorScope::SetBindGroup; + + // This statement will return an error if the pass is ended. It's + // important the error check comes before the early-out for + // `set_and_check_redundant`. + let base = pass_base!(self, scope); + + if self.current_bind_groups.set_and_check_redundant( + &bind_group, + index, + &mut base.dynamic_offsets, + offsets, + ) { + return Ok(()); + } + + let bind_group = if let Some(bind_group) = bind_group { + pass_try!(base, scope, bind_group.check_is_valid()); + Some(bind_group) + } else { + None + }; + + base.commands.push(ArcRayTracingCommand::SetBindGroup { + index, + num_dynamic_offsets: offsets.len(), + bind_group, + }); + + Ok(()) + } + + pub fn set_immediates_inner(&mut self, offset: u32, data: &[u8]) -> Result<(), PassStateError> { + let scope = PassErrorScope::SetImmediate; + let base = pass_base!(self, scope); + + pass_try!( + base, + scope, + pass::validate_immediates_alignment(offset, data.len()) + ); + + base.commands.push(ArcRayTracingCommand::SetImmediate { + offset, + data: data + .chunks_exact(size_of::()) + .map(|ck| u32::from_le_bytes(ck.try_into().unwrap())) + .collect(), + }); + + Ok(()) + } + pub fn set_immediates(&mut self, offset: u32, data: &[u8]) { + if let Err(err) = self.set_immediates_inner(offset, data) { + self.device + .handle_error(err, self.label(), "RayTracingPass::set_immediates"); + } + } +} + +#[derive(Clone, Debug, Default)] +pub struct RayTracingPassDescriptor<'a> { + pub label: Label<'a>, +} + +#[derive(Clone, Debug, Error)] +#[non_exhaustive] +pub enum TraceRayError { + #[error("Ray tracing pipeline must be set")] + MissingPipeline(pass::MissingPipeline), + #[error(transparent)] + IncompatibleBindGroup(#[from] Box), + #[error("Trace ray size ({current:?}) must be less or equal to {limit:?}")] + InvalidDimensionSize { current: [u32; 3], limit: [u32; 3] }, + #[error("The total count of rays invocations ({current:?}) must be less or equal to {limit}")] + TooManyTotal { current: u32, limit: u32 }, + #[error(transparent)] + BindingSizeTooSmall(#[from] LateMinBufferBindingSizeMismatch), + #[error("Not all immediate data required by the pipeline has been set via set_immediates (missing byte ranges: {missing})")] + MissingImmediateData { + missing: naga::valid::ImmediateSlots, + }, +} + +impl WebGpuError for TraceRayError { + fn webgpu_error_type(&self) -> ErrorType { + ErrorType::Validation + } +} + +/// Error encountered when performing a ray tracing pass. +#[derive(Clone, Debug, Error)] +pub enum RayTracingPassErrorInner { + #[error(transparent)] + Device(#[from] DeviceError), + #[error(transparent)] + EncoderState(#[from] EncoderStateError), + #[error("Parent encoder is invalid")] + InvalidParentEncoder, + #[error(transparent)] + DebugGroupError(#[from] DebugGroupError), + #[error(transparent)] + BindGroupIndexOutOfRange(#[from] pass::BindGroupIndexOutOfRange), + #[error(transparent)] + DestroyedResource(#[from] DestroyedResourceError), + #[error("Indirect buffer offset {0:?} is not a multiple of 4")] + UnalignedIndirectBufferOffset(BufferAddress), + #[error("Indirect buffer uses bytes {offset}..{end_offset} which overruns indirect buffer of size {buffer_size}")] + IndirectBufferOverrun { + offset: u64, + end_offset: u64, + buffer_size: u64, + }, + #[error(transparent)] + ResourceUsageCompatibility(#[from] ResourceUsageCompatibilityError), + #[error(transparent)] + MissingBufferUsage(#[from] MissingBufferUsageError), + #[error(transparent)] + TraceRay(#[from] TraceRayError), + #[error(transparent)] + Bind(#[from] BindError), + #[error(transparent)] + ImmediateData(#[from] ImmediateUploadError), + #[error("Immediate data offset must be aligned to 4 bytes")] + ImmediateOffsetAlignment, + #[error("Immediate data size must be aligned to 4 bytes")] + ImmediateDataizeAlignment, + #[error("Ran out of immediate data space. Don't set 4gb of immediates per RayTracingPass.")] + ImmediateOutOfMemory, + #[error(transparent)] + MissingFeatures(#[from] MissingFeatures), + #[error(transparent)] + MissingDownlevelFlags(#[from] MissingDownlevelFlags), + #[error("The ray tracing pass has already been ended and no further commands can be recorded")] + PassEnded, + #[error(transparent)] + InvalidResource(#[from] InvalidResourceError), +} + +impl From for RayTracingPassErrorInner { + fn from(error: InvalidOrDestroyedResourceError) -> Self { + match error { + InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e), + InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e), + } + } +} + +/// Error encountered when performing a ray tracing pass, stored for later reporting +/// when encoding ends. +#[derive(Clone, Debug, Error)] +#[error("{scope}")] +pub struct RayTracingPassError { + pub scope: PassErrorScope, + #[source] + pub(super) inner: Box, +} + +impl From for RayTracingPassErrorInner { + fn from(value: pass::MissingPipeline) -> Self { + Self::TraceRay(TraceRayError::MissingPipeline(value)) + } +} + +impl MapPassErr for E +where + E: Into, +{ + fn map_pass_err(self, scope: PassErrorScope) -> RayTracingPassError { + RayTracingPassError { + scope, + inner: Box::new(self.into()), + } + } +} + +impl WebGpuError for RayTracingPassError { + fn webgpu_error_type(&self) -> ErrorType { + match self.inner.as_ref() { + RayTracingPassErrorInner::Device(e) => e.webgpu_error_type(), + RayTracingPassErrorInner::EncoderState(e) => e.webgpu_error_type(), + RayTracingPassErrorInner::DebugGroupError(e) => e.webgpu_error_type(), + RayTracingPassErrorInner::DestroyedResource(e) => e.webgpu_error_type(), + RayTracingPassErrorInner::ResourceUsageCompatibility(e) => e.webgpu_error_type(), + RayTracingPassErrorInner::MissingBufferUsage(e) => e.webgpu_error_type(), + RayTracingPassErrorInner::TraceRay(e) => e.webgpu_error_type(), + RayTracingPassErrorInner::Bind(e) => e.webgpu_error_type(), + RayTracingPassErrorInner::ImmediateData(e) => e.webgpu_error_type(), + RayTracingPassErrorInner::MissingFeatures(e) => e.webgpu_error_type(), + RayTracingPassErrorInner::MissingDownlevelFlags(e) => e.webgpu_error_type(), + RayTracingPassErrorInner::InvalidResource(e) => e.webgpu_error_type(), + + RayTracingPassErrorInner::InvalidParentEncoder + | RayTracingPassErrorInner::BindGroupIndexOutOfRange { .. } + | RayTracingPassErrorInner::UnalignedIndirectBufferOffset(_) + | RayTracingPassErrorInner::IndirectBufferOverrun { .. } + | RayTracingPassErrorInner::ImmediateOffsetAlignment + | RayTracingPassErrorInner::ImmediateDataizeAlignment + | RayTracingPassErrorInner::ImmediateOutOfMemory + | RayTracingPassErrorInner::PassEnded => ErrorType::Validation, + } + } +} + +struct State<'scope, 'snatch_guard, 'cmd_enc> { + pipeline: Option>, + + pass: pass::PassState<'scope, 'snatch_guard, 'cmd_enc>, + + intermediate_trackers: Tracker, +} + +impl<'scope, 'snatch_guard, 'cmd_enc> State<'scope, 'snatch_guard, 'cmd_enc> { + fn is_ready(&self) -> Result<(), TraceRayError> { + if let Some(pipeline) = self.pipeline.as_ref() { + self.pass.binder.check_compatibility(pipeline.as_ref())?; + self.pass.binder.check_late_buffer_bindings()?; + if !self + .pass + .immediate_state + .immediate_slots_set + .contains(pipeline.immediate_slots_required) + { + return Err(TraceRayError::MissingImmediateData { + missing: pipeline + .immediate_slots_required + .difference(self.pass.immediate_state.immediate_slots_set), + }); + } + Ok(()) + } else { + Err(TraceRayError::MissingPipeline(pass::MissingPipeline)) + } + } + + fn flush_immediates(&mut self) { + let pipeline = self.pipeline.as_ref().unwrap(); + let layout = pipeline.layout().unwrap(); + self.pass + .immediate_state + .flush_immediates(layout, self.pass.base.raw_encoder); + } + + /// Flush binding state in preparation for a trace rays call. + /// + /// This behaves almost the same as a compute pass' equivalent + /// function, but also adds a `AsAction::TraceTlas` as trace ray + /// calls need a bit more validation. + /// + /// This differs from a render pass, which the equivalent method + /// on compute pass' state discuss more. + fn flush_bindings(&mut self) -> Result<(), RayTracingPassErrorInner> { + for bind_group in self.pass.binder.list_active() { + unsafe { self.pass.scope.merge_bind_group(&bind_group.used)? }; + } + // For ray tracing passes, usage scopes are associated with each trace + // ray (in the same way as compute passes) and not with the pass as a + // whole. However, because the cost of creating and dropping + // `UsageScope`s is significant (even with the pool), we add and then + // remove usage from a single usage scope. + + let intersection_types = self.pipeline.as_ref().unwrap().intersection_types()?; + + for bind_group in self.pass.binder.list_active() { + self.intermediate_trackers + .set_and_remove_from_usage_scope_sparse(&mut self.pass.scope, &bind_group.used); + + for tlas in bind_group.used.acceleration_structures.into_iter() { + self.pass.base.as_actions.push(AsAction::TraceTlas( + tlas.clone(), + intersection_types.clone(), + )); + } + } + + flush_bindings_helper(&mut self.pass)?; + + CommandEncoder::drain_barriers( + self.pass.base.raw_encoder, + &mut self.intermediate_trackers, + self.pass.base.snatch_guard, + ); + Ok(()) + } +} + +// Ray tracing pass commands + +impl RayTracingPass { + pub fn set_pipeline(&mut self, pipeline: Arc) { + if let Err(err) = self.set_pipeline_inner(pipeline) { + self.device + .handle_error(err, self.label(), "RayTracingPass::set_pipeline"); + } + } + pub fn set_pipeline_inner( + &mut self, + pipeline: Arc, + ) -> Result<(), PassStateError> { + let scope = PassErrorScope::SetPipelineRayTracing; + + let redundant = self.current_pipeline.set_and_check_redundant(&pipeline); + + // This statement will return an error if the pass is ended. + // Its important the error check comes before the early-out for `redundant`. + let base = pass_base!(self, scope); + + if redundant { + return Ok(()); + } + + pass_try!(base, scope, pipeline.check_valid()); + + base.commands + .push(ArcRayTracingCommand::SetPipeline(pipeline)); + + Ok(()) + } + pub fn end_inner(&mut self) -> Result<(), EncoderStateError> { + profiling::scope!( + "CommandEncoder::run_ray_tracing_pass {}", + self.base.label.as_deref().unwrap_or("") + ); + + let cmd_enc = self.parent.take().ok_or(EncoderStateError::Ended)?; + let mut cmd_buf_data = cmd_enc.data.lock(); + + cmd_buf_data.unlock_encoder()?; + + let base = self.base.take(); + + if let Err(RayTracingPassError { inner, scope: _ }) = &base { + if let RayTracingPassErrorInner::EncoderState( + err @ (EncoderStateError::Locked | EncoderStateError::Ended), + ) = inner.as_ref() + { + // Most encoding errors are detected and raised within `finish()`. + // + // However, we raise a validation error here if the pass was opened + // within another pass, or on a finished encoder. The latter is + // particularly important, because in that case reporting errors via + // `CommandEncoder::finish` is not possible. + return Err(err.clone()); + } + } + + cmd_buf_data.push_with(|| -> Result<_, RayTracingPassError> { + Ok(ArcCommand::RunRayTracingPass { pass: base? }) + }) + } + + pub fn end(&mut self) { + if let Err(err) = self.end_inner() { + self.device + .handle_error(err, self.label(), "RayTracingPass::end"); + } + } + + pub fn push_debug_group_inner( + &mut self, + label: &str, + color: u32, + ) -> Result<(), PassStateError> { + let base = pass_base!(self, PassErrorScope::PushDebugGroup); + + let bytes = label.as_bytes(); + base.string_data.extend_from_slice(bytes); + + base.commands.push(ArcRayTracingCommand::PushDebugGroup { + color, + len: bytes.len(), + }); + + Ok(()) + } + + pub fn push_debug_group(&mut self, label: &str, color: u32) { + if let Err(err) = self.push_debug_group_inner(label, color) { + self.device + .handle_error(err, self.label(), "RayTracingPass::push_debug_group"); + } + } + + pub fn pop_debug_group_inner(&mut self) -> Result<(), PassStateError> { + let base = pass_base!(self, PassErrorScope::PopDebugGroup); + + base.commands.push(ArcRayTracingCommand::PopDebugGroup); + + Ok(()) + } + + pub fn pop_debug_group(&mut self) { + if let Err(err) = self.pop_debug_group_inner() { + self.device + .handle_error(err, self.label(), "RayTracingPass::pop_debug_group"); + } + } + + pub fn insert_debug_marker_inner( + &mut self, + label: &str, + color: u32, + ) -> Result<(), PassStateError> { + let base = pass_base!(self, PassErrorScope::InsertDebugMarker); + + let bytes = label.as_bytes(); + base.string_data.extend_from_slice(bytes); + + base.commands.push(ArcRayTracingCommand::InsertDebugMarker { + color, + len: bytes.len(), + }); + + Ok(()) + } + + pub fn insert_debug_marker(&mut self, label: &str, color: u32) { + if let Err(err) = self.insert_debug_marker_inner(label, color) { + self.device + .handle_error(err, self.label(), "RayTracingPass::insert_debug_marker"); + } + } + + pub fn trace_rays_inner( + &mut self, + count_x: u32, + count_y: u32, + count_z: u32, + ) -> Result<(), PassStateError> { + let scope = PassErrorScope::TraceRays; + + pass_base!(self, scope) + .commands + .push(ArcRayTracingCommand::TraceRays([count_x, count_y, count_z])); + + Ok(()) + } + + pub fn trace_rays(&mut self, count_x: u32, count_y: u32, count_z: u32) { + if let Err(err) = self.trace_rays_inner(count_x, count_y, count_z) { + self.device + .handle_error(err, self.label(), "RayTracingPass::trace_rays"); + } + } +} + +impl CommandEncoder { + pub fn begin_ray_tracing_pass_inner( + self: &Arc, + desc: &RayTracingPassDescriptor<'_>, + ) -> (RayTracingPass, Option) { + use EncoderStateError as SErr; + + let label = desc.label.as_deref().map(Cow::Borrowed); + + let scope = PassErrorScope::Pass; + + let mut cmd_buf_data = self.data.lock(); + + match cmd_buf_data.lock_encoder() { + Ok(()) => { + drop(cmd_buf_data); + if let Err(err) = self.device.check_is_valid() { + return ( + RayTracingPass::new_invalid(self.clone(), &label, err.map_pass_err(scope)), + None, + ); + } + + let pass = match RayTracingPass::new( + self.clone(), + RayTracingPassDescriptor { + label: label.clone(), + }, + ) { + Ok(pass) => pass, + Err(err) => { + return ( + RayTracingPass::new_invalid( + self.clone(), + &label, + err.map_pass_err(scope), + ), + None, + ); + } + }; + + (pass, None) + } + Err(err @ SErr::Locked) => { + // Attempting to open a new pass while the encoder is locked + // invalidates the encoder, but does not generate a validation + // error. + cmd_buf_data.invalidate(err.clone()); + drop(cmd_buf_data); + ( + RayTracingPass::new_invalid(self.clone(), &label, err.map_pass_err(scope)), + None, + ) + } + Err(err @ (SErr::Ended | SErr::Submitted)) => { + // Attempting to open a new pass after the encode has ended + // generates an immediate validation error. + drop(cmd_buf_data); + ( + RayTracingPass::new_invalid( + self.clone(), + &label, + err.clone().map_pass_err(scope), + ), + Some(err.into()), + ) + } + Err(err @ SErr::Invalid) => { + // Passes can be opened even on an invalid encoder. Such passes + // are even valid, but since there's no visible side-effect of + // the pass being valid and there's no point in storing recorded + // commands that will ultimately be discarded, we open an + // invalid pass to save that work. + drop(cmd_buf_data); + ( + RayTracingPass::new_invalid(self.clone(), &label, err.map_pass_err(scope)), + None, + ) + } + Err(SErr::Unlocked) => { + unreachable!("lock_encoder cannot fail due to the encoder being unlocked") + } + } + } + + pub fn begin_ray_tracing_pass( + self: &Arc, + desc: &RayTracingPassDescriptor<'_>, + ) -> RayTracingPass { + let (pass, err) = self.begin_ray_tracing_pass_inner(desc); + if let Some(err) = err { + self.device + .handle_error(err, pass.label(), "CommandEncoder::begin_ray_tracing_pass"); + } + pass + } +} + +pub(super) fn encode_ray_tracing_pass( + parent_state: &mut EncodingState, + mut base: BasePass, +) -> Result<(), RayTracingPassError> { + let pass_scope = PassErrorScope::Pass; + + let device = parent_state.device; + + // We automatically keep extending command buffers over time, and because + // we want to insert a command buffer _before_ what we're about to record, + // we need to make sure to close the previous one. + parent_state + .raw_encoder + .close_if_open() + .map_pass_err(pass_scope)?; + let raw_encoder = parent_state + .raw_encoder + .open_pass(base.label.as_deref()) + .map_pass_err(pass_scope)?; + + let mut debug_scope_depth = 0; + + let mut state = State { + pipeline: None, + + pass: pass::PassState { + base: EncodingState { + device, + raw_encoder, + tracker: parent_state.tracker, + buffer_memory_init_actions: parent_state.buffer_memory_init_actions, + texture_memory_actions: parent_state.texture_memory_actions, + as_actions: parent_state.as_actions, + temp_resources: parent_state.temp_resources, + indirect_draw_validation_resources: parent_state.indirect_draw_validation_resources, + snatch_guard: parent_state.snatch_guard, + debug_scope_depth: &mut debug_scope_depth, + query_set_writes: parent_state.query_set_writes, + deferred_query_set_resolves: parent_state.deferred_query_set_resolves, + }, + binder: Binder::new(), + temp_offsets: Vec::new(), + dynamic_offset_count: 0, + pending_discard_init_fixups: SurfacesInDiscardState::new(), + scope: device.new_usage_scope(), + string_offset: 0, + + immediate_state: ImmediateState::default(), + }, + + intermediate_trackers: Tracker::new( + device.ordered_buffer_usages, + device.ordered_texture_usages, + ), + }; + + let indices = &device.tracker_indices; + state + .pass + .base + .tracker + .buffers + .set_size(indices.buffers.size()); + state + .pass + .base + .tracker + .textures + .set_size(indices.textures.size()); + + let hal_desc = hal::RayTracingPassDescriptor { + label: hal_label(base.label.as_deref(), device.instance_flags), + }; + + unsafe { + state + .pass + .base + .raw_encoder + .begin_ray_tracing_pass(&hal_desc); + } + + for command in base.commands.drain(..) { + match command { + ArcRayTracingCommand::SetBindGroup { + index, + num_dynamic_offsets, + bind_group, + } => { + let scope = PassErrorScope::SetBindGroup; + pass::set_bind_group::( + &mut state.pass, + device, + &base.dynamic_offsets, + index, + num_dynamic_offsets, + bind_group, + false, + ) + .map_pass_err(scope)?; + } + ArcRayTracingCommand::SetPipeline(pipeline) => { + let scope = PassErrorScope::SetPipelineRayTracing; + set_pipeline(&mut state, device, pipeline).map_pass_err(scope)?; + } + ArcRayTracingCommand::SetImmediate { offset, data } => { + let scope = PassErrorScope::SetImmediate; + state + .pass + .immediate_state + .set_immediates::( + &state.pass.base.device.limits, + offset, + &data, + ) + .map_pass_err(scope)?; + } + ArcRayTracingCommand::PushDebugGroup { color: _, len } => { + pass::push_debug_group(&mut state.pass, &base.string_data, len); + } + ArcRayTracingCommand::PopDebugGroup => { + let scope = PassErrorScope::PopDebugGroup; + pass::pop_debug_group::(&mut state.pass) + .map_pass_err(scope)?; + } + ArcRayTracingCommand::InsertDebugMarker { color: _, len } => { + pass::insert_debug_marker(&mut state.pass, &base.string_data, len); + } + ArcRayTracingCommand::TraceRays(groups) => { + let scope = PassErrorScope::TraceRays; + trace_rays(&mut state, groups, device).map_pass_err(scope)?; + } + } + } + + if *state.pass.base.debug_scope_depth > 0 { + Err( + RayTracingPassErrorInner::DebugGroupError(DebugGroupError::MissingPop) + .map_pass_err(pass_scope), + )?; + } + + unsafe { + state.pass.base.raw_encoder.end_ray_tracing_pass(); + } + + let State { + pass: pass::PassState { + pending_discard_init_fixups, + .. + }, + intermediate_trackers, + .. + } = state; + + // Stop the current command encoder. + parent_state.raw_encoder.close().map_pass_err(pass_scope)?; + + // Create a new command encoder, which we will insert _before_ the body of the ray tracing pass. + // + // Use that buffer to insert barriers and clear discarded images. + let transit = parent_state + .raw_encoder + .open_pass(hal_label( + Some("(wgpu internal) Pre Pass"), + device.instance_flags, + )) + .map_pass_err(pass_scope)?; + // If the ray tracing pass reads any surfaces that were discarded by a previous + // render pass in the same command buffer, initialize them. + fixup_discarded_surfaces( + pending_discard_init_fixups.into_iter(), + transit, + &mut parent_state.tracker.textures, + device, + parent_state.snatch_guard, + ); + CommandEncoder::insert_barriers_from_tracker( + transit, + parent_state.tracker, + &intermediate_trackers, + parent_state.snatch_guard, + ); + // Close the command encoder, and swap it with the previous. + parent_state + .raw_encoder + .close_and_swap() + .map_pass_err(pass_scope)?; + + Ok(()) +} + +fn set_pipeline( + state: &mut State, + device: &Arc, + pipeline: Arc, +) -> Result<(), RayTracingPassErrorInner> { + pipeline.same_device(device)?; + + state.pipeline = Some(pipeline.clone()); + + let pipeline = state + .pass + .base + .tracker + .ray_tracing_pipelines + .insert_single(pipeline) + .clone(); + + unsafe { + state + .pass + .base + .raw_encoder + .set_ray_tracing_pipeline(pipeline.raw()?); + } + + // Rebind resources + let pipeline_layout = pipeline.layout()?; + pass::change_pipeline_layout::( + &mut state.pass, + pipeline_layout, + &pipeline.late_sized_buffer_groups, + ) +} + +fn trace_rays( + state: &mut State, + dims: [u32; 3], + device: &Device, +) -> Result<(), RayTracingPassErrorInner> { + api_log!("RayTracingPass::trace_rays {dims:?}"); + + state.is_ready()?; + + state.flush_bindings()?; + state.flush_immediates(); + + let limits = &state.pass.base.device.limits; + + // `saturating_mul` is fine here as it is the limit, so a lower limit if it would overflow is just a + // slightly greater restriction. + let dim_size_limit = [ + limits + .max_compute_workgroup_size_x + .saturating_mul(limits.max_compute_workgroups_per_dimension), + limits + .max_compute_workgroup_size_y + .saturating_mul(limits.max_compute_workgroups_per_dimension), + limits + .max_compute_workgroup_size_z + .saturating_mul(limits.max_compute_workgroups_per_dimension), + ]; + + if dims[0] > dim_size_limit[0] { + return Err(RayTracingPassErrorInner::TraceRay( + TraceRayError::InvalidDimensionSize { + current: dims, + limit: dim_size_limit, + }, + )); + } + + if dims[1] > dim_size_limit[1] { + return Err(RayTracingPassErrorInner::TraceRay( + TraceRayError::InvalidDimensionSize { + current: dims, + limit: dim_size_limit, + }, + )); + } + + if dims[2] > dim_size_limit[2] { + return Err(RayTracingPassErrorInner::TraceRay( + TraceRayError::InvalidDimensionSize { + current: dims, + limit: dim_size_limit, + }, + )); + } + + let tot_rays = dims[0] + .checked_mul(dims[1]) + .and_then(|tmp| tmp.checked_mul(dims[2])); + + if tot_rays.is_none_or(|tot_rays| tot_rays > limits.max_ray_dispatch_count) { + return Err(RayTracingPassErrorInner::TraceRay( + TraceRayError::TooManyTotal { + current: tot_rays.unwrap_or(u32::MAX), + limit: limits.max_ray_dispatch_count, + }, + )); + } + + let current_pipeline = state.pipeline.as_ref().unwrap(); + let shader_binding_data = current_pipeline.shader_binding_data()?; + + unsafe { + state.pass.base.raw_encoder.trace_rays( + dims, + hal::PipelineGroupData { + buffer: shader_binding_data.raw.as_ref(), + offset: 0, + stride: device.alignments.ray_tracing_pipeline_group_data_size as _, + count: 1, + }, + hal::PipelineGroupData { + buffer: shader_binding_data.raw.as_ref(), + offset: shader_binding_data.miss_offset, + stride: device.alignments.ray_tracing_pipeline_group_data_size as _, + count: 1, + }, + hal::PipelineGroupData { + buffer: shader_binding_data.raw.as_ref(), + offset: shader_binding_data.intersection_offset, + stride: device.alignments.ray_tracing_pipeline_group_data_size as _, + count: shader_binding_data.num_intersection_groups as _, + }, + ); + } + Ok(()) +} diff --git a/wgpu-core/src/command/ray_tracing_pass_commands.rs b/wgpu-core/src/command/ray_tracing_pass_commands.rs new file mode 100644 index 000000000..e03e5dd98 --- /dev/null +++ b/wgpu-core/src/command/ray_tracing_pass_commands.rs @@ -0,0 +1,47 @@ +#[cfg(feature = "serde")] +use crate::command::serde_object_reference_struct; +use crate::command::{ArcReferences, ReferenceType}; +use alloc::vec::Vec; + +#[cfg(feature = "serde")] +use macro_rules_attribute::apply; + +/// cbindgen:ignore +#[derive(Clone, Debug)] +#[cfg_attr(feature = "serde", apply(serde_object_reference_struct))] +pub enum RayTracingCommand { + SetBindGroup { + index: u32, + num_dynamic_offsets: usize, + bind_group: Option, + }, + + SetPipeline(R::RayTracingPipeline), + + /// Set a range of immediates to values stored in `immediates_data`. + SetImmediate { + /// The byte offset within the immediate data storage to write to. This + /// must be a multiple of four. + offset: u32, + + /// The immediate data to be written. + data: Vec, + }, + + TraceRays([u32; 3]), + + PushDebugGroup { + color: u32, + len: usize, + }, + + PopDebugGroup, + + InsertDebugMarker { + color: u32, + len: usize, + }, +} + +/// cbindgen:ignore +pub type ArcRayTracingCommand = RayTracingCommand; diff --git a/wgpu-core/src/device/queue.rs b/wgpu-core/src/device/queue.rs index 86800bd8d..48edf865d 100644 --- a/wgpu-core/src/device/queue.rs +++ b/wgpu-core/src/device/queue.rs @@ -30,6 +30,7 @@ use crate::{ init_tracker::{has_copy_partial_init_tracker_coverage, TextureInitRange}, lock::{rank, Mutex, MutexGuard, RwLock, RwLockWriteGuard}, ray_tracing::{BlasCompactReadyPendingClosure, CompactBlasError}, + ray_tracing_pipeline, resource::{ Blas, BlasCompactState, BlasDescriptor, BlasState, Buffer, BufferAccessError, BufferMapState, DestroyedBuffer, DestroyedQuerySet, DestroyedResourceError, @@ -351,6 +352,9 @@ pub(crate) struct EncoderInFlight { pub(crate) pending_textures: FastHashMap>, /// These are the BLASes that have been tracked by `PendingWrites`. pub(crate) pending_blas_s: FastHashMap>, + /// These are the shader binding data buffers that have been tracked by `PendingWrites`. + /// Only need to keep these live while the writes wait. + _pending_shader_binding_data: Vec>, } /// A private command encoder for writes made directly on the device @@ -393,6 +397,9 @@ pub(crate) struct PendingWrites { dst_buffers: FastHashMap>, dst_textures: FastHashMap>, copied_blas_s: FastHashMap>, + /// Buffers of shader binding data that have been written to when creating their + /// ray tracing pipelines. + written_shader_binding_data: Vec>, instance_flags: wgt::InstanceFlags, /// Staging buffers that are the source of a copy recorded in @@ -444,6 +451,7 @@ impl PendingWrites { instance_flags, hoisted_staging_buffers: Vec::new(), hoisted_buffer_barriers: Vec::new(), + written_shader_binding_data: Vec::new(), } } @@ -462,6 +470,10 @@ impl PendingWrites { .insert(blas.tracker_index(), blas.clone()); } + pub fn use_shader_binding_data(&mut self, sbd: &Arc) { + self.written_shader_binding_data.push(sbd.clone()) + } + pub fn contains_buffer(&self, buffer: &Arc) -> bool { self.dst_buffers.contains_key(&buffer.tracker_index()) } @@ -604,6 +616,7 @@ impl PendingWrites { let pending_buffers = mem::take(&mut self.dst_buffers); let pending_textures = mem::take(&mut self.dst_textures); let pending_blas_s = mem::take(&mut self.copied_blas_s); + let pending_shader_binding_data = mem::take(&mut self.written_shader_binding_data); let cmd_buf = unsafe { self.command_encoder.end_encoding() } .map_err(|e| device.handle_hal_error(e))?; @@ -630,6 +643,7 @@ impl PendingWrites { pending_buffers, pending_textures, pending_blas_s, + _pending_shader_binding_data: pending_shader_binding_data, }; let staging_buffers = self.record_hoisted_barriers(&mut encoder, snatch_guard)?; @@ -642,6 +656,7 @@ impl PendingWrites { self.dst_buffers.clear(); self.dst_textures.clear(); self.copied_blas_s.clear(); + self.written_shader_binding_data.clear(); Ok(None) } } @@ -1830,6 +1845,7 @@ impl Queue { pending_buffers: FastHashMap::default(), pending_textures: FastHashMap::default(), pending_blas_s: FastHashMap::default(), + _pending_shader_binding_data: Vec::new(), }); } } @@ -2148,8 +2164,7 @@ impl Queue { self.device.check_is_valid()?; - self.device - .require_features(wgpu_types::Features::EXPERIMENTAL_RAY_QUERY)?; + self.device.require_acceleration_structures()?; blas.check_is_valid()?; self.same_device_as(blas.as_ref())?; diff --git a/wgpu-core/src/device/ray_tracing.rs b/wgpu-core/src/device/ray_tracing.rs index 286c6250a..863235581 100644 --- a/wgpu-core/src/device/ray_tracing.rs +++ b/wgpu-core/src/device/ray_tracing.rs @@ -1,10 +1,13 @@ -use alloc::{sync::Arc, vec::Vec}; +use alloc::{string::ToString, sync::Arc, vec::Vec}; use core::mem::{size_of, ManuallyDrop}; +use crate::device::stage_compiler::StageCompiler; #[cfg(feature = "trace")] use crate::device::trace::{Action, IntoTrace}; -use crate::device::DeviceError; -use crate::resource::ResourceState; +use crate::device::{DeviceError, ENTRYPOINT_FAILURE_ERROR}; +use crate::pipeline::CreatePipelineError; +use crate::ray_tracing_pipeline; +use crate::resource::{ParentDevice, ResourceState}; use crate::{ api_log, device::Device, @@ -21,6 +24,12 @@ use hal::AccelerationStructureTriangleIndices; use wgt::{Features, AABB_GEOMETRY_MIN_STRIDE}; impl Device { + /// Requires any feature that allows acceleration structures as they can be provided by multiple extensions. + pub fn require_acceleration_structures(&self) -> Result<(), crate::device::MissingFeatures> { + self.require_features(Features::EXPERIMENTAL_RAY_QUERY) + .or_else(|_| self.require_features(Features::EXPERIMENTAL_RAY_TRACING_PIPELINES)) + } + pub fn create_blas( self: &Arc, blas_desc: &resource::BlasDescriptor, @@ -52,7 +61,7 @@ impl Device { sizes: wgt::BlasGeometrySizeDescriptors, ) -> Result, CreateBlasError> { self.check_is_valid()?; - self.require_features(Features::EXPERIMENTAL_RAY_QUERY)?; + self.require_acceleration_structures()?; if blas_desc .flags @@ -262,7 +271,7 @@ impl Device { desc: &resource::TlasDescriptor, ) -> Result, CreateTlasError> { self.check_is_valid()?; - self.require_features(Features::EXPERIMENTAL_RAY_QUERY)?; + self.require_acceleration_structures()?; if desc.max_instances > self.limits.max_tlas_instance_count { return Err(CreateTlasError::TooManyInstances( @@ -343,6 +352,265 @@ impl Device { label: desc.label.to_string(), max_instance_count: desc.max_instances, tracking_data: TrackingData::new(self.tracker_indices.tlas_s.clone()), + max_intersection_index: RwLock::new(rank::TLAS_MAX_INTERSECTION_IDX, None), + required_intersection_types: RwLock::new( + rank::TLAS_REQUIRED_INTERSECTION_TYPES, + Vec::new(), + ), })) } + + pub fn create_ray_tracing_pipeline( + self: &Arc, + desc: ray_tracing_pipeline::RayTracingPipelineDescriptor, + ) -> ( + Arc, + Option, + ) { + let (ray_tracing_pipeline, error) = + match self.create_ray_tracing_pipeline_inner(desc.clone()) { + Ok(ray_tracing_pipeline) => (ray_tracing_pipeline, None), + Err(error) => ( + ray_tracing_pipeline::RayTracingPipeline::invalid( + self.clone(), + desc.label.to_string(), + ), + Some(error), + ), + }; + #[cfg(feature = "trace")] + if let Some(ref mut trace) = *self.trace.lock() { + use crate::device::trace::IntoTrace; + trace.add(Action::CreateRayTracingPipeline { + id: ray_tracing_pipeline.to_trace(), + desc: desc.to_trace(), + }); + } + (ray_tracing_pipeline, error) + } + + pub fn create_ray_tracing_pipeline_inner( + self: &Arc, + desc: ray_tracing_pipeline::RayTracingPipelineDescriptor, + ) -> Result, CreatePipelineError> { + use crate::validation; + + self.check_is_valid()?; + self.require_features(Features::EXPERIMENTAL_RAY_TRACING_PIPELINES)?; + + let io = validation::StageIo::default(); + + let is_auto_layout = desc.layout.is_none(); + + // Get the pipeline layout from the desc if it is provided. + let pipeline_layout = match desc.layout { + Some(pipeline_layout) => { + pipeline_layout.same_device(self)?; + Some(pipeline_layout) + } + None => None, + }; + + let mut compiler = StageCompiler::new(self, pipeline_layout.clone(), io, None); + + let ray_generation = { + let stage = validation::ShaderStageForValidation::RayGeneration; + + compiler.compile(&desc.ray_generation, stage)? + }; + + let miss = { + let stage = validation::ShaderStageForValidation::Miss; + + compiler.compile(&desc.miss, stage)? + }; + + if desc.intersections.len() > 1 << 24 { + return Err( + ray_tracing_pipeline::RayTracingPipelineError::TooManyIntersectionGroups( + desc.intersections.len(), + ) + .into(), + ); + } + + if desc.max_recursion_depth > self.limits.max_ray_recursion_depth { + return Err( + ray_tracing_pipeline::RayTracingPipelineError::TooHighRayRecursionDepth( + desc.max_recursion_depth, + self.limits.max_ray_recursion_depth, + ) + .into(), + ); + } + + let mut intersections = Vec::with_capacity(desc.intersections.len()); + let mut compiled_intersections = Vec::with_capacity(desc.intersections.len()); + + for intersection in &desc.intersections { + match intersection { + ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle { + closest_hit, + any_hit, + } => { + let closest_hit = { + let stage = + validation::ShaderStageForValidation::ClosestHit { triangle: true }; + + compiler.compile(closest_hit, stage)? + }; + + let any_hit = match any_hit { + Some(any_hit) => { + let stage = + validation::ShaderStageForValidation::AnyHit { triangle: true }; + + Some(compiler.compile(any_hit, stage)?) + } + None => None, + }; + + compiled_intersections.push((closest_hit, any_hit)); + } + } + } + + for (closest_hit, any_hit) in compiled_intersections.iter() { + intersections.push(hal::RayObjectIntersectionState { + closest_hit: closest_hit.to_hal(), + any_hit: any_hit.as_ref().map(|any| any.to_hal()), + }); + } + + let StageCompiler { resources, .. } = compiler; + + let pipeline_layout = match resources.layout { + validation::BindingLayoutSource::Provided(layout) => layout, + validation::BindingLayoutSource::Derived(entries) => { + self.create_derived_pipeline_layout(entries, resources.immediates.size())? + } + }; + + let late_sized_buffer_groups = Device::make_late_sized_buffer_groups( + &resources.minimum_binding_sizes, + &pipeline_layout, + ); + + let cache = match desc.cache { + Some(cache) => { + cache.same_device(self)?; + Some(cache) + } + None => None, + }; + + let raw = { + let pipeline_desc = hal::RayTracingPipelineDescriptor { + label: desc.label.to_hal(self.instance_flags), + layout: pipeline_layout.raw()?, + ray_generation: ray_generation.to_hal(), + miss: miss.to_hal(), + intersection: &intersections, + max_recursion_depth: desc.max_recursion_depth, + cache: cache.as_ref().map(|it| it.raw()).transpose()?, + }; + unsafe { self.raw().create_ray_tracing_pipeline(&pipeline_desc) }.map_err(|err| { + match err { + hal::PipelineError::Device(error) => { + CreatePipelineError::Device(self.handle_hal_error(error)) + } + hal::PipelineError::Linkage(stage, message) => { + CreatePipelineError::Internal { stage, message } + } + hal::PipelineError::EntryPoint(stage) => CreatePipelineError::Internal { + stage: hal::auxil::map_naga_stage(stage), + message: ENTRYPOINT_FAILURE_ERROR.to_string(), + }, + hal::PipelineError::PipelineConstants(stage, message) => { + CreatePipelineError::PipelineConstants { stage, message } + } + } + })? + }; + + let (shader_modules, intersection_types) = { + let mut shader_modules = Vec::new(); + shader_modules.push(desc.ray_generation.module.clone()); + shader_modules.push(desc.miss.module.clone()); + shader_modules.reserve(desc.intersections.len()); + let mut intersection_types = Vec::with_capacity(desc.intersections.len()); + for intersection in &desc.intersections { + match intersection { + ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle { + closest_hit, + any_hit, + } => { + shader_modules.push(closest_hit.module.clone()); + if let Some(any) = any_hit { + shader_modules.push(any.module.clone()); + } + intersection_types + .push(ray_tracing_pipeline::RayTracingIntersectionType::Triangle); + } + } + } + ( + shader_modules, + Arc::from(intersection_types.into_boxed_slice()), + ) + }; + + // Won't panic because the length of `desc.intersections` is required to be below 2^24 + // (see `CreateRayTracingPipelineError::TooManyIntersectionGroups`) + let shader_binding_data = match ray_tracing_pipeline::ShaderBindingData::from_raw_pipeline( + self.clone(), + raw.as_ref(), + desc.intersections.len(), + ) { + Ok(sbd) => sbd, + Err(e) => { + // We need to destroy the raw ray tracing pipeline first. + unsafe { self.raw().destroy_ray_tracing_pipeline(raw) }; + return Err(e); + } + }; + + let naga::valid::ImmediateUsage::Valid { + slots: immediate_slots_required, + size: _, + } = resources.immediates + else { + unreachable!("Immediates exceeding maxImmediateSize should have been rejected"); + }; + + let pipeline = ray_tracing_pipeline::RayTracingPipeline { + state: ResourceState::Valid(ray_tracing_pipeline::RayTracingPipelineState { + raw: ManuallyDrop::new(raw), + layout: pipeline_layout.clone(), + _shader_modules: shader_modules, + shader_binding_data, + intersection_types, + }), + device: self.clone(), + late_sized_buffer_groups, + immediate_slots_required, + label: desc.label.to_string(), + tracking_data: TrackingData::new(self.tracker_indices.ray_tracing_pipelines.clone()), + }; + + let pipeline = Arc::new(pipeline); + + if is_auto_layout { + for bgl in pipeline_layout.bind_group_layouts.iter() { + let Some(bgl) = bgl else { + continue; + }; + + // `bind_group_layouts` might contain duplicate entries, so we need to ignore the result. + let _ = bgl.exclusive_pipeline.set((&pipeline).into()); + } + } + + Ok(pipeline) + } } diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index febcccaa3..49007d0ec 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -1249,7 +1249,7 @@ impl Device { .usage .intersects(wgt::BufferUsages::BLAS_INPUT | wgt::BufferUsages::TLAS_INPUT) { - self.require_features(wgt::Features::EXPERIMENTAL_RAY_QUERY)?; + self.require_acceleration_structures()?; } if desc.usage.contains(wgt::BufferUsages::INDEX) @@ -2944,7 +2944,7 @@ impl Device { /// Generate information about late-validated buffer bindings for pipelines. //TODO: should this be combined with `get_introspection_bind_group_layouts` in some way? - fn make_late_sized_buffer_groups( + pub(super) fn make_late_sized_buffer_groups( shader_binding_sizes: &FastHashMap, layout: &binding_model::PipelineLayout, ) -> ArrayVec { @@ -3205,11 +3205,12 @@ impl Device { ) } Bt::AccelerationStructure { vertex_return } => { - self.require_features(wgt::Features::EXPERIMENTAL_RAY_QUERY) - .map_err(|e| CreateBindGroupLayoutError::Entry { + self.require_acceleration_structures().map_err(|e| { + CreateBindGroupLayoutError::Entry { binding: entry.binding, error: e.into(), - })?; + } + })?; if vertex_return { self.require_features(wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN) .map_err(|e| CreateBindGroupLayoutError::Entry { @@ -4407,7 +4408,7 @@ impl Device { Ok(layout) } - fn create_derived_pipeline_layout( + pub(super) fn create_derived_pipeline_layout( self: &Arc, mut derived_group_layouts: Box>, immediate_size: u32, diff --git a/wgpu-core/src/device/trace.rs b/wgpu-core/src/device/trace.rs index 6e2d26be8..3b55d7186 100644 --- a/wgpu-core/src/device/trace.rs +++ b/wgpu-core/src/device/trace.rs @@ -171,6 +171,11 @@ pub enum Action<'a, R: ReferenceType> { pipeline: PointerId, index: u32, }, + GetRayTracingPipelineBindGroupLayout { + id: PointerId, + pipeline: PointerId, + index: u32, + }, DropBindGroupLayout(PointerId), CreatePipelineLayout( PointerId, @@ -202,6 +207,11 @@ pub enum Action<'a, R: ReferenceType> { desc: TraceGeneralRenderPipelineDescriptor<'a>, }, DropRenderPipeline(PointerId), + CreateRayTracingPipeline { + id: PointerId, + desc: TraceRayTracingPipelineDescriptor<'a>, + }, + DropRayTracingPipeline(PointerId), CreatePipelineCache { id: PointerId, desc: crate::pipeline::PipelineCacheDescriptor<'a>, @@ -286,3 +296,15 @@ pub type TraceComputePipelineDescriptor<'a> = crate::pipeline::ComputePipelineDe PointerId, PointerId, >; + +/// Not a public API. For use by `player` only. +/// +/// cbindgen:ignore +#[doc(hidden)] +pub type TraceRayTracingPipelineDescriptor<'a> = + crate::ray_tracing_pipeline::RayTracingPipelineDescriptor< + 'a, + PointerId, + PointerId, + PointerId, + >; diff --git a/wgpu-core/src/device/trace/record.rs b/wgpu-core/src/device/trace/record.rs index 1668728bd..a00d371a9 100644 --- a/wgpu-core/src/device/trace/record.rs +++ b/wgpu-core/src/device/trace/record.rs @@ -4,11 +4,12 @@ use std::io::Write as _; use crate::{ command::{ - ArcCommand, ArcComputeCommand, ArcReferences, ArcRenderCommand, BasePass, ColorAttachments, - Command, ComputeCommand, PassTimestampWrites, PointerReferences, RenderCommand, - RenderPassColorAttachment, ResolvedRenderPassDepthStencilAttachment, + ArcCommand, ArcComputeCommand, ArcRayTracingCommand, ArcReferences, ArcRenderCommand, + BasePass, ColorAttachments, Command, ComputeCommand, PassTimestampWrites, + PointerReferences, RayTracingCommand, RenderCommand, RenderPassColorAttachment, + ResolvedRenderPassDepthStencilAttachment, }, - device::trace::{Data, DataKind}, + device::trace::{Data, DataKind, TraceRayTracingPipelineDescriptor}, id::{markers, PointerId}, storage::StorageItem, }; @@ -273,6 +274,9 @@ impl IntoTrace for ArcCommand { occlusion_query_set: occlusion_query_set.map(|q| q.to_trace()), multiview_mask, }, + ArcCommand::RunRayTracingPass { pass } => Command::RunRayTracingPass { + pass: pass.into_trace(), + }, ArcCommand::BuildAccelerationStructures { blas, tlas } => { Command::BuildAccelerationStructures { blas: blas.into_iter().map(|b| b.into_trace()).collect(), @@ -431,6 +435,7 @@ impl IntoTrace for crate::ray_tracing::OwnedTlasInstance { transform: self.transform, custom_data: self.custom_data, mask: self.mask, + intersection_index: self.intersection_index, } } } @@ -654,6 +659,30 @@ impl IntoTrace for ArcRenderCommand { } } +impl IntoTrace for ArcRayTracingCommand { + type Output = RayTracingCommand; + fn into_trace(self) -> Self::Output { + use RayTracingCommand as C; + match self { + C::SetBindGroup { + index, + num_dynamic_offsets, + bind_group, + } => C::SetBindGroup { + index, + num_dynamic_offsets, + bind_group: bind_group.map(|bg| bg.into_trace()), + }, + C::SetPipeline(id) => C::SetPipeline(id.into_trace()), + C::SetImmediate { offset, data } => C::SetImmediate { offset, data }, + C::TraceRays(groups) => C::TraceRays(groups), + C::PushDebugGroup { color, len } => C::PushDebugGroup { color, len }, + C::PopDebugGroup => C::PopDebugGroup, + C::InsertDebugMarker { color, len } => C::InsertDebugMarker { color, len }, + } + } +} + impl IntoTrace for crate::binding_model::PipelineLayoutDescriptor<'_> { type Output = crate::binding_model::PipelineLayoutDescriptor< 'static, @@ -773,6 +802,34 @@ impl<'a> IntoTrace for crate::pipeline::ComputePipelineDescriptor<'a> { } } +impl<'a> IntoTrace for crate::ray_tracing_pipeline::RayTracingPipelineDescriptor<'a> { + type Output = TraceRayTracingPipelineDescriptor<'a>; + + fn into_trace(self) -> Self::Output { + TraceRayTracingPipelineDescriptor { + label: self.label, + layout: self.layout.into_trace(), + ray_generation: self.ray_generation.into_trace(), + miss: self.miss.into_trace(), + intersections: self + .intersections + .into_iter() + .map(|intersection| match intersection { + crate::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle { + closest_hit, + any_hit, + } => crate::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle { + closest_hit: closest_hit.into_trace(), + any_hit: any_hit.map(|a| a.into_trace()), + }, + }) + .collect(), + cache: self.cache.map(|c| c.into_trace()), + max_recursion_depth: self.max_recursion_depth, + } + } +} + impl<'a> IntoTrace for crate::pipeline::ProgrammableStageDescriptor<'a> { type Output = crate::pipeline::ProgrammableStageDescriptor<'a, PointerId>; @@ -912,11 +969,21 @@ fn action_to_owned(action: Action<'_, PointerReferences>) -> Action<'static, Poi pipeline, index, }, + A::GetRayTracingPipelineBindGroupLayout { + id, + pipeline, + index, + } => A::GetRayTracingPipelineBindGroupLayout { + id, + pipeline, + index, + }, A::DropPipelineLayout(layout) => A::DropPipelineLayout(layout), A::DropBindGroup(bind_group) => A::DropBindGroup(bind_group), A::DropShaderModule(shader_module) => A::DropShaderModule(shader_module), A::DropComputePipeline(pipeline) => A::DropComputePipeline(pipeline), A::DropRenderPipeline(pipeline) => A::DropRenderPipeline(pipeline), + A::DropRayTracingPipeline(pipeline) => A::DropRayTracingPipeline(pipeline), A::DropPipelineCache(cache) => A::DropPipelineCache(cache), A::DropRenderBundle(render_bundle) => A::DropRenderBundle(render_bundle), A::DestroyQuerySet(query_set) => A::DestroyQuerySet(query_set), @@ -1143,6 +1210,30 @@ fn action_to_owned(action: Action<'_, PointerReferences>) -> Action<'static, Poi cache: desc.cache, }, }, + A::CreateRayTracingPipeline { id, desc } => A::CreateRayTracingPipeline { + id, + desc: crate::ray_tracing_pipeline::RayTracingPipelineDescriptor { + label: owned_label(&desc.label), + layout: desc.layout, + ray_generation: owned_stage(desc.ray_generation), + miss: owned_stage(desc.miss), + intersections: desc + .intersections + .into_iter() + .map(|i| match i { + crate::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle { + closest_hit, + any_hit, + } => crate::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle { + closest_hit: owned_stage(closest_hit), + any_hit: any_hit.map(owned_stage), + }, + }) + .collect::>(), + max_recursion_depth: desc.max_recursion_depth, + cache: desc.cache, + }, + }, A::CreatePipelineCache { id, desc } => A::CreatePipelineCache { id, desc: crate::pipeline::PipelineCacheDescriptor { diff --git a/wgpu-core/src/lib.rs b/wgpu-core/src/lib.rs index a5103ca78..031e23345 100644 --- a/wgpu-core/src/lib.rs +++ b/wgpu-core/src/lib.rs @@ -84,6 +84,7 @@ mod pipeline_cache; mod pool; pub mod present; pub mod ray_tracing; +pub mod ray_tracing_pipeline; pub mod resource; mod snatch; pub mod storage; diff --git a/wgpu-core/src/lock/rank.rs b/wgpu-core/src/lock/rank.rs index 12babf6f1..cf11e260c 100644 --- a/wgpu-core/src/lock/rank.rs +++ b/wgpu-core/src/lock/rank.rs @@ -177,6 +177,8 @@ define_lock_ranks! { TEXTURE_INITIALIZATION_STATUS, TLAS_BUILT_INDEX, TLAS_DEPENDENCIES, + TLAS_MAX_INTERSECTION_IDX, + TLAS_REQUIRED_INTERSECTION_TYPES, } rank COMMAND_BUFFER_DATA "CommandBuffer::data" followed by { BUFFER_MAP_STATE, @@ -250,6 +252,8 @@ define_lock_ranks! { rank TEXTURE_CLEAR_MODE "Texture::clear_mode" followed by { } rank TEXTURE_INITIALIZATION_STATUS "Texture::initialization_status" followed by { } rank TEXTURE_VIEWS "Texture::views" followed by { } + rank TLAS_MAX_INTERSECTION_IDX "Tlas::max_intersection_index" followed by { } + rank TLAS_REQUIRED_INTERSECTION_TYPES "Tlas::required_intersection_types" followed by { } #[cfg(test)] rank PAWN "pawn" followed by { ROOK, BISHOP } diff --git a/wgpu-core/src/pipeline.rs b/wgpu-core/src/pipeline.rs index a9c7ad288..b51ed9353 100644 --- a/wgpu-core/src/pipeline.rs +++ b/wgpu-core/src/pipeline.rs @@ -14,6 +14,7 @@ use thiserror::Error; use wgt::error::{ErrorType, WebGpuError}; pub use crate::pipeline_cache::PipelineCacheValidationError; +use crate::ray_tracing_pipeline::RayTracingPipelineError; use crate::{ api_log, binding_model::{ @@ -482,6 +483,8 @@ pub enum CreatePipelineError { InvalidResource(#[from] InvalidResourceError), #[error(transparent)] Render(#[from] RenderError), + #[error(transparent)] + RayTracing(#[from] RayTracingPipelineError), } impl From for CreatePipelineError { @@ -579,6 +582,7 @@ impl WebGpuError for CreatePipelineError { Self::Internal { .. } => ErrorType::Internal, Self::PipelineConstants { .. } => ErrorType::Validation, Self::Render(e) => e.webgpu_error_type(), + Self::RayTracing(e) => e.webgpu_error_type(), } } } diff --git a/wgpu-core/src/ray_tracing.rs b/wgpu-core/src/ray_tracing.rs index 1f5f384f2..af7a97a03 100644 --- a/wgpu-core/src/ray_tracing.rs +++ b/wgpu-core/src/ray_tracing.rs @@ -176,10 +176,8 @@ pub enum BuildAccelerationStructureError { #[error("Blas {0:?} build sizes require index buffer but none was provided")] MissingIndexBuffer(ResourceErrorIdent), - #[error( - "Tlas {0:?} an associated instances contains an invalid custom index (more than 24bits)" - )] - TlasInvalidCustomIndex(ResourceErrorIdent), + #[error("Tlas {0:?} instance {1} contains an invalid custom data (more than 24bits)")] + TlasInvalidCustomData(ResourceErrorIdent, usize), #[error( "Tlas {0:?} has {1} active instances but only {2} are allowed as specified by the descriptor at creation" @@ -209,6 +207,10 @@ pub enum BuildAccelerationStructureError { #[error("Blas {0:?} AABB stride is invalid (must be >= {1} and a multiple of 8)")] InvalidAabbStride(ResourceErrorIdent, BufferAddress), + #[error( + "Tlas {0:?} instance {1} contains an intersection index {2} which is greater than 2^24 - 1" + )] + TlasInvalidIntersectionIndex(ResourceErrorIdent, usize, u32), } impl WebGpuError for BuildAccelerationStructureError { @@ -237,11 +239,12 @@ impl WebGpuError for BuildAccelerationStructureError { | Self::DifferentBlasIndexFormats(..) | Self::CompactedBlas(..) | Self::MissingIndexBuffer(..) - | Self::TlasInvalidCustomIndex(..) + | Self::TlasInvalidCustomData(..) | Self::TlasInstanceCountExceeded(..) | Self::TransformMissing(..) | Self::UseTransformMissing(..) | Self::TlasDependentMissingVertexReturn(..) + | Self::TlasInvalidIntersectionIndex(..) | Self::BlasGeometryKindMismatch(..) | Self::IncompatibleBlasAabbPrimitiveCount(..) | Self::UnalignedAabbPrimitiveOffset(..) @@ -263,15 +266,28 @@ pub enum ValidateAsActionsError { #[error("Blas {0:?} is newer than the containing Tlas {1:?}")] BlasNewerThenTlas(ResourceErrorIdent, ResourceErrorIdent), + + #[error("Tlas {0:?} has an intersection index {1:?} out of bounds of the length of the intersection array {2:?}")] + TlasIntersectionInvalid(ResourceErrorIdent, u32, u32), + + #[error("An instance of Tlas {0:?} requires an intersection type of {1:?} for index {2}, but got {3:?}")] + TlasInstancesIntersectionIndicesDiffer( + ResourceErrorIdent, + crate::ray_tracing_pipeline::RayTracingIntersectionType, + u32, + Option, + ), } impl WebGpuError for ValidateAsActionsError { fn webgpu_error_type(&self) -> ErrorType { match self { Self::DestroyedResource(e) => e.webgpu_error_type(), - Self::UsedUnbuiltTlas(..) | Self::UsedUnbuiltBlas(..) | Self::BlasNewerThenTlas(..) => { - ErrorType::Validation - } + Self::UsedUnbuiltTlas(..) + | Self::UsedUnbuiltBlas(..) + | Self::BlasNewerThenTlas(..) + | Self::TlasIntersectionInvalid(..) + | Self::TlasInstancesIntersectionIndicesDiffer(..) => ErrorType::Validation, } } } @@ -320,6 +336,7 @@ pub struct TlasInstance<'a, Blas = Arc> { pub transform: &'a [f32; 12], pub custom_data: u32, pub mask: u8, + pub intersection_index: u32, } pub struct TlasPackage<'a, Tlas = Arc, Blas = Arc> { @@ -332,6 +349,8 @@ pub struct TlasPackage<'a, Tlas = Arc, Blas = Arc, pub dependencies: Vec>, + pub max_intersection_idx: Option, + pub required_intersection_types: Vec, } #[derive(Debug, Clone, Default)] @@ -352,7 +371,23 @@ impl AsBuild { #[derive(Debug, Clone)] pub(crate) enum AsAction { Build(AsBuild), - UseTlas(Arc), + /// A [`Tlas`] has been bound and used by any pass. The [`Blas`]es it + /// was built with must be validated to have not been built after the + /// [`Tlas`] as backends have undefined behaviour on this (it would + /// cause AABBs to be incorrect, etc.) + BindTlas(Arc), + /// A [`RayTracingPipeline`] has had a `trace_rays` call on it. + /// This [`Tlas`] has been put in a bindgroup, and so the validation + /// must ensure that the maximum intersection index in the [`Tlas`] is + /// less than the length of the intersection group array and that the + /// types of the [`Blas`]es are the same as those of the + /// [`RayTracingPipeline`]. + /// + /// [`RayTracingPipeline`]: crate::ray_tracing_pipeline::RayTracingPipeline + TraceTlas( + Arc, + Arc<[crate::ray_tracing_pipeline::RayTracingIntersectionType]>, + ), } /// Like [`BlasTriangleGeometry`], but with owned data. @@ -407,6 +442,7 @@ pub struct OwnedTlasInstance { pub transform: [f32; 12], pub custom_data: u32, pub mask: u8, + pub intersection_index: u32, } pub type ArcTlasInstance = OwnedTlasInstance; diff --git a/wgpu-core/src/ray_tracing_pipeline.rs b/wgpu-core/src/ray_tracing_pipeline.rs new file mode 100644 index 000000000..89152cdaa --- /dev/null +++ b/wgpu-core/src/ray_tracing_pipeline.rs @@ -0,0 +1,369 @@ +use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec}; +use core::{mem::ManuallyDrop, num::NonZeroU64}; +use hal::BufferDescriptor; + +use arrayvec::ArrayVec; +use thiserror::Error; +use wgt::error::{ErrorType, WebGpuError}; + +use crate::pipeline::{ + CreatePipelineError, LateSizedBufferGroup, PipelineCache, ProgrammableStageDescriptor, + ShaderModule, +}; +use crate::{ + binding_model::{BindGroupLayout, GetBindGroupLayoutError, PipelineLayout}, + device::Device, + resource::{InvalidResourceError, Labeled, ResourceState, TrackingData}, + resource_log, Label, +}; + +#[derive(Clone, Debug, Error)] +#[non_exhaustive] +pub enum RayTracingPipelineError { + #[error("The number of intersection shaders {0} is greater than 2^24")] + TooManyIntersectionGroups(usize), + #[error( + "The ray recursion depth {0} is greater than the limit Limits::max_ray_recursion_depth {1}" + )] + TooHighRayRecursionDepth(u32, u32), +} + +impl WebGpuError for RayTracingPipelineError { + fn webgpu_error_type(&self) -> ErrorType { + match self { + Self::TooManyIntersectionGroups(..) | Self::TooHighRayRecursionDepth(..) => { + ErrorType::Validation + } + } + } +} + +#[derive(Clone, Debug)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum RayTracingIntersectionDescriptor<'a, SM = Arc> { + Triangle { + closest_hit: ProgrammableStageDescriptor<'a, SM>, + any_hit: Option>, + }, +} + +/// Describes a ray tracing pipeline. +#[derive(Clone, Debug)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct RayTracingPipelineDescriptor< + 'a, + PLL = Arc, + SM = Arc, + PLC = Arc, +> { + pub label: Label<'a>, + /// The layout of bind groups for this pipeline. + pub layout: Option, + /// The ray generation stage descriptor + pub ray_generation: ProgrammableStageDescriptor<'a, SM>, + /// The miss stage descriptor + pub miss: ProgrammableStageDescriptor<'a, SM>, + /// All the descriptors for intersection functions + pub intersections: Vec>, + /// The maximum number of nested `traceRay` calls. The ray generation stage is at depth 0. + pub max_recursion_depth: u32, + /// The pipeline cache to use when creating this pipeline. + pub cache: Option, +} + +/// The type of intersection of a index into `RayTracingPipelineDescriptor::intersections` +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub enum RayTracingIntersectionType { + /// The intersection is to be used for triangles. + Triangle, + /// The intersection is to be used for AABBs. + AABB, +} + +/// Metal's shader binding data is opaque, but Vulkan's and DX12's has opaque data +/// but a non-opaque storage mechanism, so each require separate codepaths. +/// Therefore, this is a semi-opaque structure because if metal gets ray tracing pipelines, +/// this will need to turn into an enum so it shouldn't have other code +/// tangled with it. +#[derive(Debug)] +pub struct ShaderBindingData { + pub(crate) raw: ManuallyDrop>, + pub(crate) device: Arc, + pub(crate) num_intersection_groups: u32, + pub(crate) miss_offset: wgt::BufferAddress, + pub(crate) intersection_offset: wgt::BufferAddress, +} + +impl ShaderBindingData { + /// Panics if `num_intersection_groups` is above u32::MAX + pub(crate) fn from_raw_pipeline( + device: Arc, + pipeline: &dyn hal::DynRayTracingPipeline, + num_intersection_groups: usize, + ) -> Result, CreatePipelineError> { + let mut base_data = Vec::new(); + + let ray_generation_data = unsafe { + device + .raw() + .get_raytracing_pipeline_group_data(pipeline, 0..1) + } + .map_err(|e| CreatePipelineError::Device(device.handle_hal_error(e)))?; + + base_data.extend_from_slice(&ray_generation_data); + + let padded_miss_offset = (base_data.len() as wgt::BufferAddress).next_multiple_of( + device.alignments.ray_tracing_pipeline_data_offset_alignment as wgt::BufferAddress, + ); + + base_data.resize(padded_miss_offset as _, 0); + + let miss_data = unsafe { + device + .raw() + .get_raytracing_pipeline_group_data(pipeline, 1..2) + } + .map_err(|e| CreatePipelineError::Device(device.handle_hal_error(e)))?; + + base_data.extend_from_slice(&miss_data); + + let padded_intersection_offset = (base_data.len() as wgt::BufferAddress).next_multiple_of( + device.alignments.ray_tracing_pipeline_data_offset_alignment as wgt::BufferAddress, + ); + + base_data.resize(padded_intersection_offset as _, 0); + + if num_intersection_groups != 0 { + let intersection_data = unsafe { + device.raw().get_raytracing_pipeline_group_data( + pipeline, + 2..(2 + num_intersection_groups as u32), + ) + } + .map_err(|e| CreatePipelineError::Device(device.handle_hal_error(e)))?; + + base_data.extend_from_slice(&intersection_data); + } + + // Don't need the exact allocated size as it will be grater than this. + let (buffer, _) = unsafe { + device.raw().create_buffer(&BufferDescriptor { + label: None, + size: base_data.len() as _, + usage: wgt::BufferUses::RAY_TRACING_PIPELINE_SHADER_DATA + | wgt::BufferUses::COPY_DST, + memory_flags: hal::MemoryFlags::PREFER_COHERENT, + }) + } + .map_err(|e| CreatePipelineError::Device(device.handle_hal_error(e)))?; + + let sbd = Arc::new(Self { + raw: ManuallyDrop::new(buffer), + device: device.clone(), + num_intersection_groups: u32::try_from(num_intersection_groups).unwrap(), + miss_offset: padded_miss_offset, + intersection_offset: padded_intersection_offset, + }); + + // If there is no queue anymore, the ray tracing pipeline can't be accessed, so we don't have to worry about UB from uninitialized values + if let Some(queue) = device.get_queue() { + let mut staging = crate::resource::StagingBuffer::new( + &device, + NonZeroU64::new(base_data.len() as _).expect( + "The total number of groups is always greater than zero, \ + and `ray_tracing_pipeline_group_data_size` must be too.", + ), + )?; + + staging.write_exact(&base_data); + + let staging_buf = staging.flush(); + + let mut writes = queue.pending_writes.lock(); + let encoder = writes.activate(); + unsafe { + encoder.transition_buffers(&[ + hal::BufferBarrier { + buffer: staging_buf.raw(), + usage: hal::StateTransition { + from: wgt::BufferUses::MAP_WRITE, + to: wgt::BufferUses::COPY_SRC, + }, + }, + hal::BufferBarrier { + buffer: sbd.raw.as_ref(), + usage: hal::StateTransition { + from: wgt::BufferUses::empty(), + to: wgt::BufferUses::COPY_DST, + }, + }, + ]); + encoder.copy_buffer_to_buffer( + staging_buf.raw(), + sbd.raw.as_ref(), + &[hal::BufferCopy { + src_offset: 0, + dst_offset: 0, + size: NonZeroU64::new(base_data.len() as _) + .expect("Already checked size isn't zero."), + }], + ); + encoder.transition_buffers(&[hal::BufferBarrier { + buffer: sbd.raw.as_ref(), + usage: hal::StateTransition { + from: wgt::BufferUses::COPY_DST, + to: wgt::BufferUses::RAY_TRACING_PIPELINE_SHADER_DATA, + }, + }]); + }; + + writes.consume(staging_buf); + writes.use_shader_binding_data(&sbd); + } + + Ok(sbd) + } +} + +impl Drop for ShaderBindingData { + fn drop(&mut self) { + // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point. + let raw = unsafe { ManuallyDrop::take(&mut self.raw) }; + unsafe { + self.device.raw().destroy_buffer(raw); + } + } +} + +#[derive(Debug)] +pub(crate) struct RayTracingPipelineState { + pub(crate) raw: ManuallyDrop>, + pub(crate) layout: Arc, + pub(crate) shader_binding_data: Arc, + pub(crate) _shader_modules: Vec>, + pub(crate) intersection_types: Arc<[RayTracingIntersectionType]>, +} + +#[derive(Debug)] +pub struct RayTracingPipeline { + pub(crate) state: ResourceState, + pub(crate) device: Arc, + pub(crate) late_sized_buffer_groups: ArrayVec, + pub(crate) immediate_slots_required: naga::valid::ImmediateSlots, + /// The `label` from the descriptor used to create the resource. + pub(crate) label: String, + pub(crate) tracking_data: TrackingData, +} + +impl Drop for RayTracingPipeline { + fn drop(&mut self) { + resource_log!("Destroy raw {}", self.error_ident()); + + #[cfg(feature = "trace")] + { + use crate::device::trace; + if let Some(t) = self.device.trace.lock().as_mut() { + t.add(trace::Action::DropRayTracingPipeline(unsafe { + trace::to_trace(self) + })); + } + } + + let ResourceState::Valid(state) = &mut self.state else { + return; + }; + + // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point. + let raw = unsafe { ManuallyDrop::take(&mut state.raw) }; + unsafe { + self.device.raw().destroy_ray_tracing_pipeline(raw); + } + } +} + +crate::impl_resource_type!(RayTracingPipeline); +crate::impl_labeled!(RayTracingPipeline); +crate::impl_parent_device!(RayTracingPipeline); +crate::impl_storage_item!(RayTracingPipeline); +crate::impl_trackable!(RayTracingPipeline); + +impl RayTracingPipeline { + pub(crate) fn raw(&self) -> Result<&dyn hal::DynRayTracingPipeline, InvalidResourceError> { + let ResourceState::Valid(state) = &self.state else { + return Err(InvalidResourceError(self.error_ident())); + }; + Ok(state.raw.as_ref()) + } + + pub(crate) fn invalid(device: Arc, label: String) -> Arc { + Arc::new(Self { + tracking_data: TrackingData::new(device.tracker_indices.ray_tracing_pipelines.clone()), + state: ResourceState::Invalid, + device, + immediate_slots_required: naga::valid::ImmediateSlots::default(), + late_sized_buffer_groups: ArrayVec::new(), + label, + }) + } + + pub(crate) fn check_valid(&self) -> Result<(), InvalidResourceError> { + let ResourceState::Valid(_) = &self.state else { + return Err(InvalidResourceError(self.error_ident())); + }; + Ok(()) + } + + pub(crate) fn layout(&self) -> Result<&Arc, InvalidResourceError> { + let ResourceState::Valid(state) = &self.state else { + return Err(InvalidResourceError(self.error_ident())); + }; + Ok(&state.layout) + } + + pub(crate) fn shader_binding_data(&self) -> Result<&ShaderBindingData, InvalidResourceError> { + let ResourceState::Valid(state) = &self.state else { + return Err(InvalidResourceError(self.error_ident())); + }; + Ok(&state.shader_binding_data) + } + + pub(crate) fn intersection_types( + &self, + ) -> Result<&Arc<[RayTracingIntersectionType]>, InvalidResourceError> { + let ResourceState::Valid(state) = &self.state else { + return Err(InvalidResourceError(self.error_ident())); + }; + Ok(&state.intersection_types) + } + + pub fn get_bind_group_layout_inner( + self: &Arc, + index: u32, + ) -> Result, GetBindGroupLayoutError> { + self.layout()?.get_bind_group_layout(index, self.into()) + } + + pub fn get_bind_group_layout( + self: &Arc, + index: u32, + ) -> (Arc, Option) { + let (bgl, error) = match self.get_bind_group_layout_inner(index) { + Ok(bgl) => (bgl, None), + Err(e) => ( + BindGroupLayout::invalid(&self.device, String::new()), + Some(e), + ), + }; + #[cfg(feature = "trace")] + if let Some(ref mut trace) = *self.device.trace.lock() { + use crate::device::trace; + use trace::IntoTrace; + trace.add(trace::Action::GetRayTracingPipelineBindGroupLayout { + id: bgl.to_trace(), + pipeline: self.to_trace(), + index, + }); + }; + (bgl, error) + } +} diff --git a/wgpu-core/src/resource.rs b/wgpu-core/src/resource.rs index feb5f84e6..37dc3c0a2 100644 --- a/wgpu-core/src/resource.rs +++ b/wgpu-core/src/resource.rs @@ -3714,6 +3714,12 @@ crate::impl_parent_device!(Blas); crate::impl_storage_item!(Blas); crate::impl_trackable!(Blas); +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) struct TlasIntersectionType { + pub(crate) index: u32, + pub(crate) required_intersection_ty: crate::ray_tracing_pipeline::RayTracingIntersectionType, +} + #[derive(Debug)] pub(crate) struct TlasState { pub(crate) raw: Snatchable>, @@ -3730,9 +3736,13 @@ pub struct Tlas { pub(crate) update_mode: wgt::AccelerationStructureUpdateMode, pub(crate) built_index: RwLock>, pub(crate) dependencies: RwLock>>, + pub(crate) max_intersection_index: RwLock>, /// The `label` from the descriptor used to create the resource. pub(crate) label: String, pub(crate) tracking_data: TrackingData, + /// The intersections that are required to be of a certain type + /// if using a ray tracing pipeline. + pub(crate) required_intersection_types: RwLock>, } impl Drop for Tlas { @@ -3787,6 +3797,11 @@ impl Tlas { built_index: RwLock::new(rank::TLAS_BUILT_INDEX, None), dependencies: RwLock::new(rank::TLAS_DEPENDENCIES, Vec::new()), device, + max_intersection_index: RwLock::new(rank::TLAS_MAX_INTERSECTION_IDX, None), + required_intersection_types: RwLock::new( + rank::TLAS_REQUIRED_INTERSECTION_TYPES, + Vec::new(), + ), }) } } diff --git a/wgpu-core/src/track/mod.rs b/wgpu-core/src/track/mod.rs index 98c196cb8..ddfc95f1a 100644 --- a/wgpu-core/src/track/mod.rs +++ b/wgpu-core/src/track/mod.rs @@ -106,7 +106,7 @@ mod texture; use crate::{ binding_model, command, lock::{rank, Mutex}, - pipeline, + pipeline, ray_tracing_pipeline, resource::{self, Labeled, RawResourceAccess, ResourceErrorIdent, Trackable}, snatch::SnatchGuard, track::blas::BlasTracker, @@ -232,6 +232,7 @@ pub(crate) struct TrackerIndexAllocators { pub bind_groups: Arc, pub compute_pipelines: Arc, pub render_pipelines: Arc, + pub ray_tracing_pipelines: Arc, pub bundles: Arc, pub query_sets: Arc, pub blas_s: Arc, @@ -248,6 +249,7 @@ impl TrackerIndexAllocators { bind_groups: Arc::new(SharedTrackerIndexAllocator::new()), compute_pipelines: Arc::new(SharedTrackerIndexAllocator::new()), render_pipelines: Arc::new(SharedTrackerIndexAllocator::new()), + ray_tracing_pipelines: Arc::new(SharedTrackerIndexAllocator::new()), bundles: Arc::new(SharedTrackerIndexAllocator::new()), query_sets: Arc::new(SharedTrackerIndexAllocator::new()), blas_s: Arc::new(SharedTrackerIndexAllocator::new()), @@ -648,6 +650,7 @@ pub(crate) struct Tracker { pub compute_pipelines: StatelessTracker, pub render_pipelines: StatelessTracker, + pub ray_tracing_pipelines: StatelessTracker, pub bundles: StatelessTracker, pub query_sets: QuerySetTracker, } @@ -666,6 +669,7 @@ impl Tracker { bind_groups: StatelessTracker::new(), compute_pipelines: StatelessTracker::new(), render_pipelines: StatelessTracker::new(), + ray_tracing_pipelines: StatelessTracker::new(), bundles: StatelessTracker::new(), query_sets: QuerySetTracker::new(), } diff --git a/wgpu-core/src/validation.rs b/wgpu-core/src/validation.rs index 5e2dc1527..b20a15827 100644 --- a/wgpu-core/src/validation.rs +++ b/wgpu-core/src/validation.rs @@ -4,7 +4,7 @@ use alloc::{ sync::Arc, vec::Vec, }; -use core::fmt; +use core::{fmt, num::NonZeroU32}; use arrayvec::ArrayVec; use hashbrown::hash_map::Entry; @@ -362,6 +362,9 @@ struct EntryPoint { /// Size of the immediate data, and which slots this entry point uses. immediate_usage: naga::valid::ImmediateUsage, + + /// The payload for ray tracing, if this is a ray tracing stage. + ray_tracing_payload: Option, } #[derive(Debug, Hash, PartialEq, Eq)] @@ -376,6 +379,91 @@ impl hashbrown::Equivalent for EntryPointKeyRef<'_> { } } +#[derive(Debug, PartialEq, Eq, Clone)] +/// An enum containing the types allowed in a ray tracing payload, to be +/// stored in the interface so various shaders can be checked that they +/// all have the same types. Roughly equal to naga's type inner, but without names, +pub enum RayTracingPayloadType { + /// A single numeric type. + Numeric(NumericType), + /// A struct containing other payload types + Struct { + /// The members of the struct and their offset + members: Vec, + /// The span of the struct + span: u32, + }, + /// An array containing other payload types + Array { + /// The type the array contains within itself + inner: Box, + /// The size of the array, (non-override, non-dynamic). + size: NonZeroU32, + /// The stride of each element in the array. + stride: u32, + }, +} + +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct RayTracingPayloadMember { + offset: u32, + ty: Box, +} + +impl RayTracingPayloadType { + pub fn from_naga(ty: &naga::TypeInner, module: &naga::Module) -> Option { + Some(match ty { + naga::TypeInner::Scalar(scalar) => Self::Numeric(NumericType { + dim: NumericDimension::Scalar, + scalar: *scalar, + }), + naga::TypeInner::Vector { size, scalar } => Self::Numeric(NumericType { + dim: NumericDimension::Vector(*size), + scalar: *scalar, + }), + naga::TypeInner::Matrix { + columns, + rows, + scalar, + } => Self::Numeric(NumericType { + dim: NumericDimension::Matrix(*columns, *rows), + scalar: *scalar, + }), + naga::TypeInner::Struct { members, span } => { + let mut struct_members = Vec::with_capacity(members.len()); + + for member in members { + let ty = &module.types[member.ty].inner; + + struct_members.push(RayTracingPayloadMember { + offset: member.offset, + ty: Box::new(Self::from_naga(ty, module)?), + }); + } + + Self::Struct { + members: struct_members, + span: *span, + } + } + naga::TypeInner::Array { + base, + size: naga::ArraySize::Constant(size), + stride, + } => { + let ty = &module.types[*base].inner; + + Self::Array { + inner: Box::new(Self::from_naga(ty, module)?), + size: *size, + stride: *stride, + } + } + _ => return None, + }) + } +} + /// A summary of the [shader interfaces][si] of the entry points in a [`naga::Module`]. /// /// [si]: https://www.w3.org/TR/WGSL/#shader-interface @@ -633,6 +721,8 @@ pub enum StageError { MeshTopologyMismatch, #[error("Pipeline layout immediate size ({layout}) must be >= the required immediate size ({required}) of the shader entry point")] LayoutImmediateSize { layout: u32, required: u32 }, + #[error("Ray tracing payloads do not match.")] + RayTracingPayloadMismatch, } impl WebGpuError for StageError { @@ -674,7 +764,8 @@ impl WebGpuError for StageError { | Self::MissingFragDepthAttachment | Self::PerVertexNotTriangles | Self::MeshTopologyMismatch - | Self::LayoutImmediateSize { .. } => ErrorType::Validation, + | Self::LayoutImmediateSize { .. } + | Self::RayTracingPayloadMismatch => ErrorType::Validation, } } } @@ -1220,6 +1311,7 @@ pub struct StageIo { /// /// This is `None` if the prior stage was not a mesh shader. pub primitive_index: Option, + pub ray_tracing_payload: Option, } impl Interface { @@ -1514,6 +1606,34 @@ impl Interface { ); } + // Set the payload if there is an incoming payload set and it is a shader that should have one. + if matches!( + entry_point.stage, + naga::ShaderStage::ClosestHit | naga::ShaderStage::AnyHit | naga::ShaderStage::Miss + ) { + let ray_payload = entry_point + .incoming_ray_payload + .expect("these stages must have an incoming payload"); + let ty = module.global_variables[ray_payload].ty; + + ep.ray_tracing_payload = Some( + RayTracingPayloadType::from_naga(&module.types[ty].inner, module) + .expect("naga should already validate invalid payloads out!"), + ); + } + // Or if a payload global variable is used and it is a ray gen shader which doesn't have incoming + // payloads. This may not have a payload if it dispatches no trace rays which should be fine + else if matches!(entry_point.stage, naga::ShaderStage::RayGeneration) { + for (handle, gv) in module.global_variables.iter() { + if !func_info[handle].is_empty() && gv.space == naga::AddressSpace::RayPayload { + ep.ray_tracing_payload = Some( + RayTracingPayloadType::from_naga(&module.types[gv.ty].inner, module) + .expect("naga should already validate invalid payloads out!"), + ); + } + } + } + entry_points.insert( EntryPointKey(entry_point.stage, entry_point.name.clone()), ep, @@ -2112,6 +2232,25 @@ impl Interface { *immediates = immediate_usage; + let mut ray_tracing_payload = inputs.ray_tracing_payload; + + let current_ray_payload = entry_point.ray_tracing_payload.clone(); + + if let (Some(ray_tracing_payload), Some(current_ray_payload)) = + (ray_tracing_payload.as_ref(), current_ray_payload.as_ref()) + { + if ray_tracing_payload != current_ray_payload { + return Err(StageError::RayTracingPayloadMismatch); + } + } + + // We've just checked that if there was previously a payload, it is the same as + // the current payload (if any), so the two must be the same if both `Some`, so + // this doesn't go over any validation. + if let Some(current_ray_payload) = current_ray_payload { + ray_tracing_payload = Some(current_ray_payload) + } + Ok(StageIo { task_payload_size: entry_point.task_payload_size, varyings: outputs, @@ -2120,6 +2259,7 @@ impl Interface { } else { None }, + ray_tracing_payload, }) } } @@ -2252,6 +2392,14 @@ pub enum ShaderStageForValidation { }, Compute, Task, + RayGeneration, + Miss, + ClosestHit { + triangle: bool, + }, + AnyHit { + triangle: bool, + }, } impl ShaderStageForValidation { @@ -2262,6 +2410,10 @@ impl ShaderStageForValidation { Self::Fragment { .. } => naga::ShaderStage::Fragment, Self::Compute => naga::ShaderStage::Compute, Self::Task => naga::ShaderStage::Task, + Self::RayGeneration => naga::ShaderStage::RayGeneration, + Self::Miss => naga::ShaderStage::Miss, + Self::AnyHit { .. } => naga::ShaderStage::AnyHit, + Self::ClosestHit { .. } => naga::ShaderStage::ClosestHit, } } @@ -2272,6 +2424,10 @@ impl ShaderStageForValidation { Self::Fragment { .. } => wgt::ShaderStages::FRAGMENT, Self::Compute => wgt::ShaderStages::COMPUTE, Self::Task => wgt::ShaderStages::TASK, + Self::RayGeneration => wgt::ShaderStages::RAY_GENERATION, + Self::Miss => wgt::ShaderStages::MISS, + Self::AnyHit { .. } => wgt::ShaderStages::ANY_HIT, + Self::ClosestHit { .. } => wgt::ShaderStages::CLOSEST_HIT, } } } diff --git a/wgpu-hal/src/vulkan/adapter.rs b/wgpu-hal/src/vulkan/adapter.rs index e41a9de1c..49e6cc231 100644 --- a/wgpu-hal/src/vulkan/adapter.rs +++ b/wgpu-hal/src/vulkan/adapter.rs @@ -2531,6 +2531,7 @@ impl super::Instance { .map(|maintenance_5| maintenance_5.depth_stencil_swizzle_one_support == vk::TRUE) .unwrap_or(false), ray_tracing_pipeline_group_data_size: alignments.ray_tracing_pipeline_group_data_size, + shader_binding_table_alignment: alignments.ray_tracing_pipeline_data_offset_alignment, store_op_none: phd_capabilities.device_api_version >= vk::API_VERSION_1_3 || (phd_capabilities.device_api_version >= vk::API_VERSION_1_2 && phd_capabilities.supports_extension(khr::dynamic_rendering::NAME)) diff --git a/wgpu-hal/src/vulkan/conv.rs b/wgpu-hal/src/vulkan/conv.rs index fa682a38f..0e5a038c6 100644 --- a/wgpu-hal/src/vulkan/conv.rs +++ b/wgpu-hal/src/vulkan/conv.rs @@ -705,6 +705,10 @@ pub fn map_buffer_usage_to_barrier( stages |= vk::PipelineStageFlags::TRANSFER; access |= vk::AccessFlags::TRANSFER_WRITE; } + if usage.contains(wgt::BufferUses::RAY_TRACING_PIPELINE_SHADER_DATA) { + stages |= vk::PipelineStageFlags::RAY_TRACING_SHADER_KHR; + access |= vk::AccessFlags::SHADER_READ; + } (stages, access) } diff --git a/wgpu-hal/src/vulkan/device.rs b/wgpu-hal/src/vulkan/device.rs index 3426b484f..ef548f335 100644 --- a/wgpu-hal/src/vulkan/device.rs +++ b/wgpu-hal/src/vulkan/device.rs @@ -1056,6 +1056,15 @@ impl crate::Device for super::Device { .max(self.shared.private_caps.scratch_buffer_alignment as u64); } + if desc + .usage + .contains(wgt::BufferUses::RAY_TRACING_PIPELINE_SHADER_DATA) + { + requirements.alignment = requirements + .alignment + .max(self.shared.private_caps.shader_binding_table_alignment as u64); + } + let allocation = self .mem_allocator .allocate( diff --git a/wgpu-hal/src/vulkan/mod.rs b/wgpu-hal/src/vulkan/mod.rs index df50e06ca..0835fcb60 100644 --- a/wgpu-hal/src/vulkan/mod.rs +++ b/wgpu-hal/src/vulkan/mod.rs @@ -520,6 +520,10 @@ struct PrivateCapabilities { /// require an unnecessary parameter. ray_tracing_pipeline_group_data_size: u32, + /// `shaderGroupBaseAlignment`. Shader binding table regions must start at a device + /// address that is a multiple of this, so shader binding table buffers use it as their alignment. + shader_binding_table_alignment: u32, + /// Whether `VK_ATTACHMENT_STORE_OP_NONE` is supported. This includes: /// - `VK_ATTACHMENT_STORE_OP_NONE` provided by `VK_VERSION_1_3`. /// - `VK_ATTACHMENT_STORE_OP_NONE_KHR` provided by `VK_KHR_dynamic_rendering`, or `VK_KHR_load_store_op_none` (promoted to Vulkan 1.4). diff --git a/wgpu-types/src/limits.rs b/wgpu-types/src/limits.rs index 3eb1680b7..db5fca897 100644 --- a/wgpu-types/src/limits.rs +++ b/wgpu-types/src/limits.rs @@ -362,14 +362,10 @@ pub struct Limits { /// The maximum total number (`x*y*z`) of rays able to be dispatched by a trace rays call in a ray /// tracing pass. Requesting more than 0 during device creation only makes sense if [`Features::EXPERIMENTAL_RAY_TRACING_PIPELINES`] /// is enabled. - /// - /// Currently only affects wgpu-hal pub max_ray_dispatch_count: u32, /// The maximum number that one can pass into a ray tracing pipeline creation to be the maximum ray /// recursion depth. (the maximum of the max ray recursion depth) Requesting more than 0 during device /// creation only makes sense if [`Features::EXPERIMENTAL_RAY_TRACING_PIPELINES`] is enabled. - /// - /// Currently only affects wgpu-hal pub max_ray_recursion_depth: u32, } diff --git a/wgpu-types/src/markers.rs b/wgpu-types/src/markers.rs index 1b217e0b6..bcebc25b1 100644 --- a/wgpu-types/src/markers.rs +++ b/wgpu-types/src/markers.rs @@ -56,9 +56,11 @@ ids! { pub type CommandBuffer; pub type RenderPassEncoder; pub type ComputePassEncoder; + pub type RayTracingPassEncoder; pub type RenderBundleEncoder; pub type RenderBundle; pub type QuerySet; pub type Blas; pub type Tlas; + pub type RayTracingPipeline; } diff --git a/wgpu/src/api/blas.rs b/wgpu/src/api/blas.rs index 2efb2d06f..ee628f15f 100644 --- a/wgpu/src/api/blas.rs +++ b/wgpu/src/api/blas.rs @@ -65,6 +65,13 @@ pub struct TlasInstance { /// Mask for the instance used inside the shader to filter instances. /// Reports hit only if `(shader_cull_mask & tlas_instance.mask) != 0u`. pub mask: u8, + /// Intersection group index into a ray tracing pipeline. Must be less than the number of intersection groups in any ray tracing + /// pipeline a tlas built with this is used for. This can be read in ray queries. If this field is non-zero, + /// [`Features::EXPERIMENTAL_RAY_TRACING_PIPELINES`] must be enabled. This must only use the lower 24 bits, if any bits are + /// outside that range (byte 4 does not equal 0) the TlasInstance becomes invalid and generates a validation error when built. + /// + /// [`Features::EXPERIMENTAL_RAY_TRACING_PIPELINES`]: wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES + pub intersection_index: u32, } impl TlasInstance { @@ -73,18 +80,26 @@ impl TlasInstance { /// - transform: Transform buffer offset in bytes (optional, required if transform buffer is present) /// - custom_data: Custom index for the instance used inside the shader (max 24 bits) /// - mask: Mask for the instance used inside the shader to filter instances + /// - intersection_index: Either an index into an intersection group in a ray tracing pipeline or data for ray queries /// /// Note: while one of these contains a reference to a BLAS that BLAS will not be dropped, /// but it can still be destroyed. Destroying a BLAS that is referenced by one or more /// TlasInstance(s) will immediately make them invalid. If one or more of those invalid /// TlasInstances is inside a TlasPackage that is attempted to be built, the build will /// generate a validation error. - pub fn new(blas: &Blas, transform: [f32; 12], custom_data: u32, mask: u8) -> Self { + pub fn new( + blas: &Blas, + transform: [f32; 12], + custom_data: u32, + mask: u8, + intersection_index: u32, + ) -> Self { Self { blas: blas.inner.clone(), transform, custom_data, mask, + intersection_index, } } diff --git a/wgpu/src/api/command_encoder.rs b/wgpu/src/api/command_encoder.rs index c701ac92b..060be59f4 100644 --- a/wgpu/src/api/command_encoder.rs +++ b/wgpu/src/api/command_encoder.rs @@ -107,6 +107,28 @@ impl CommandEncoder { } } + /// Begins recording of a ray tracing pass. + /// + /// This function returns a [`RayTracingPass`] object which records a single ray tracing pass. + /// + /// As long as the returned [`RayTracingPass`] has not ended, + /// any mutating operation on this command encoder causes an error and invalidates it. + /// Note that the `'encoder` lifetime relationship protects against this, + /// but it is possible to opt out of it by calling [`RayTracingPass::forget_lifetime`]. + /// This can be useful for runtime handling of the encoder->pass + /// dependency e.g. when pass and encoder are stored in the same data structure. + pub fn begin_ray_tracing_pass<'encoder>( + &'encoder mut self, + desc: &RayTracingPassDescriptor<'_>, + ) -> RayTracingPass<'encoder> { + let rtpass = self.inner.begin_ray_tracing_pass(desc); + RayTracingPass { + inner: rtpass, + actions: Arc::clone(&self.actions), + _encoder_guard: api::PhantomDrop::default(), + } + } + /// Copy data from one buffer to another. /// /// # Panics diff --git a/wgpu/src/api/compute_pipeline.rs b/wgpu/src/api/compute_pipeline.rs index dfffe9fee..e4076161f 100644 --- a/wgpu/src/api/compute_pipeline.rs +++ b/wgpu/src/api/compute_pipeline.rs @@ -97,6 +97,7 @@ pub struct ComputePipelineDescriptor<'a> { /// selected. // NOTE: keep phrasing in sync. with `FragmentState::entry_point` // NOTE: keep phrasing in sync. with `VertexState::entry_point` + // NOTE: keep phrasing in sync. with `RayTracingStage::entry_point` pub entry_point: Option<&'a str>, /// Advanced options for when this pipeline is compiled /// diff --git a/wgpu/src/api/device.rs b/wgpu/src/api/device.rs index 2d85084a0..cd880e7d0 100644 --- a/wgpu/src/api/device.rs +++ b/wgpu/src/api/device.rs @@ -5,6 +5,7 @@ use core::{error, fmt, future::Future, marker::PhantomData}; use hashbrown::HashSet; use crate::api::blas::{Blas, BlasGeometrySizeDescriptors, CreateBlasDescriptor}; +use crate::api::ray_tracing_pipeline::{RayTracingPipeline, RayTracingPipelineDescriptor}; use crate::api::tlas::{CreateTlasDescriptor, Tlas}; use crate::util::Mutex; use crate::*; @@ -285,6 +286,16 @@ impl Device { ComputePipeline { inner: pipeline } } + /// Creates a [`RayTracingPipeline`]. + #[must_use] + pub fn create_ray_tracing_pipeline( + &self, + desc: &RayTracingPipelineDescriptor<'_>, + ) -> RayTracingPipeline { + let pipeline = self.inner.create_ray_tracing_pipeline(desc); + RayTracingPipeline { inner: pipeline } + } + /// Creates a [`Buffer`]. #[must_use] pub fn create_buffer(&self, desc: &BufferDescriptor<'_>) -> Buffer { diff --git a/wgpu/src/api/mod.rs b/wgpu/src/api/mod.rs index b564aa75f..50a9956b7 100644 --- a/wgpu/src/api/mod.rs +++ b/wgpu/src/api/mod.rs @@ -40,6 +40,8 @@ mod pipeline_cache; mod pipeline_layout; mod query_set; mod queue; +mod ray_tracing_pass; +mod ray_tracing_pipeline; mod render_bundle; mod render_bundle_encoder; mod render_pass; @@ -70,6 +72,8 @@ pub use pipeline_cache::*; pub use pipeline_layout::*; pub use query_set::*; pub use queue::*; +pub use ray_tracing_pass::*; +pub use ray_tracing_pipeline::*; pub use render_bundle::*; pub use render_bundle_encoder::*; pub use render_pass::*; diff --git a/wgpu/src/api/ray_tracing_pass.rs b/wgpu/src/api/ray_tracing_pass.rs new file mode 100644 index 000000000..ff991af87 --- /dev/null +++ b/wgpu/src/api/ray_tracing_pass.rs @@ -0,0 +1,112 @@ +use wgt::DynamicOffset; + +use crate::{api::SharedDeferredCommandBufferActions, *}; + +/// In-progress recording of a ray tracing pass. +/// +/// It can be created with [`CommandEncoder::begin_ray_tracing_pass`]. +#[derive(Debug)] +pub struct RayTracingPass<'encoder> { + pub(crate) inner: dispatch::DispatchRayTracingPass, + + /// Shared with CommandEncoder to enqueue deferred actions from within a pass. + pub(crate) actions: SharedDeferredCommandBufferActions, + + /// This lifetime is used to protect the [`CommandEncoder`] from being used + /// while the pass is alive. This needs to be PhantomDrop to prevent the lifetime + /// from being shortened. + pub(crate) _encoder_guard: crate::api::PhantomDrop<&'encoder ()>, +} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(RayTracingPass<'_>: Send, Sync); + +crate::cmp::impl_eq_ord_hash_proxy!(RayTracingPass<'_> => .inner); + +impl RayTracingPass<'_> { + /// Drops the lifetime relationship to the parent command encoder, making usage of + /// the encoder while this pass is recorded a run-time error instead. + /// + /// Attention: As long as the ray tracing pass has not been ended, any mutating operation on the parent + /// command encoder will cause a run-time error and invalidate it! + /// By default, the lifetime constraint prevents this, but it can be useful + /// to handle this at run time, such as when storing the pass and encoder in the same + /// data structure. + /// + /// This operation has no effect on pass recording. + /// It's a safe operation, since [`CommandEncoder`] is in a locked state as long as the pass is active + /// regardless of the lifetime constraint or its absence. + pub fn forget_lifetime(self) -> RayTracingPass<'static> { + RayTracingPass { + inner: self.inner, + actions: self.actions, + _encoder_guard: crate::api::PhantomDrop::default(), + } + } + + /// Sets the active ray tracing pipeline. + pub fn set_pipeline(&mut self, pipeline: &RayTracingPipeline) { + self.inner.set_pipeline(&pipeline.inner); + } + + /// Sets the active bind group for a given bind group index. The bind group layout + /// in the active pipeline when the `trace_rays()` function is called must match the layout of this bind group. + /// + /// If the bind group have dynamic offsets, provide them in the binding order. + /// These offsets have to be aligned to [`Limits::min_uniform_buffer_offset_alignment`] + /// or [`Limits::min_storage_buffer_offset_alignment`] appropriately. + pub fn set_bind_group<'a, BG>(&mut self, index: u32, bind_group: BG, offsets: &[DynamicOffset]) + where + Option<&'a BindGroup>: From, + { + let bg: Option<&BindGroup> = bind_group.into(); + let bg = bg.map(|bg| &bg.inner); + self.inner.set_bind_group(index, bg, offsets); + } + + /// Inserts debug marker. + pub fn insert_debug_marker(&mut self, label: &str) { + self.inner.insert_debug_marker(label); + } + + /// Start record commands and group it into debug marker group. + pub fn push_debug_group(&mut self, label: &str) { + self.inner.push_debug_group(label); + } + + /// Stops command recording and creates debug group. + pub fn pop_debug_group(&mut self) { + self.inner.pop_debug_group(); + } + + /// Dispatches rays in the current ray tracing pipeline. + pub fn trace_rays(&mut self, x: u32, y: u32, z: u32) { + self.inner.trace_rays(x, y, z); + } +} + +/// [`Features::IMMEDIATES`] must be enabled on the device in order to call these functions. +impl RayTracingPass<'_> { + /// Set immediate data for subsequent [RayTracingPass::trace_rays] calls. + /// + /// Write the bytes in `data` at offset `offset` within immediate data + /// storage. Both `offset` and the length of `data` must be + /// multiples of [`crate::IMMEDIATE_DATA_ALIGNMENT`], which is always 4. + /// + /// For example, if `offset` is `4` and `data` is eight bytes long, this + /// call will write `data` to bytes `4..12` of immediate data storage. + pub fn set_immediates(&mut self, offset: u32, data: &[u8]) { + self.inner.set_immediates(offset, data); + } +} + +/// Describes the attachments of a ray tracing pass. +/// +/// For use with [`CommandEncoder::begin_ray_tracing_pass`]. +#[derive(Clone, Default, Debug)] +pub struct RayTracingPassDescriptor<'a> { + /// Debug label of the ray tracing pass. This will show up in graphics debuggers for easy identification. + pub label: Label<'a>, +} +#[cfg(send_sync)] +static_assertions::assert_impl_all!(RayTracingPassDescriptor<'_>: Send, Sync); diff --git a/wgpu/src/api/ray_tracing_pipeline.rs b/wgpu/src/api/ray_tracing_pipeline.rs new file mode 100644 index 000000000..bdc9e1f2d --- /dev/null +++ b/wgpu/src/api/ray_tracing_pipeline.rs @@ -0,0 +1,143 @@ +use crate::*; + +/// Handle to a ray tracing pipeline. +/// +/// A `RayTracingPipeline` object represents a ray tracing pipeline and its stages. +/// It can be created with [`Device::create_ray_tracing_pipeline`]. +#[derive(Debug, Clone)] +pub struct RayTracingPipeline { + pub(crate) inner: dispatch::DispatchRayTracingPipeline, +} +#[cfg(send_sync)] +static_assertions::assert_impl_all!(RayTracingPipeline: Send, Sync); + +crate::cmp::impl_eq_ord_hash_proxy!(RayTracingPipeline => .inner); + +impl RayTracingPipeline { + /// Get an object representing the bind group layout at a given index. + /// + /// If this pipeline was created with a [default layout][RayTracingPipelineDescriptor::layout], then + /// bind groups created with the returned `BindGroupLayout` can only be used with this pipeline. + /// + /// This method will raise a validation error if there is no bind group layout at `index`. + pub fn get_bind_group_layout(&self, index: u32) -> BindGroupLayout { + let layout = self.inner.get_bind_group_layout(index); + BindGroupLayout { inner: layout } + } + + #[cfg(custom)] + /// Returns custom implementation of RayTracingPipeline (if custom backend and is internally T) + pub fn as_custom(&self) -> Option<&T> { + self.inner.as_custom() + } +} + +/// Describes a stage in a ray tracing pipeline +/// +/// For use in [`RayTracingPipelineDescriptor`] +#[derive(Clone, Debug)] +pub struct RayTracingStage<'a> { + /// The compiled shader module for this stage. + pub module: &'a ShaderModule, + /// The name of the entry point in the compiled shader to use. + /// + /// If [`Some`], there must be a shader entry point with this name in `module` of the stage required. + /// Otherwise, expect exactly one entry point in `module` of the stage required, which will be + /// selected. + // NOTE: keep phrasing in sync. with `ComputePipelineDescriptor::entry_point` + // NOTE: keep phrasing in sync. with `VertexState::entry_point` + // NOTE: keep phrasing in sync. with `FragmentState::entry_point` + pub entry_point: Option<&'a str>, + /// Advanced options for when this pipeline is compiled + /// + /// This implements `Default`, and for most users can be set to `Default::default()` + pub compilation_options: PipelineCompilationOptions<'a>, +} + +/// Describes a group of stages to be called for an intersection in a ray tracing pipeline +/// +/// For use in [`RayTracingPipelineDescriptor`] +#[derive(Clone, Debug)] +pub enum RayTracingIntersectionDescriptor<'a> { + /// This group of shaders may only be used when + /// a BLAS with triangle geometry is intersected. + Triangle { + /// Stage to call if, after the entire intersection process is complete, a triangle within an instance bound to this + /// descriptor is the closest hit. + closest_hit: RayTracingStage<'a>, + /// Optional stage to call when a triangle within an instance bound to this descriptor is hit at any point during the + /// intersection process. + any_hit: Option>, + }, +} + +/// Describes a ray tracing pipeline. +/// +/// For use with [`Device::create_ray_tracing_pipeline`]. +#[derive(Clone, Debug)] +pub struct RayTracingPipelineDescriptor<'a> { + /// Debug label of the pipeline. This will show up in graphics debuggers for easy identification. + pub label: Label<'a>, + /// The layout of bind groups for this pipeline. + /// + /// If this is set, then [`Device::create_ray_tracing_pipeline`] will raise a validation error if + /// the layout doesn't match what the shader module(s) expect. + /// + /// Using the same [`PipelineLayout`] for many [`RayTracingPipeline`] or [`RenderPipeline`] or [`ComputePipeline`] + /// pipelines guarantees that you don't have to rebind any resources when switching between + /// those pipelines. + /// + /// ## Default pipeline layout + /// + /// If `layout` is `None`, then the pipeline has a [default layout] created and used instead. + /// The default layout is deduced from the shader modules. + /// + /// You can use [`RayTracingPipeline::get_bind_group_layout`] to create bind groups for use with the + /// default layout. However, these bind groups cannot be used with any other pipelines. This is + /// convenient for simple pipelines, but using an explicit layout is recommended in most cases. + /// + /// Keep phrasing in sync. with [`RenderPipelineDescriptor`] and [`ComputePipelineDescriptor`]. + /// + /// [default layout]: https://www.w3.org/TR/webgpu/#default-pipeline-layout + pub layout: Option<&'a PipelineLayout>, + /// The ray generation stage. The shader stage invoked by command encoder trace rays. + pub ray_generation: RayTracingStage<'a>, + /// The miss stage. Called if a ray does not hit any object. + pub miss: RayTracingStage<'a>, + /// The list of intersection descriptors + pub intersections: &'a [RayTracingIntersectionDescriptor<'a>], + /// The maximum number of nested `traceRay` calls. The ray generation stage is at depth 0, + /// so it can call `traceRay` only if this is at least 1. Calling `traceRay` at a depth + /// equal to or greater than this value is undefined behavior. + pub max_recursion_depth: u32, + /// The pipeline cache to use when creating this pipeline. + pub cache: Option<&'a PipelineCache>, +} +#[cfg(send_sync)] +static_assertions::assert_impl_all!(RayTracingPipelineDescriptor<'_>: Send, Sync); + +#[cfg(wgpu_core)] +impl RayTracingPipeline { + /// Create a new ray tracing pipeline of wgpu from a wgpu-core ray tracing pipeline. + /// + /// # Arguments + /// + /// - `core_ray_tracing_pipeline` - wgpu-core ray tracing pipeline. + pub fn from_core( + core_ray_tracing_pipeline: alloc::sync::Arc, + ) -> Self { + Self { + inner: crate::backend::wgpu_core::CoreRayTracingPipeline::from_core( + core_ray_tracing_pipeline, + ) + .into(), + } + } + + /// Returns the underlying wgpu-core ray tracing pipeline if this `RayTracingPipeline` is on the wgpu-core backend, otherwise `None`. + pub fn as_core( + &self, + ) -> Option> { + self.inner.as_core_opt().map(|rtp| rtp.as_core()) + } +} diff --git a/wgpu/src/api/render_pipeline.rs b/wgpu/src/api/render_pipeline.rs index 82ed4c970..ade1e1eb6 100644 --- a/wgpu/src/api/render_pipeline.rs +++ b/wgpu/src/api/render_pipeline.rs @@ -124,6 +124,7 @@ pub struct VertexState<'a> { /// selected. // NOTE: keep phrasing in sync. with `ComputePipelineDescriptor::entry_point` // NOTE: keep phrasing in sync. with `FragmentState::entry_point` + // NOTE: keep phrasing in sync. with `RayTracingStage::entry_point` pub entry_point: Option<&'a str>, /// Advanced options for when this pipeline is compiled /// diff --git a/wgpu/src/backend/custom.rs b/wgpu/src/backend/custom.rs index 3160ca785..d07979c86 100644 --- a/wgpu/src/backend/custom.rs +++ b/wgpu/src/backend/custom.rs @@ -89,10 +89,12 @@ dyn_type!(pub ref struct DynQuerySet(dyn QuerySetInterface)); dyn_type!(pub ref struct DynPipelineLayout(dyn PipelineLayoutInterface)); dyn_type!(pub ref struct DynRenderPipeline(dyn RenderPipelineInterface)); dyn_type!(pub ref struct DynComputePipeline(dyn ComputePipelineInterface)); +dyn_type!(pub ref struct DynRayTracingPipeline(dyn RayTracingPipelineInterface)); dyn_type!(pub ref struct DynPipelineCache(dyn PipelineCacheInterface)); dyn_type!(pub mut struct DynCommandEncoder(dyn CommandEncoderInterface)); dyn_type!(pub mut struct DynComputePass(dyn ComputePassInterface)); dyn_type!(pub mut struct DynRenderPass(dyn RenderPassInterface)); +dyn_type!(pub mut struct DynRayTracingPass(dyn RayTracingPassInterface)); dyn_type!(pub mut struct DynCommandBuffer(dyn CommandBufferInterface)); static NEXT_RENDER_BUNDLE_ENCODER_ID: AtomicU64 = AtomicU64::new(0); diff --git a/wgpu/src/backend/webgpu.rs b/wgpu/src/backend/webgpu.rs index f7a2edc5b..5c12933b4 100644 --- a/wgpu/src/backend/webgpu.rs +++ b/wgpu/src/backend/webgpu.rs @@ -1435,6 +1435,12 @@ pub struct WebComputePipeline { ident: crate::cmp::Identifier, } +#[derive(Debug, Clone)] +pub struct WebRayTracingPipeline { + /// Unique identifier for this RayTracingPipeline. + ident: crate::cmp::Identifier, +} // no ray tracing pipelines on web + #[derive(Debug, Clone)] pub struct WebPipelineCache { /// Unique identifier for this PipelineCache. @@ -1462,6 +1468,12 @@ pub struct WebRenderPassEncoder { ident: crate::cmp::Identifier, } +#[derive(Debug, Clone)] +pub struct WebRayTracingPassEncoder { + /// Unique identifier for this RayTracingPassEncoder. + ident: crate::cmp::Identifier, +} // no ray tracing pipelines on web + #[derive(Debug)] pub struct WebCommandBuffer { pub(crate) inner: webgpu_sys::GpuCommandBuffer, @@ -1544,10 +1556,12 @@ impl_send_sync!(WebQuerySet); impl_send_sync!(WebPipelineLayout); impl_send_sync!(WebRenderPipeline); impl_send_sync!(WebComputePipeline); +impl_send_sync!(WebRayTracingPipeline); impl_send_sync!(WebPipelineCache); impl_send_sync!(WebCommandEncoder); impl_send_sync!(WebComputePassEncoder); impl_send_sync!(WebRenderPassEncoder); +impl_send_sync!(WebRayTracingPassEncoder); impl_send_sync!(WebCommandBuffer); impl_send_sync!(WebRenderBundleEncoder); impl_send_sync!(WebRenderBundle); @@ -1574,11 +1588,13 @@ crate::cmp::impl_eq_ord_hash_proxy!(WebQuerySet => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebPipelineLayout => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebRenderPipeline => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebComputePipeline => .ident); +crate::cmp::impl_eq_ord_hash_proxy!(WebRayTracingPipeline => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebPipelineCache => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebCommandEncoder => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebComputePassEncoder => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebRenderPassEncoder => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebCommandBuffer => .ident); +crate::cmp::impl_eq_ord_hash_proxy!(WebRayTracingPassEncoder => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebRenderBundleEncoder => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebRenderBundle => .ident); crate::cmp::impl_eq_ord_hash_proxy!(WebSurface => .ident); @@ -2589,6 +2605,13 @@ impl dispatch::DeviceInterface for WebDevice { .into() } + fn create_ray_tracing_pipeline( + &self, + _desc: &crate::RayTracingPipelineDescriptor<'_>, + ) -> dispatch::DispatchRayTracingPipeline { + unimplemented!("ray tracing is not on the web.") + } + unsafe fn create_pipeline_cache( &self, _desc: &crate::PipelineCacheDescriptor<'_>, @@ -3343,6 +3366,17 @@ impl Drop for WebComputePipeline { } } +impl dispatch::RayTracingPipelineInterface for WebRayTracingPipeline { + fn get_bind_group_layout(&self, _index: u32) -> dispatch::DispatchBindGroupLayout { + unimplemented!("ray tracing is not on the web.") + } +} +impl Drop for WebRayTracingPipeline { + fn drop(&mut self) { + // no-op + } +} + impl dispatch::CommandEncoderInterface for WebCommandEncoder { fn copy_buffer_to_buffer( &self, @@ -3573,6 +3607,13 @@ impl dispatch::CommandEncoderInterface for WebCommandEncoder { .into() } + fn begin_ray_tracing_pass( + &self, + _desc: &crate::RayTracingPassDescriptor<'_>, + ) -> dispatch::DispatchRayTracingPass { + unimplemented!("ray tracing is not on the web.") + } + fn finish(&mut self) -> dispatch::DispatchCommandBuffer { let label = self.inner.label(); let buffer = if label.is_empty() { @@ -4077,6 +4118,43 @@ impl Drop for WebRenderPassEncoder { } } +impl dispatch::RayTracingPassInterface for WebRayTracingPassEncoder { + fn set_pipeline(&mut self, _pipeline: &dispatch::DispatchRayTracingPipeline) { + unreachable!("Ray tracing pipelines are unavailable on the web.") + } + fn set_bind_group( + &mut self, + _index: u32, + _bind_group: Option<&dispatch::DispatchBindGroup>, + _offsets: &[crate::DynamicOffset], + ) { + unreachable!("Ray tracing pipelines are unavailable on the web.") + } + fn set_immediates(&mut self, _offset: u32, _data: &[u8]) { + unreachable!("Ray tracing pipelines are unavailable on the web.") + } + + fn insert_debug_marker(&mut self, _label: &str) { + unreachable!("Ray tracing pipelines are unavailable on the web.") + } + fn push_debug_group(&mut self, _group_label: &str) { + unreachable!("Ray tracing pipelines are unavailable on the web.") + } + fn pop_debug_group(&mut self) { + unreachable!("Ray tracing pipelines are unavailable on the web.") + } + + fn trace_rays(&mut self, _x: u32, _y: u32, _z: u32) { + unreachable!("Ray tracing pipelines are unavailable on the web.") + } +} + +impl Drop for WebRayTracingPassEncoder { + fn drop(&mut self) { + // no-op + } +} + impl dispatch::CommandBufferInterface for WebCommandBuffer {} impl Drop for WebCommandBuffer { fn drop(&mut self) { diff --git a/wgpu/src/backend/wgpu_core.rs b/wgpu/src/backend/wgpu_core.rs index d137181ef..c2bff759b 100644 --- a/wgpu/src/backend/wgpu_core.rs +++ b/wgpu/src/backend/wgpu_core.rs @@ -577,6 +577,25 @@ impl CoreRenderPipeline { } } +#[derive(Debug, Clone)] +pub struct CoreRayTracingPipeline { + pub(crate) wgpu_ray_tracing_pipeline: Arc, +} + +impl CoreRayTracingPipeline { + pub(crate) fn from_core( + core_ray_tracing_pipeline: Arc, + ) -> Self { + Self { + wgpu_ray_tracing_pipeline: core_ray_tracing_pipeline, + } + } + + pub(crate) fn as_core(&self) -> Arc { + self.wgpu_ray_tracing_pipeline.clone() + } +} + #[derive(Debug)] pub struct CoreComputePass { pass: wgc::command::ComputePass, @@ -591,6 +610,13 @@ pub struct CoreRenderPass { id: crate::cmp::Identifier, } +#[derive(Debug)] +pub struct CoreRayTracingPass { + pass: wgc::command::RayTracingPass, + + id: crate::cmp::Identifier, +} + pub struct CoreCommandEncoder { pub(crate) wgpu_command_encoder: Arc, } @@ -707,10 +733,12 @@ crate::cmp::impl_eq_ord_hash_arc_address!(CoreQuerySet => .wgpu_query_set); crate::cmp::impl_eq_ord_hash_arc_address!(CorePipelineLayout => .wgpu_pipeline_layout); crate::cmp::impl_eq_ord_hash_arc_address!(CoreRenderPipeline => .wgpu_render_pipeline); crate::cmp::impl_eq_ord_hash_arc_address!(CoreComputePipeline => .wgpu_compute_pipeline); +crate::cmp::impl_eq_ord_hash_arc_address!(CoreRayTracingPipeline => .wgpu_ray_tracing_pipeline); crate::cmp::impl_eq_ord_hash_arc_address!(CorePipelineCache => .wgpu_pipeline_cache); crate::cmp::impl_eq_ord_hash_arc_address!(CoreCommandEncoder => .wgpu_command_encoder); crate::cmp::impl_eq_ord_hash_proxy!(CoreComputePass => .id); crate::cmp::impl_eq_ord_hash_proxy!(CoreRenderPass => .id); +crate::cmp::impl_eq_ord_hash_proxy!(CoreRayTracingPass => .id); crate::cmp::impl_eq_ord_hash_arc_address!(CoreCommandBuffer => .wgpu_command_buffer); crate::cmp::impl_eq_ord_hash_box_address!(CoreRenderBundleEncoder => .encoder); crate::cmp::impl_eq_ord_hash_arc_address!(CoreRenderBundle => .wgpu_render_bundle); @@ -1420,6 +1448,77 @@ impl dispatch::DeviceInterface for CoreDevice { .into() } + fn create_ray_tracing_pipeline( + &self, + desc: &crate::RayTracingPipelineDescriptor<'_>, + ) -> dispatch::DispatchRayTracingPipeline { + use wgc::pipeline as pipe; + use wgc::ray_tracing_pipeline as rt_pipe; + + fn downcast_rt_stage<'a>( + stage: &'a crate::RayTracingStage<'a>, + ) -> pipe::ProgrammableStageDescriptor<'a> { + pipe::ProgrammableStageDescriptor { + module: stage.module.inner.as_core().wgpu_shader_module.clone(), + entry_point: stage.entry_point.map(Borrowed), + constants: stage + .compilation_options + .constants + .iter() + .map(|&(key, value)| (String::from(key), value)) + .collect(), + zero_initialize_workgroup_memory: stage + .compilation_options + .zero_initialize_workgroup_memory, + } + } + + let descriptor = rt_pipe::RayTracingPipelineDescriptor { + label: desc.label.map(Borrowed), + layout: desc + .layout + .map(|pll| pll.inner.as_core().wgpu_pipeline_layout.clone()), + ray_generation: downcast_rt_stage(&desc.ray_generation), + miss: downcast_rt_stage(&desc.miss), + intersections: desc + .intersections + .iter() + .map(|intersection_desc| match intersection_desc { + crate::RayTracingIntersectionDescriptor::Triangle { + closest_hit, + any_hit, + } => rt_pipe::RayTracingIntersectionDescriptor::Triangle { + closest_hit: downcast_rt_stage(closest_hit), + any_hit: any_hit.as_ref().map(|stage| downcast_rt_stage(stage)), + }, + }) + .collect::>(), + max_recursion_depth: desc.max_recursion_depth, + cache: desc + .cache + .map(|cache| cache.inner.as_core().wgpu_pipeline_cache.clone()), + }; + + let (wgpu_ray_tracing_pipeline, error) = + self.wgpu_device.create_ray_tracing_pipeline(descriptor); + if let Some(cause) = error { + if let pipe::CreatePipelineError::Internal { stage, ref message } = cause { + log::error!( + "Shader translation error for stage {:?}: {}", + stage, + message + ); + log::error!("Please report it to https://github.com/gfx-rs/wgpu"); + } + self.wgpu_device + .handle_error(cause, desc.label, "Device::create_ray_tracing_pipeline"); + } + CoreRayTracingPipeline { + wgpu_ray_tracing_pipeline, + } + .into() + } + unsafe fn create_pipeline_cache( &self, desc: &crate::PipelineCacheDescriptor<'_>, @@ -1975,6 +2074,22 @@ impl dispatch::RenderPipelineInterface for CoreRenderPipeline { } } +impl dispatch::RayTracingPipelineInterface for CoreRayTracingPipeline { + fn get_bind_group_layout(&self, index: u32) -> dispatch::DispatchBindGroupLayout { + let (wgpu_bind_group_layout, error) = + self.wgpu_ray_tracing_pipeline.get_bind_group_layout(index); + if let Some(err) = error { + self.wgpu_ray_tracing_pipeline + .device() + .handle_error_nolabel(err, "RayTracingPipeline::get_bind_group_layout") + } + CoreBindGroupLayout { + wgpu_bind_group_layout, + } + .into() + } +} + impl dispatch::ComputePipelineInterface for CoreComputePipeline { fn get_bind_group_layout(&self, index: u32) -> dispatch::DispatchBindGroupLayout { let wgpu_bind_group_layout = self.wgpu_compute_pipeline.get_bind_group_layout(index); @@ -2136,6 +2251,23 @@ impl dispatch::CommandEncoderInterface for CoreCommandEncoder { .into() } + fn begin_ray_tracing_pass( + &self, + desc: &crate::RayTracingPassDescriptor<'_>, + ) -> dispatch::DispatchRayTracingPass { + let pass = self.wgpu_command_encoder.begin_ray_tracing_pass( + &wgc::command::RayTracingPassDescriptor { + label: desc.label.map(Borrowed), + }, + ); + + CoreRayTracingPass { + pass, + id: crate::cmp::Identifier::create(), + } + .into() + } + fn finish(&mut self) -> dispatch::DispatchCommandBuffer { let descriptor = wgt::CommandBufferDescriptor::default(); let wgpu_command_buffer = self.wgpu_command_encoder.finish(&descriptor); @@ -2279,6 +2411,7 @@ impl dispatch::CommandEncoderInterface for CoreCommandEncoder { transform: instance.transform, custom_data: instance.custom_data, mask: instance.mask, + intersection_index: instance.intersection_index, }) }) .collect(); @@ -2710,6 +2843,52 @@ impl Drop for CoreRenderPass { } } +impl dispatch::RayTracingPassInterface for CoreRayTracingPass { + fn set_pipeline(&mut self, pipeline: &dispatch::DispatchRayTracingPipeline) { + let pipeline = pipeline.as_core(); + + self.pass + .set_pipeline(pipeline.wgpu_ray_tracing_pipeline.clone()) + } + + fn set_bind_group( + &mut self, + index: u32, + bind_group: Option<&dispatch::DispatchBindGroup>, + offsets: &[crate::DynamicOffset], + ) { + let bg = bind_group.map(|bg| bg.as_core().wgpu_bind_group.clone()); + + self.pass.set_bind_group(index, bg, offsets) + } + + fn set_immediates(&mut self, offset: u32, data: &[u8]) { + self.pass.set_immediates(offset, data) + } + + fn insert_debug_marker(&mut self, label: &str) { + self.pass.insert_debug_marker(label, 0) + } + + fn push_debug_group(&mut self, group_label: &str) { + self.pass.push_debug_group(group_label, 0) + } + + fn pop_debug_group(&mut self) { + self.pass.pop_debug_group() + } + + fn trace_rays(&mut self, x: u32, y: u32, z: u32) { + self.pass.trace_rays(x, y, z) + } +} + +impl Drop for CoreRayTracingPass { + fn drop(&mut self) { + self.pass.end() + } +} + impl dispatch::RenderBundleEncoderInterface for CoreRenderBundleEncoder { fn set_pipeline(&mut self, pipeline: &dispatch::DispatchRenderPipeline) { let pipeline = pipeline.as_core(); diff --git a/wgpu/src/dispatch.rs b/wgpu/src/dispatch.rs index 851769a8a..4f2a3b3cd 100644 --- a/wgpu/src/dispatch.rs +++ b/wgpu/src/dispatch.rs @@ -176,6 +176,10 @@ pub trait DeviceInterface: CommonTraits { &self, desc: &crate::ComputePipelineDescriptor<'_>, ) -> DispatchComputePipeline; + fn create_ray_tracing_pipeline( + &self, + desc: &crate::RayTracingPipelineDescriptor<'_>, + ) -> DispatchRayTracingPipeline; unsafe fn create_pipeline_cache( &self, desc: &crate::PipelineCacheDescriptor<'_>, @@ -345,6 +349,9 @@ pub trait RenderPipelineInterface: CommonTraits { pub trait ComputePipelineInterface: CommonTraits { fn get_bind_group_layout(&self, index: u32) -> DispatchBindGroupLayout; } +pub trait RayTracingPipelineInterface: CommonTraits { + fn get_bind_group_layout(&self, index: u32) -> DispatchBindGroupLayout; +} pub trait PipelineCacheInterface: CommonTraits { fn get_data(&self) -> Option>; } @@ -378,6 +385,10 @@ pub trait CommandEncoderInterface: CommonTraits { fn begin_compute_pass(&self, desc: &crate::ComputePassDescriptor<'_>) -> DispatchComputePass; fn begin_render_pass(&self, desc: &crate::RenderPassDescriptor<'_>) -> DispatchRenderPass; + fn begin_ray_tracing_pass( + &self, + desc: &crate::RayTracingPassDescriptor<'_>, + ) -> DispatchRayTracingPass; fn finish(&mut self) -> DispatchCommandBuffer; fn clear_texture( @@ -566,6 +577,22 @@ pub trait RenderPassInterface: CommonTraits + Drop { fn execute_bundles(&mut self, render_bundles: &mut dyn Iterator); } +pub trait RayTracingPassInterface: CommonTraits + Drop { + fn set_pipeline(&mut self, pipeline: &DispatchRayTracingPipeline); + fn set_bind_group( + &mut self, + index: u32, + bind_group: Option<&DispatchBindGroup>, + offsets: &[crate::DynamicOffset], + ); + fn set_immediates(&mut self, offset: u32, data: &[u8]); + + fn insert_debug_marker(&mut self, label: &str); + fn push_debug_group(&mut self, group_label: &str); + fn pop_debug_group(&mut self); + + fn trace_rays(&mut self, x: u32, y: u32, z: u32); +} pub trait RenderBundleEncoderInterface: CommonTraits { fn set_pipeline(&mut self, pipeline: &DispatchRenderPipeline); @@ -1097,10 +1124,12 @@ dispatch_types! {ref type DispatchQuerySet: QuerySetInterface = CoreQuerySet, We dispatch_types! {ref type DispatchPipelineLayout: PipelineLayoutInterface = CorePipelineLayout, WebPipelineLayout, DynPipelineLayout} dispatch_types! {ref type DispatchRenderPipeline: RenderPipelineInterface = CoreRenderPipeline, WebRenderPipeline, DynRenderPipeline} dispatch_types! {ref type DispatchComputePipeline: ComputePipelineInterface = CoreComputePipeline, WebComputePipeline, DynComputePipeline} +dispatch_types! {ref type DispatchRayTracingPipeline: RayTracingPipelineInterface = CoreRayTracingPipeline, WebRayTracingPipeline, DynRayTracingPipeline} dispatch_types! {ref type DispatchPipelineCache: PipelineCacheInterface = CorePipelineCache, WebPipelineCache, DynPipelineCache} dispatch_types! {mut type DispatchCommandEncoder: CommandEncoderInterface = CoreCommandEncoder, WebCommandEncoder, DynCommandEncoder} dispatch_types! {mut type DispatchComputePass: ComputePassInterface = CoreComputePass, WebComputePassEncoder, DynComputePass} dispatch_types! {mut type DispatchRenderPass: RenderPassInterface = CoreRenderPass, WebRenderPassEncoder, DynRenderPass} +dispatch_types! {mut type DispatchRayTracingPass: RayTracingPassInterface = CoreRayTracingPass, WebRayTracingPassEncoder, DynRayTracingPass} dispatch_types! {mut type DispatchCommandBuffer: CommandBufferInterface = CoreCommandBuffer, WebCommandBuffer, DynCommandBuffer} dispatch_types! {mut type DispatchRenderBundleEncoder: RenderBundleEncoderInterface = CoreRenderBundleEncoder, WebRenderBundleEncoder, DynRenderBundleEncoder} dispatch_types! {ref type DispatchRenderBundle: RenderBundleInterface = CoreRenderBundle, WebRenderBundle, DynRenderBundle}