Skip to main content

wgpu_core/command/
ray_tracing_pass.rs

1use core::{convert::Infallible, fmt};
2
3use alloc::{borrow::Cow, boxed::Box, sync::Arc, vec::Vec};
4
5use thiserror::Error;
6use wgt::{
7    error::{ErrorType, WebGpuError},
8    BufferAddress, DynamicOffset,
9};
10
11use crate::{
12    api_log,
13    binding_model::{BindError, BindGroup, ImmediateUploadError},
14    command::{
15        bind::{Binder, BinderError},
16        memory_init::{fixup_discarded_surfaces, SurfacesInDiscardState},
17        pass::{self, flush_bindings_helper, ImmediateState},
18        pass_base, pass_try,
19        ray_tracing_pass_commands::ArcRayTracingCommand,
20        ArcCommand, BasePass, BindGroupStateChange, CommandEncoder, CommandEncoderError,
21        DebugGroupError, EncoderStateError, EncodingState, InnerCommandEncoder, MapPassErr,
22        PassErrorScope, PassStateError, StateChange,
23    },
24    device::{Device, DeviceError, MissingDownlevelFlags, MissingFeatures},
25    hal_label, id, impl_resource_type,
26    init_tracker::MemoryInitKind,
27    ray_tracing::AsAction,
28    ray_tracing_pipeline::RayTracingPipeline,
29    resource::{
30        Buffer, DestroyedResourceError, InvalidOrDestroyedResourceError, InvalidResourceError,
31        Labeled, MissingBufferUsageError, ParentDevice, RawResourceAccess, Trackable,
32    },
33    track::{ResourceUsageCompatibilityError, Tracker},
34    Label,
35};
36
37pub type RayTracingBasePass = BasePass<ArcRayTracingCommand, RayTracingPassError>;
38
39/// Very similar to [`super::compute::ComputePass`]
40pub struct RayTracingPass {
41    /// All pass data & records is stored here.
42    base: RayTracingBasePass,
43
44    /// Parent command encoder that this pass records commands into.
45    ///
46    /// Implications are the same as [`super::compute::ComputePass::parent`]
47    parent: Option<Arc<CommandEncoder>>,
48
49    device: Arc<Device>,
50
51    current_bind_groups: BindGroupStateChange,
52    current_pipeline: StateChange<Arc<RayTracingPipeline>>,
53}
54
55impl_resource_type!(RayTracingPass);
56
57impl crate::storage::StorageItem for RayTracingPass {
58    type Marker = id::markers::RayTracingPassEncoder;
59}
60
61impl fmt::Debug for RayTracingPass {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        match self.parent {
64            Some(ref cmd_enc) => {
65                write!(f, "RayTracingPass {{ parent: {} }}", cmd_enc.error_ident())
66            }
67            None => write!(f, "RayTracingPass {{ parent: None }}"),
68        }
69    }
70}
71
72impl RayTracingPass {
73    /// If the parent command encoder is invalid, the returned pass will be invalid.
74    fn new(
75        parent: Arc<CommandEncoder>,
76        desc: RayTracingPassDescriptor,
77    ) -> Result<Self, MissingFeatures> {
78        parent
79            .device
80            .require_features(wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES)?;
81
82        let RayTracingPassDescriptor { label } = desc;
83
84        Ok(Self {
85            base: BasePass::new(&label),
86            device: parent.device.clone(),
87            parent: Some(parent),
88
89            current_bind_groups: BindGroupStateChange::new(),
90            current_pipeline: StateChange::new(),
91        })
92    }
93
94    fn new_invalid(parent: Arc<CommandEncoder>, label: &Label, err: RayTracingPassError) -> Self {
95        Self {
96            base: BasePass::new_invalid(label, err),
97            device: parent.device.clone(),
98            parent: Some(parent),
99            current_bind_groups: BindGroupStateChange::new(),
100            current_pipeline: StateChange::new(),
101        }
102    }
103
104    #[inline]
105    pub fn label(&self) -> Option<&str> {
106        self.base.label.as_deref()
107    }
108
109    pub fn set_bind_group(
110        &mut self,
111        index: u32,
112        bind_group: Option<Arc<BindGroup>>,
113        offsets: &[DynamicOffset],
114    ) {
115        if let Err(err) = self.set_bind_group_inner(index, bind_group, offsets) {
116            self.device
117                .handle_error(err, self.label(), "RayTracingPass::set_bind_group");
118        }
119    }
120
121    pub fn set_bind_group_inner(
122        &mut self,
123        index: u32,
124        bind_group: Option<Arc<BindGroup>>,
125        offsets: &[DynamicOffset],
126    ) -> Result<(), PassStateError> {
127        let scope = PassErrorScope::SetBindGroup;
128
129        // This statement will return an error if the pass is ended. It's
130        // important the error check comes before the early-out for
131        // `set_and_check_redundant`.
132        let base = pass_base!(self, scope);
133
134        if self.current_bind_groups.set_and_check_redundant(
135            &bind_group,
136            index,
137            &mut base.dynamic_offsets,
138            offsets,
139        ) {
140            return Ok(());
141        }
142
143        let bind_group = if let Some(bind_group) = bind_group {
144            pass_try!(base, scope, bind_group.check_is_valid());
145            Some(bind_group)
146        } else {
147            None
148        };
149
150        base.commands.push(ArcRayTracingCommand::SetBindGroup {
151            index,
152            num_dynamic_offsets: offsets.len(),
153            bind_group,
154        });
155
156        Ok(())
157    }
158
159    pub fn set_immediates_inner(&mut self, offset: u32, data: &[u8]) -> Result<(), PassStateError> {
160        let scope = PassErrorScope::SetImmediate;
161        let base = pass_base!(self, scope);
162
163        pass_try!(
164            base,
165            scope,
166            pass::validate_immediates_alignment(offset, data.len())
167        );
168
169        base.commands.push(ArcRayTracingCommand::SetImmediate {
170            offset,
171            data: data
172                .chunks_exact(size_of::<u32>())
173                .map(|ck| u32::from_le_bytes(ck.try_into().unwrap()))
174                .collect(),
175        });
176
177        Ok(())
178    }
179    pub fn set_immediates(&mut self, offset: u32, data: &[u8]) {
180        if let Err(err) = self.set_immediates_inner(offset, data) {
181            self.device
182                .handle_error(err, self.label(), "RayTracingPass::set_immediates");
183        }
184    }
185}
186
187#[derive(Clone, Debug, Default)]
188pub struct RayTracingPassDescriptor<'a> {
189    pub label: Label<'a>,
190}
191
192#[derive(Clone, Debug, Error)]
193#[non_exhaustive]
194pub enum TraceRayError {
195    #[error("Ray tracing pipeline must be set")]
196    MissingPipeline(pass::MissingPipeline),
197    #[error(transparent)]
198    IncompatibleBindGroup(#[from] Box<BinderError>),
199    #[error("Trace ray size ({current:?}) must be less or equal to {limit:?}")]
200    InvalidDimensionSize { current: [u32; 3], limit: [u32; 3] },
201    #[error("The total count of rays invocations ({current:?}) must be less or equal to {limit}")]
202    TooManyTotal { current: u32, limit: u32 },
203
204    #[error("Not all immediate data required by the pipeline has been set via set_immediates (missing byte ranges: {missing})")]
205    MissingImmediateData {
206        missing: naga::valid::ImmediateSlots,
207    },
208}
209
210impl WebGpuError for TraceRayError {
211    fn webgpu_error_type(&self) -> ErrorType {
212        ErrorType::Validation
213    }
214}
215
216/// Error encountered when performing a ray tracing pass.
217#[derive(Clone, Debug, Error)]
218pub enum RayTracingPassErrorInner {
219    #[error(transparent)]
220    Device(#[from] DeviceError),
221    #[error(transparent)]
222    EncoderState(#[from] EncoderStateError),
223    #[error("Parent encoder is invalid")]
224    InvalidParentEncoder,
225    #[error(transparent)]
226    DebugGroupError(#[from] DebugGroupError),
227    #[error(transparent)]
228    BindGroupIndexOutOfRange(#[from] pass::BindGroupIndexOutOfRange),
229    #[error(transparent)]
230    DestroyedResource(#[from] DestroyedResourceError),
231    #[error("Indirect buffer offset {0:?} is not a multiple of 4")]
232    UnalignedIndirectBufferOffset(BufferAddress),
233    #[error("Indirect buffer uses bytes {offset}..{end_offset} which overruns indirect buffer of size {buffer_size}")]
234    IndirectBufferOverrun {
235        offset: u64,
236        end_offset: u64,
237        buffer_size: u64,
238    },
239    #[error(transparent)]
240    ResourceUsageCompatibility(#[from] ResourceUsageCompatibilityError),
241    #[error(transparent)]
242    MissingBufferUsage(#[from] MissingBufferUsageError),
243    #[error(transparent)]
244    TraceRay(#[from] TraceRayError),
245    #[error(transparent)]
246    Bind(#[from] BindError),
247    #[error(transparent)]
248    ImmediateData(#[from] ImmediateUploadError),
249    #[error("Immediate data offset must be aligned to 4 bytes")]
250    ImmediateOffsetAlignment,
251    #[error("Immediate data size must be aligned to 4 bytes")]
252    ImmediateDataizeAlignment,
253    #[error("Ran out of immediate data space. Don't set 4gb of immediates per RayTracingPass.")]
254    ImmediateOutOfMemory,
255    #[error(transparent)]
256    MissingFeatures(#[from] MissingFeatures),
257    #[error(transparent)]
258    MissingDownlevelFlags(#[from] MissingDownlevelFlags),
259    #[error("The ray tracing pass has already been ended and no further commands can be recorded")]
260    PassEnded,
261    #[error(transparent)]
262    InvalidResource(#[from] InvalidResourceError),
263}
264
265impl From<InvalidOrDestroyedResourceError> for RayTracingPassErrorInner {
266    fn from(error: InvalidOrDestroyedResourceError) -> Self {
267        match error {
268            InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e),
269            InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e),
270        }
271    }
272}
273
274/// Error encountered when performing a ray tracing pass, stored for later reporting
275/// when encoding ends.
276#[derive(Clone, Debug, Error)]
277#[error("{scope}")]
278pub struct RayTracingPassError {
279    pub scope: PassErrorScope,
280    #[source]
281    pub(super) inner: Box<RayTracingPassErrorInner>,
282}
283
284impl From<pass::MissingPipeline> for RayTracingPassErrorInner {
285    fn from(value: pass::MissingPipeline) -> Self {
286        Self::TraceRay(TraceRayError::MissingPipeline(value))
287    }
288}
289
290impl<E> MapPassErr<RayTracingPassError> for E
291where
292    E: Into<RayTracingPassErrorInner>,
293{
294    fn map_pass_err(self, scope: PassErrorScope) -> RayTracingPassError {
295        RayTracingPassError {
296            scope,
297            inner: Box::new(self.into()),
298        }
299    }
300}
301
302impl WebGpuError for RayTracingPassError {
303    fn webgpu_error_type(&self) -> ErrorType {
304        match self.inner.as_ref() {
305            RayTracingPassErrorInner::Device(e) => e.webgpu_error_type(),
306            RayTracingPassErrorInner::EncoderState(e) => e.webgpu_error_type(),
307            RayTracingPassErrorInner::DebugGroupError(e) => e.webgpu_error_type(),
308            RayTracingPassErrorInner::DestroyedResource(e) => e.webgpu_error_type(),
309            RayTracingPassErrorInner::ResourceUsageCompatibility(e) => e.webgpu_error_type(),
310            RayTracingPassErrorInner::MissingBufferUsage(e) => e.webgpu_error_type(),
311            RayTracingPassErrorInner::TraceRay(e) => e.webgpu_error_type(),
312            RayTracingPassErrorInner::Bind(e) => e.webgpu_error_type(),
313            RayTracingPassErrorInner::ImmediateData(e) => e.webgpu_error_type(),
314            RayTracingPassErrorInner::MissingFeatures(e) => e.webgpu_error_type(),
315            RayTracingPassErrorInner::MissingDownlevelFlags(e) => e.webgpu_error_type(),
316            RayTracingPassErrorInner::InvalidResource(e) => e.webgpu_error_type(),
317
318            RayTracingPassErrorInner::InvalidParentEncoder
319            | RayTracingPassErrorInner::BindGroupIndexOutOfRange { .. }
320            | RayTracingPassErrorInner::UnalignedIndirectBufferOffset(_)
321            | RayTracingPassErrorInner::IndirectBufferOverrun { .. }
322            | RayTracingPassErrorInner::ImmediateOffsetAlignment
323            | RayTracingPassErrorInner::ImmediateDataizeAlignment
324            | RayTracingPassErrorInner::ImmediateOutOfMemory
325            | RayTracingPassErrorInner::PassEnded => ErrorType::Validation,
326        }
327    }
328}
329
330struct State<'scope, 'snatch_guard, 'cmd_enc> {
331    pipeline: Option<Arc<RayTracingPipeline>>,
332
333    pass: pass::PassState<'scope, 'snatch_guard, 'cmd_enc>,
334
335    intermediate_trackers: Tracker,
336}
337
338impl<'scope, 'snatch_guard, 'cmd_enc> State<'scope, 'snatch_guard, 'cmd_enc> {
339    fn is_ready(&self) -> Result<(), TraceRayError> {
340        if let Some(pipeline) = self.pipeline.as_ref() {
341            self.pass
342                .binder
343                .check_compatibility(pipeline.as_ref(), &pipeline.late_sized_buffer_groups)?;
344            if !self
345                .pass
346                .immediate_state
347                .immediate_slots_set
348                .contains(pipeline.immediate_slots_required)
349            {
350                return Err(TraceRayError::MissingImmediateData {
351                    missing: pipeline
352                        .immediate_slots_required
353                        .difference(self.pass.immediate_state.immediate_slots_set),
354                });
355            }
356            Ok(())
357        } else {
358            Err(TraceRayError::MissingPipeline(pass::MissingPipeline))
359        }
360    }
361
362    fn flush_immediates(&mut self) {
363        let pipeline = self.pipeline.as_ref().unwrap();
364        let layout = pipeline.layout().unwrap();
365        self.pass
366            .immediate_state
367            .flush_immediates(layout, self.pass.base.raw_encoder);
368    }
369
370    /// Flush binding state in preparation for a trace rays call.
371    ///
372    /// This behaves almost the same as a compute pass' equivalent
373    /// function, but also adds a `AsAction::TraceTlas` as trace ray
374    /// calls need a bit more validation.
375    ///
376    /// This differs from a render pass, which the equivalent method
377    /// on compute pass' state discuss more.
378    ///
379    /// `indirect_buffer` is checked for usage conflicts with the bound
380    /// resources. Set `track_indirect_buffer` when the trace reads it
381    /// directly, so it is transitioned to `INDIRECT`. Leave it unset when
382    /// indirect validation reads the buffer instead, which tracks it itself.
383    fn flush_bindings(
384        &mut self,
385        indirect_buffer: Option<&Arc<Buffer>>,
386        track_indirect_buffer: bool,
387    ) -> Result<(), RayTracingPassErrorInner> {
388        for bind_group in self.pass.binder.list_active() {
389            unsafe { self.pass.scope.merge_bind_group(&bind_group.used)? };
390        }
391
392        if let Some(buffer) = indirect_buffer {
393            self.pass
394                .scope
395                .buffers
396                .merge_single(buffer, wgt::BufferUses::INDIRECT)?;
397        }
398        // For ray tracing passes, usage scopes are associated with each trace
399        // ray (in the same way as compute passes) and not with the pass as a
400        // whole. However, because the cost of creating and dropping
401        // `UsageScope`s is significant (even with the pool), we add and then
402        // remove usage from a single usage scope.
403
404        let intersection_types = self.pipeline.as_ref().unwrap().intersection_types()?;
405
406        for bind_group in self.pass.binder.list_active() {
407            self.intermediate_trackers
408                .set_and_remove_from_usage_scope_sparse(&mut self.pass.scope, &bind_group.used);
409
410            for tlas in bind_group.used.acceleration_structures.into_iter() {
411                self.pass.base.as_actions.push(AsAction::TraceTlas(
412                    tlas.clone(),
413                    intersection_types.clone(),
414                ));
415            }
416        }
417
418        if track_indirect_buffer {
419            self.intermediate_trackers
420                .buffers
421                .set_and_remove_from_usage_scope_sparse(
422                    &mut self.pass.scope.buffers,
423                    indirect_buffer.map(|buf| buf.tracker_index()),
424                );
425        } else if let Some(buffer) = indirect_buffer {
426            self.pass
427                .scope
428                .buffers
429                .remove_usage(buffer, wgt::BufferUses::INDIRECT);
430        }
431
432        flush_bindings_helper(&mut self.pass)?;
433
434        CommandEncoder::drain_barriers(
435            self.pass.base.raw_encoder,
436            &mut self.intermediate_trackers,
437            self.pass.base.snatch_guard,
438        );
439        Ok(())
440    }
441}
442
443// Ray tracing pass commands
444
445impl RayTracingPass {
446    pub fn set_pipeline(&mut self, pipeline: Arc<RayTracingPipeline>) {
447        if let Err(err) = self.set_pipeline_inner(pipeline) {
448            self.device
449                .handle_error(err, self.label(), "RayTracingPass::set_pipeline");
450        }
451    }
452    pub fn set_pipeline_inner(
453        &mut self,
454        pipeline: Arc<RayTracingPipeline>,
455    ) -> Result<(), PassStateError> {
456        let scope = PassErrorScope::SetPipelineRayTracing;
457
458        let redundant = self.current_pipeline.set_and_check_redundant(&pipeline);
459
460        // This statement will return an error if the pass is ended.
461        // Its important the error check comes before the early-out for `redundant`.
462        let base = pass_base!(self, scope);
463
464        if redundant {
465            return Ok(());
466        }
467
468        pass_try!(base, scope, pipeline.check_valid());
469
470        base.commands
471            .push(ArcRayTracingCommand::SetPipeline(pipeline));
472
473        Ok(())
474    }
475    pub fn end_inner(&mut self) -> Result<(), EncoderStateError> {
476        profiling::scope!(
477            "CommandEncoder::run_ray_tracing_pass {}",
478            self.base.label.as_deref().unwrap_or("")
479        );
480
481        let cmd_enc = self.parent.take().ok_or(EncoderStateError::Ended)?;
482        let mut cmd_buf_data = cmd_enc.data.lock();
483
484        cmd_buf_data.unlock_encoder()?;
485
486        let base = self.base.take();
487
488        if let Err(RayTracingPassError { inner, scope: _ }) = &base {
489            if let RayTracingPassErrorInner::EncoderState(
490                err @ (EncoderStateError::Locked | EncoderStateError::Ended),
491            ) = inner.as_ref()
492            {
493                // Most encoding errors are detected and raised within `finish()`.
494                //
495                // However, we raise a validation error here if the pass was opened
496                // within another pass, or on a finished encoder. The latter is
497                // particularly important, because in that case reporting errors via
498                // `CommandEncoder::finish` is not possible.
499                return Err(err.clone());
500            }
501        }
502
503        cmd_buf_data.push_with(|| -> Result<_, RayTracingPassError> {
504            Ok(ArcCommand::RunRayTracingPass { pass: base? })
505        })
506    }
507
508    pub fn end(&mut self) {
509        if let Err(err) = self.end_inner() {
510            self.device
511                .handle_error(err, self.label(), "RayTracingPass::end");
512        }
513    }
514
515    pub fn push_debug_group_inner(
516        &mut self,
517        label: &str,
518        color: u32,
519    ) -> Result<(), PassStateError> {
520        let base = pass_base!(self, PassErrorScope::PushDebugGroup);
521
522        let bytes = label.as_bytes();
523        base.string_data.extend_from_slice(bytes);
524
525        base.commands.push(ArcRayTracingCommand::PushDebugGroup {
526            color,
527            len: bytes.len(),
528        });
529
530        Ok(())
531    }
532
533    pub fn push_debug_group(&mut self, label: &str, color: u32) {
534        if let Err(err) = self.push_debug_group_inner(label, color) {
535            self.device
536                .handle_error(err, self.label(), "RayTracingPass::push_debug_group");
537        }
538    }
539
540    pub fn pop_debug_group_inner(&mut self) -> Result<(), PassStateError> {
541        let base = pass_base!(self, PassErrorScope::PopDebugGroup);
542
543        base.commands.push(ArcRayTracingCommand::PopDebugGroup);
544
545        Ok(())
546    }
547
548    pub fn pop_debug_group(&mut self) {
549        if let Err(err) = self.pop_debug_group_inner() {
550            self.device
551                .handle_error(err, self.label(), "RayTracingPass::pop_debug_group");
552        }
553    }
554
555    pub fn insert_debug_marker_inner(
556        &mut self,
557        label: &str,
558        color: u32,
559    ) -> Result<(), PassStateError> {
560        let base = pass_base!(self, PassErrorScope::InsertDebugMarker);
561
562        let bytes = label.as_bytes();
563        base.string_data.extend_from_slice(bytes);
564
565        base.commands.push(ArcRayTracingCommand::InsertDebugMarker {
566            color,
567            len: bytes.len(),
568        });
569
570        Ok(())
571    }
572
573    pub fn insert_debug_marker(&mut self, label: &str, color: u32) {
574        if let Err(err) = self.insert_debug_marker_inner(label, color) {
575            self.device
576                .handle_error(err, self.label(), "RayTracingPass::insert_debug_marker");
577        }
578    }
579
580    pub fn trace_rays_inner(
581        &mut self,
582        count_x: u32,
583        count_y: u32,
584        count_z: u32,
585    ) -> Result<(), PassStateError> {
586        let scope = PassErrorScope::TraceRays { indirect: false };
587
588        pass_base!(self, scope)
589            .commands
590            .push(ArcRayTracingCommand::TraceRays([count_x, count_y, count_z]));
591
592        Ok(())
593    }
594
595    pub fn trace_rays(&mut self, count_x: u32, count_y: u32, count_z: u32) {
596        if let Err(err) = self.trace_rays_inner(count_x, count_y, count_z) {
597            self.device
598                .handle_error(err, self.label(), "RayTracingPass::trace_rays");
599        }
600    }
601
602    pub fn trace_rays_indirect_inner(
603        &mut self,
604        buffer: Arc<Buffer>,
605        offset: BufferAddress,
606    ) -> Result<(), PassStateError> {
607        let scope = PassErrorScope::TraceRays { indirect: true };
608        let base = pass_base!(self, scope);
609
610        pass_try!(base, scope, buffer.check_is_valid());
611
612        base.commands
613            .push(ArcRayTracingCommand::TraceRaysIndirect { buffer, offset });
614
615        Ok(())
616    }
617
618    pub fn trace_rays_indirect(&mut self, buffer: Arc<Buffer>, offset: BufferAddress) {
619        if let Err(err) = self.trace_rays_indirect_inner(buffer, offset) {
620            self.device
621                .handle_error(err, self.label(), "RayTracingPass::trace_rays_indirect");
622        }
623    }
624}
625
626impl CommandEncoder {
627    pub fn begin_ray_tracing_pass_inner(
628        self: &Arc<Self>,
629        desc: &RayTracingPassDescriptor<'_>,
630    ) -> (RayTracingPass, Option<CommandEncoderError>) {
631        use EncoderStateError as SErr;
632
633        let label = desc.label.as_deref().map(Cow::Borrowed);
634
635        let scope = PassErrorScope::Pass;
636
637        let mut cmd_buf_data = self.data.lock();
638
639        match cmd_buf_data.lock_encoder() {
640            Ok(()) => {
641                drop(cmd_buf_data);
642                if let Err(err) = self.device.check_is_valid() {
643                    return (
644                        RayTracingPass::new_invalid(self.clone(), &label, err.map_pass_err(scope)),
645                        None,
646                    );
647                }
648
649                let pass = match RayTracingPass::new(
650                    self.clone(),
651                    RayTracingPassDescriptor {
652                        label: label.clone(),
653                    },
654                ) {
655                    Ok(pass) => pass,
656                    Err(err) => {
657                        return (
658                            RayTracingPass::new_invalid(
659                                self.clone(),
660                                &label,
661                                err.map_pass_err(scope),
662                            ),
663                            None,
664                        );
665                    }
666                };
667
668                (pass, None)
669            }
670            Err(err @ SErr::Locked) => {
671                // Attempting to open a new pass while the encoder is locked
672                // invalidates the encoder, but does not generate a validation
673                // error.
674                cmd_buf_data.invalidate(err.clone());
675                drop(cmd_buf_data);
676                (
677                    RayTracingPass::new_invalid(self.clone(), &label, err.map_pass_err(scope)),
678                    None,
679                )
680            }
681            Err(err @ (SErr::Ended | SErr::Submitted)) => {
682                // Attempting to open a new pass after the encode has ended
683                // generates an immediate validation error.
684                drop(cmd_buf_data);
685                (
686                    RayTracingPass::new_invalid(
687                        self.clone(),
688                        &label,
689                        err.clone().map_pass_err(scope),
690                    ),
691                    Some(err.into()),
692                )
693            }
694            Err(err @ SErr::Invalid) => {
695                // Passes can be opened even on an invalid encoder. Such passes
696                // are even valid, but since there's no visible side-effect of
697                // the pass being valid and there's no point in storing recorded
698                // commands that will ultimately be discarded, we open an
699                // invalid pass to save that work.
700                drop(cmd_buf_data);
701                (
702                    RayTracingPass::new_invalid(self.clone(), &label, err.map_pass_err(scope)),
703                    None,
704                )
705            }
706            Err(SErr::Unlocked) => {
707                unreachable!("lock_encoder cannot fail due to the encoder being unlocked")
708            }
709        }
710    }
711
712    pub fn begin_ray_tracing_pass(
713        self: &Arc<Self>,
714        desc: &RayTracingPassDescriptor<'_>,
715    ) -> RayTracingPass {
716        let (pass, err) = self.begin_ray_tracing_pass_inner(desc);
717        if let Some(err) = err {
718            self.device
719                .handle_error(err, pass.label(), "CommandEncoder::begin_ray_tracing_pass");
720        }
721        pass
722    }
723}
724
725pub(super) fn encode_ray_tracing_pass(
726    parent_state: &mut EncodingState<InnerCommandEncoder>,
727    mut base: BasePass<ArcRayTracingCommand, Infallible>,
728) -> Result<(), RayTracingPassError> {
729    let pass_scope = PassErrorScope::Pass;
730
731    let device = parent_state.device;
732
733    // We automatically keep extending command buffers over time, and because
734    // we want to insert a command buffer _before_ what we're about to record,
735    // we need to make sure to close the previous one.
736    parent_state
737        .raw_encoder
738        .close_if_open()
739        .map_pass_err(pass_scope)?;
740    let raw_encoder = parent_state
741        .raw_encoder
742        .open_pass(base.label.as_deref())
743        .map_pass_err(pass_scope)?;
744
745    let mut debug_scope_depth = 0;
746
747    let mut state = State {
748        pipeline: None,
749
750        pass: pass::PassState {
751            base: EncodingState {
752                device,
753                raw_encoder,
754                tracker: parent_state.tracker,
755                buffer_memory_init_actions: parent_state.buffer_memory_init_actions,
756                texture_memory_actions: parent_state.texture_memory_actions,
757                as_actions: parent_state.as_actions,
758                temp_resources: parent_state.temp_resources,
759                indirect_draw_validation_resources: parent_state.indirect_draw_validation_resources,
760                snatch_guard: parent_state.snatch_guard,
761                debug_scope_depth: &mut debug_scope_depth,
762                query_set_writes: parent_state.query_set_writes,
763                deferred_query_set_resolves: parent_state.deferred_query_set_resolves,
764            },
765            binder: Binder::new(),
766            temp_offsets: Vec::new(),
767            dynamic_offset_count: 0,
768            pending_discard_init_fixups: SurfacesInDiscardState::new(),
769            scope: device.new_usage_scope(),
770            string_offset: 0,
771
772            immediate_state: ImmediateState::default(),
773        },
774
775        intermediate_trackers: Tracker::new(
776            device.ordered_buffer_usages,
777            device.ordered_texture_usages,
778        ),
779    };
780
781    let indices = &device.tracker_indices;
782    state
783        .pass
784        .base
785        .tracker
786        .buffers
787        .set_size(indices.buffers.size());
788    state
789        .pass
790        .base
791        .tracker
792        .textures
793        .set_size(indices.textures.size());
794
795    // The label is a debug marker around the hal pass, rather than the hal pass label, because
796    // indirect trace rays validation ends and restarts the hal pass.
797    let pass_label = hal_label(base.label.as_deref(), device.instance_flags);
798    if let Some(label) = pass_label {
799        unsafe { state.pass.base.raw_encoder.begin_debug_marker(label) };
800    }
801
802    unsafe {
803        state
804            .pass
805            .base
806            .raw_encoder
807            .begin_ray_tracing_pass(&hal::RayTracingPassDescriptor { label: None });
808    }
809
810    for command in base.commands.drain(..) {
811        match command {
812            ArcRayTracingCommand::SetBindGroup {
813                index,
814                num_dynamic_offsets,
815                bind_group,
816            } => {
817                let scope = PassErrorScope::SetBindGroup;
818                pass::set_bind_group::<RayTracingPassErrorInner>(
819                    &mut state.pass,
820                    device,
821                    &base.dynamic_offsets,
822                    index,
823                    num_dynamic_offsets,
824                    bind_group,
825                    false,
826                )
827                .map_pass_err(scope)?;
828            }
829            ArcRayTracingCommand::SetPipeline(pipeline) => {
830                let scope = PassErrorScope::SetPipelineRayTracing;
831                set_pipeline(&mut state, device, pipeline).map_pass_err(scope)?;
832            }
833            ArcRayTracingCommand::SetImmediate { offset, data } => {
834                let scope = PassErrorScope::SetImmediate;
835                state
836                    .pass
837                    .immediate_state
838                    .set_immediates::<RayTracingPassErrorInner>(
839                        &state.pass.base.device.limits,
840                        offset,
841                        &data,
842                    )
843                    .map_pass_err(scope)?;
844            }
845            ArcRayTracingCommand::PushDebugGroup { color: _, len } => {
846                pass::push_debug_group(&mut state.pass, &base.string_data, len);
847            }
848            ArcRayTracingCommand::PopDebugGroup => {
849                let scope = PassErrorScope::PopDebugGroup;
850                pass::pop_debug_group::<RayTracingPassErrorInner>(&mut state.pass)
851                    .map_pass_err(scope)?;
852            }
853            ArcRayTracingCommand::InsertDebugMarker { color: _, len } => {
854                pass::insert_debug_marker(&mut state.pass, &base.string_data, len);
855            }
856            ArcRayTracingCommand::TraceRays(groups) => {
857                let scope = PassErrorScope::TraceRays { indirect: false };
858                trace_rays(&mut state, groups, device).map_pass_err(scope)?;
859            }
860            ArcRayTracingCommand::TraceRaysIndirect { buffer, offset } => {
861                let scope = PassErrorScope::TraceRays { indirect: true };
862                trace_rays_indirect(&mut state, device, buffer, offset).map_pass_err(scope)?;
863            }
864        }
865    }
866
867    if *state.pass.base.debug_scope_depth > 0 {
868        Err(
869            RayTracingPassErrorInner::DebugGroupError(DebugGroupError::MissingPop)
870                .map_pass_err(pass_scope),
871        )?;
872    }
873
874    unsafe {
875        state.pass.base.raw_encoder.end_ray_tracing_pass();
876    }
877    if pass_label.is_some() {
878        unsafe { state.pass.base.raw_encoder.end_debug_marker() };
879    }
880
881    let State {
882        pass: pass::PassState {
883            pending_discard_init_fixups,
884            ..
885        },
886        intermediate_trackers,
887        ..
888    } = state;
889
890    // Stop the current command encoder.
891    parent_state.raw_encoder.close().map_pass_err(pass_scope)?;
892
893    // Create a new command encoder, which we will insert _before_ the body of the ray tracing pass.
894    //
895    // Use that buffer to insert barriers and clear discarded images.
896    let transit = parent_state
897        .raw_encoder
898        .open_pass(hal_label(
899            Some("(wgpu internal) Pre Pass"),
900            device.instance_flags,
901        ))
902        .map_pass_err(pass_scope)?;
903    // If the ray tracing pass reads any surfaces that were discarded by a previous
904    // render pass in the same command buffer, initialize them.
905    fixup_discarded_surfaces(
906        pending_discard_init_fixups.into_iter(),
907        transit,
908        &mut parent_state.tracker.textures,
909        device,
910        parent_state.snatch_guard,
911    );
912    CommandEncoder::insert_barriers_from_tracker(
913        transit,
914        parent_state.tracker,
915        &intermediate_trackers,
916        parent_state.snatch_guard,
917    );
918    // Close the command encoder, and swap it with the previous.
919    parent_state
920        .raw_encoder
921        .close_and_swap()
922        .map_pass_err(pass_scope)?;
923
924    Ok(())
925}
926
927fn set_pipeline(
928    state: &mut State,
929    device: &Arc<Device>,
930    pipeline: Arc<RayTracingPipeline>,
931) -> Result<(), RayTracingPassErrorInner> {
932    pipeline.same_device(device)?;
933
934    state.pipeline = Some(pipeline.clone());
935
936    let pipeline = state
937        .pass
938        .base
939        .tracker
940        .ray_tracing_pipelines
941        .insert_single(pipeline)
942        .clone();
943
944    unsafe {
945        state
946            .pass
947            .base
948            .raw_encoder
949            .set_ray_tracing_pipeline(pipeline.raw()?);
950    }
951
952    // Rebind resources
953    let pipeline_layout = pipeline.layout()?;
954    pass::change_pipeline_layout::<RayTracingPassErrorInner>(&mut state.pass, pipeline_layout)
955}
956
957/// The maximum number of rays per dimension of a trace rays call.
958///
959/// These are the per-dimension limits Vulkan requires for `vkCmdTraceRaysKHR`.
960pub(crate) fn max_trace_rays_dimensions(limits: &wgt::Limits) -> [u32; 3] {
961    // `saturating_mul` is fine here as it is the limit, so a lower limit if it would overflow is just a
962    // slightly greater restriction.
963    [
964        limits
965            .max_compute_workgroup_size_x
966            .saturating_mul(limits.max_compute_workgroups_per_dimension),
967        limits
968            .max_compute_workgroup_size_y
969            .saturating_mul(limits.max_compute_workgroups_per_dimension),
970        limits
971            .max_compute_workgroup_size_z
972            .saturating_mul(limits.max_compute_workgroups_per_dimension),
973    ]
974}
975
976/// Returns the ray generation, miss and intersection group data of `pipeline`.
977fn shader_binding_table<'a>(
978    pipeline: &'a RayTracingPipeline,
979    device: &Device,
980) -> Result<[hal::PipelineGroupData<'a, dyn hal::DynBuffer>; 3], InvalidResourceError> {
981    let shader_binding_data = pipeline.shader_binding_data()?;
982    let stride = device.alignments.ray_tracing_pipeline_group_data_size as _;
983    Ok([
984        hal::PipelineGroupData {
985            buffer: shader_binding_data.raw.as_ref(),
986            offset: 0,
987            stride,
988            count: 1,
989        },
990        hal::PipelineGroupData {
991            buffer: shader_binding_data.raw.as_ref(),
992            offset: shader_binding_data.miss_offset,
993            stride,
994            count: 1,
995        },
996        hal::PipelineGroupData {
997            buffer: shader_binding_data.raw.as_ref(),
998            offset: shader_binding_data.intersection_offset,
999            stride,
1000            count: shader_binding_data.num_intersection_groups as _,
1001        },
1002    ])
1003}
1004
1005fn trace_rays(
1006    state: &mut State,
1007    dims: [u32; 3],
1008    device: &Device,
1009) -> Result<(), RayTracingPassErrorInner> {
1010    api_log!("RayTracingPass::trace_rays {dims:?}");
1011
1012    state.is_ready()?;
1013
1014    state.flush_bindings(None, false)?;
1015    state.flush_immediates();
1016
1017    let limits = &state.pass.base.device.limits;
1018
1019    let dim_size_limit = max_trace_rays_dimensions(limits);
1020
1021    if dims
1022        .iter()
1023        .zip(dim_size_limit)
1024        .any(|(&dim, limit)| dim > limit)
1025    {
1026        return Err(RayTracingPassErrorInner::TraceRay(
1027            TraceRayError::InvalidDimensionSize {
1028                current: dims,
1029                limit: dim_size_limit,
1030            },
1031        ));
1032    }
1033
1034    let tot_rays = dims[0]
1035        .checked_mul(dims[1])
1036        .and_then(|tmp| tmp.checked_mul(dims[2]));
1037
1038    if tot_rays.is_none_or(|tot_rays| tot_rays > limits.max_ray_dispatch_count) {
1039        return Err(RayTracingPassErrorInner::TraceRay(
1040            TraceRayError::TooManyTotal {
1041                current: tot_rays.unwrap_or(u32::MAX),
1042                limit: limits.max_ray_dispatch_count,
1043            },
1044        ));
1045    }
1046
1047    let [ray_generation, miss, intersection] =
1048        shader_binding_table(state.pipeline.as_ref().unwrap(), device)?;
1049
1050    unsafe {
1051        state
1052            .pass
1053            .base
1054            .raw_encoder
1055            .trace_rays(dims, ray_generation, miss, intersection);
1056    }
1057    Ok(())
1058}
1059
1060fn trace_rays_indirect(
1061    state: &mut State,
1062    device: &Arc<Device>,
1063    buffer: Arc<Buffer>,
1064    offset: u64,
1065) -> Result<(), RayTracingPassErrorInner> {
1066    api_log!("RayTracingPass::trace_rays_indirect");
1067
1068    buffer.same_device(device)?;
1069
1070    device.require_features(wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES_INDIRECT)?;
1071
1072    state.is_ready()?;
1073
1074    state
1075        .pass
1076        .base
1077        .device
1078        .require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)?;
1079
1080    buffer.check_usage(wgt::BufferUsages::INDIRECT)?;
1081
1082    if !offset.is_multiple_of(4) {
1083        return Err(RayTracingPassErrorInner::UnalignedIndirectBufferOffset(
1084            offset,
1085        ));
1086    }
1087
1088    let args_size = size_of::<wgt::DispatchIndirectArgs>() as u64;
1089    let end_offset = offset.saturating_add(args_size);
1090    if end_offset > buffer.size {
1091        return Err(RayTracingPassErrorInner::IndirectBufferOverrun {
1092            offset,
1093            end_offset,
1094            buffer_size: buffer.size,
1095        });
1096    }
1097
1098    buffer.check_destroyed(state.pass.base.snatch_guard)?;
1099
1100    state.pass.base.buffer_memory_init_actions.extend(
1101        buffer.initialization_status.read().create_action(
1102            &buffer,
1103            offset..end_offset,
1104            MemoryInitKind::NeedsInitializedMemory,
1105        ),
1106    );
1107
1108    let (indirect_buffer, indirect_offset) = if let Some(ref indirect_validation) =
1109        state.pass.base.device.indirect_validation
1110    {
1111        let params = indirect_validation
1112            .dispatch
1113            .trace_rays_params(&state.pass.base.device.limits, offset, buffer.size)
1114            .expect("Indirect trace rays requires `Features::EXPERIMENTAL_RAY_TRACING_PIPELINES_INDIRECT`");
1115
1116        // The validation runs a compute dispatch, which needs a compute pass.
1117        unsafe {
1118            let raw_encoder = &mut *state.pass.base.raw_encoder;
1119            raw_encoder.end_ray_tracing_pass();
1120            raw_encoder.begin_compute_pass(&hal::ComputePassDescriptor {
1121                label: None,
1122                timestamp_writes: None,
1123            });
1124            raw_encoder.set_compute_pipeline(params.pipeline);
1125            raw_encoder.set_immediates(
1126                params.pipeline_layout,
1127                0,
1128                &[params.offset_remainder as u32 / 4],
1129            );
1130            raw_encoder.set_bind_group(params.pipeline_layout, 0, params.dst_bind_group, &[]);
1131            raw_encoder.set_bind_group(
1132                params.pipeline_layout,
1133                1,
1134                buffer
1135                    .indirect_validation_bind_groups
1136                    .get(state.pass.base.snatch_guard)
1137                    .unwrap()
1138                    .dispatch
1139                    .as_ref(),
1140                &[params.aligned_offset as u32],
1141            );
1142        }
1143
1144        let src_transition = state
1145            .intermediate_trackers
1146            .buffers
1147            .set_single(&buffer, wgt::BufferUses::STORAGE_READ_ONLY);
1148        let src_barrier = src_transition
1149            .map(|transition| transition.into_hal(&buffer, state.pass.base.snatch_guard));
1150
1151        unsafe {
1152            let raw_encoder = &mut *state.pass.base.raw_encoder;
1153            raw_encoder.transition_buffers(src_barrier.as_slice());
1154            raw_encoder.transition_buffers(&[hal::BufferBarrier {
1155                buffer: params.dst_buffer,
1156                usage: hal::StateTransition {
1157                    from: wgt::BufferUses::INDIRECT,
1158                    to: wgt::BufferUses::STORAGE_READ_WRITE,
1159                },
1160            }]);
1161            raw_encoder.dispatch_workgroups([1, 1, 1]);
1162            raw_encoder.transition_buffers(&[hal::BufferBarrier {
1163                buffer: params.dst_buffer,
1164                usage: hal::StateTransition {
1165                    from: wgt::BufferUses::STORAGE_READ_WRITE,
1166                    to: wgt::BufferUses::INDIRECT,
1167                },
1168            }]);
1169            raw_encoder.end_compute_pass();
1170            raw_encoder.begin_ray_tracing_pass(&hal::RayTracingPassDescriptor { label: None });
1171        }
1172
1173        // Restore the ray tracing pass state.
1174        let pipeline = state.pipeline.as_ref().unwrap();
1175        unsafe {
1176            state
1177                .pass
1178                .base
1179                .raw_encoder
1180                .set_ray_tracing_pipeline(pipeline.raw()?);
1181        }
1182        let pipeline_layout = pipeline.layout()?.raw()?;
1183        for (i, group, dynamic_offsets) in state.pass.binder.list_valid() {
1184            let raw_bg = group.try_raw(state.pass.base.snatch_guard)?;
1185            unsafe {
1186                state.pass.base.raw_encoder.set_bind_group(
1187                    pipeline_layout,
1188                    i as u32,
1189                    raw_bg,
1190                    dynamic_offsets,
1191                );
1192            }
1193        }
1194        state.pass.immediate_state.immediates_dirty = true;
1195
1196        state.flush_bindings(Some(&buffer), false)?;
1197        (params.dst_buffer, 0)
1198    } else {
1199        state.flush_bindings(Some(&buffer), true)?;
1200        (buffer.try_raw(state.pass.base.snatch_guard)?, offset)
1201    };
1202    state.flush_immediates();
1203
1204    let [ray_generation, miss, intersection] =
1205        shader_binding_table(state.pipeline.as_ref().unwrap(), device)?;
1206
1207    unsafe {
1208        state.pass.base.raw_encoder.trace_rays_indirect(
1209            indirect_buffer,
1210            indirect_offset,
1211            ray_generation,
1212            miss,
1213            intersection,
1214        );
1215    }
1216    Ok(())
1217}