Skip to main content

wgpu_core/
ray_tracing.rs

1// Ray tracing
2// Major missing optimizations (no api surface changes needed):
3// - use custom tracker to track build state
4// - no forced rebuilt (build mode deduction)
5// - lazy instance buffer allocation
6// - maybe share scratch and instance staging buffer allocation
7// - partial instance buffer uploads (api surface already designed with this in mind)
8// - Batch BLAS read-backs (if it shows up in performance).
9// - ([non performance] extract function in build (rust function extraction with guards is a pain))
10
11use alloc::{boxed::Box, sync::Arc, vec::Vec};
12
13#[cfg(feature = "serde")]
14use macro_rules_attribute::apply;
15use thiserror::Error;
16use wgt::{
17    error::{ErrorType, WebGpuError},
18    AccelerationStructureGeometryFlags, BufferAddress, IndexFormat, VertexFormat,
19};
20
21#[cfg(feature = "serde")]
22use crate::command::serde_object_reference_struct;
23use crate::{
24    command::{ArcReferences, EncoderStateError, ReferenceType},
25    device::{DeviceError, MissingFeatures},
26    resource::{
27        self, Blas, BlasCompactCallback, BlasPrepareCompactResult, DestroyedResourceError,
28        InvalidResourceError, MissingBufferUsageError, ResourceErrorIdent, Tlas,
29    },
30};
31
32#[derive(Clone, Debug, Error)]
33pub enum CreateBlasError {
34    #[error(transparent)]
35    Device(#[from] DeviceError),
36    #[error(transparent)]
37    MissingFeatures(#[from] MissingFeatures),
38    #[error(
39        "Only one of 'index_count' and 'index_format' was provided (either provide both or none)"
40    )]
41    MissingIndexData,
42    #[error("Provided format was not within allowed formats. Provided format: {0:?}. Allowed formats: {1:?}")]
43    InvalidVertexFormat(VertexFormat, Vec<VertexFormat>),
44    #[error("Limit `max_blas_geometry_count` is {0}, but the BLAS had {1} geometries")]
45    TooManyGeometries(u32, u32),
46    #[error(
47        "Limit `max_blas_primitive_count` is {0}, but the BLAS had a maximum of {1} primitives"
48    )]
49    TooManyPrimitives(u32, u32),
50}
51
52impl WebGpuError for CreateBlasError {
53    fn webgpu_error_type(&self) -> ErrorType {
54        match self {
55            Self::Device(e) => e.webgpu_error_type(),
56            Self::MissingFeatures(e) => e.webgpu_error_type(),
57            Self::MissingIndexData
58            | Self::InvalidVertexFormat(..)
59            | Self::TooManyGeometries(..)
60            | Self::TooManyPrimitives(..) => ErrorType::Validation,
61        }
62    }
63}
64
65#[derive(Clone, Debug, Error)]
66pub enum CreateTlasError {
67    #[error(transparent)]
68    Device(#[from] DeviceError),
69    #[error(transparent)]
70    MissingFeatures(#[from] MissingFeatures),
71    #[error("Flag {0:?} is not allowed on a TLAS")]
72    DisallowedFlag(wgt::AccelerationStructureFlags),
73    #[error("Limit `max_tlas_instance_count` is {0}, but the TLAS had a maximum of {1} instances")]
74    TooManyInstances(u32, u32),
75}
76
77impl WebGpuError for CreateTlasError {
78    fn webgpu_error_type(&self) -> ErrorType {
79        match self {
80            Self::Device(e) => e.webgpu_error_type(),
81            Self::MissingFeatures(e) => e.webgpu_error_type(),
82            Self::DisallowedFlag(..) | Self::TooManyInstances(..) => ErrorType::Validation,
83        }
84    }
85}
86
87/// Error encountered while attempting to do a copy on a command encoder.
88#[derive(Clone, Debug, Error)]
89pub enum BuildAccelerationStructureError {
90    #[error(transparent)]
91    EncoderState(#[from] EncoderStateError),
92
93    #[error(transparent)]
94    Device(#[from] DeviceError),
95
96    #[error(transparent)]
97    InvalidResource(#[from] InvalidResourceError),
98
99    #[error(transparent)]
100    DestroyedResource(#[from] DestroyedResourceError),
101
102    #[error(transparent)]
103    MissingBufferUsage(#[from] MissingBufferUsageError),
104
105    #[error(transparent)]
106    MissingFeatures(#[from] MissingFeatures),
107
108    #[error(
109        "Data range of {region_size} B starting at offset {offset} would overrun the size {buffer_size} of buffer {buffer_ident:?}"
110    )]
111    InsufficientBufferSize {
112        buffer_ident: ResourceErrorIdent,
113        offset: BufferAddress,
114        region_size: BufferAddress,
115        buffer_size: BufferAddress,
116    },
117
118    #[error(
119        "Offset {offset}, computed as {count} times {stride} B, exceeds the maximum addressable offset 2^32 - 1 within buffer {buffer_ident:?}"
120    )]
121    OffsetLimitedTo4GB {
122        buffer_ident: ResourceErrorIdent,
123        offset: BufferAddress,
124        count: BufferAddress,
125        stride: BufferAddress,
126    },
127
128    #[error("Buffer {0:?} associated offset doesn't align with the index type")]
129    UnalignedIndexBufferOffset(ResourceErrorIdent),
130
131    #[error("Buffer {0:?} associated offset is unaligned")]
132    UnalignedTransformBufferOffset(ResourceErrorIdent),
133
134    #[error("Buffer {0:?} associated index count not divisible by 3 (count: {1}")]
135    InvalidIndexCount(ResourceErrorIdent, u32),
136
137    #[error("Buffer {0:?} associated data contains None")]
138    MissingAssociatedData(ResourceErrorIdent),
139
140    #[error(
141        "Blas {0:?} build sizes to may be greater than the descriptor at build time specified"
142    )]
143    IncompatibleBlasBuildSizes(ResourceErrorIdent),
144
145    #[error("Blas {0:?} flags are different, creation flags: {1:?}, provided: {2:?}")]
146    IncompatibleBlasFlags(
147        ResourceErrorIdent,
148        AccelerationStructureGeometryFlags,
149        AccelerationStructureGeometryFlags,
150    ),
151
152    #[error("Blas {0:?} build vertex count is greater than creation count (needs to be less than or equal to), creation: {1:?}, build: {2:?}")]
153    IncompatibleBlasVertexCount(ResourceErrorIdent, u32, u32),
154
155    #[error("Blas {0:?} vertex formats are different, creation format: {1:?}, provided: {2:?}")]
156    DifferentBlasVertexFormats(ResourceErrorIdent, VertexFormat, VertexFormat),
157
158    #[error("Blas {0:?} stride was required to be at least {1} but stride given was {2}")]
159    VertexStrideTooSmall(ResourceErrorIdent, u64, u64),
160
161    #[error("Blas {0:?} stride was required to be a multiple of {1} but stride given was {2}")]
162    VertexStrideUnaligned(ResourceErrorIdent, u64, u64),
163
164    #[error("Blas {0:?} index count was provided at creation or building, but not the other")]
165    BlasIndexCountProvidedMismatch(ResourceErrorIdent),
166
167    #[error("Blas {0:?} build index count is greater than creation count (needs to be less than or equal to), creation: {1:?}, build: {2:?}")]
168    IncompatibleBlasIndexCount(ResourceErrorIdent, u32, u32),
169
170    #[error("Blas {0:?} index formats are different, creation format: {1:?}, provided: {2:?}")]
171    DifferentBlasIndexFormats(ResourceErrorIdent, Option<IndexFormat>, Option<IndexFormat>),
172
173    #[error("Blas {0:?} is compacted and so cannot be built")]
174    CompactedBlas(ResourceErrorIdent),
175
176    #[error("Blas {0:?} build sizes require index buffer but none was provided")]
177    MissingIndexBuffer(ResourceErrorIdent),
178
179    #[error("Tlas {0:?} instance {1} contains an invalid custom data (more than 24bits)")]
180    TlasInvalidCustomData(ResourceErrorIdent, usize),
181
182    #[error(
183        "Tlas {0:?} has {1} active instances but only {2} are allowed as specified by the descriptor at creation"
184    )]
185    TlasInstanceCountExceeded(ResourceErrorIdent, u32, u32),
186
187    #[error("Blas {0:?} has flag USE_TRANSFORM but the transform buffer is missing")]
188    TransformMissing(ResourceErrorIdent),
189
190    #[error("Blas {0:?} is missing the flag USE_TRANSFORM but the transform buffer is set")]
191    UseTransformMissing(ResourceErrorIdent),
192    #[error(
193        "Tlas {0:?} dependent {1:?} is missing AccelerationStructureFlags::ALLOW_RAY_HIT_VERTEX_RETURN"
194    )]
195    TlasDependentMissingVertexReturn(ResourceErrorIdent, ResourceErrorIdent),
196
197    #[error("Blas {0:?} geometry kind at creation does not match build (triangles vs AABBs)")]
198    BlasGeometryKindMismatch(ResourceErrorIdent),
199
200    #[error(
201        "Blas {0:?} build AABB primitive count is greater than creation count (creation: {1}, build: {2})"
202    )]
203    IncompatibleBlasAabbPrimitiveCount(ResourceErrorIdent, u32, u32),
204
205    #[error("Blas {0:?} AABB primitive offset must be a multiple of 8")]
206    UnalignedAabbPrimitiveOffset(ResourceErrorIdent),
207
208    #[error("Blas {0:?} AABB stride is invalid (must be >= {1} and a multiple of 8)")]
209    InvalidAabbStride(ResourceErrorIdent, BufferAddress),
210    #[error(
211        "Tlas {0:?} instance {1} contains an intersection index {2} which is greater than 2^24 - 1"
212    )]
213    TlasInvalidIntersectionIndex(ResourceErrorIdent, usize, u32),
214
215    #[error("Tlas instance has invalid flags {0:?}")]
216    TlasInstanceFlagsInvalid(wgt::AccelerationStructureInstanceFlags),
217}
218
219impl WebGpuError for BuildAccelerationStructureError {
220    fn webgpu_error_type(&self) -> ErrorType {
221        match self {
222            Self::EncoderState(e) => e.webgpu_error_type(),
223            Self::Device(e) => e.webgpu_error_type(),
224            Self::InvalidResource(e) => e.webgpu_error_type(),
225            Self::DestroyedResource(e) => e.webgpu_error_type(),
226            Self::MissingBufferUsage(e) => e.webgpu_error_type(),
227            Self::MissingFeatures(e) => e.webgpu_error_type(),
228            Self::InsufficientBufferSize { .. }
229            | Self::OffsetLimitedTo4GB { .. }
230            | Self::UnalignedIndexBufferOffset(..)
231            | Self::UnalignedTransformBufferOffset(..)
232            | Self::InvalidIndexCount(..)
233            | Self::MissingAssociatedData(..)
234            | Self::IncompatibleBlasBuildSizes(..)
235            | Self::IncompatibleBlasFlags(..)
236            | Self::IncompatibleBlasVertexCount(..)
237            | Self::DifferentBlasVertexFormats(..)
238            | Self::VertexStrideTooSmall(..)
239            | Self::VertexStrideUnaligned(..)
240            | Self::BlasIndexCountProvidedMismatch(..)
241            | Self::IncompatibleBlasIndexCount(..)
242            | Self::DifferentBlasIndexFormats(..)
243            | Self::CompactedBlas(..)
244            | Self::MissingIndexBuffer(..)
245            | Self::TlasInvalidCustomData(..)
246            | Self::TlasInstanceCountExceeded(..)
247            | Self::TransformMissing(..)
248            | Self::UseTransformMissing(..)
249            | Self::TlasDependentMissingVertexReturn(..)
250            | Self::TlasInvalidIntersectionIndex(..)
251            | Self::BlasGeometryKindMismatch(..)
252            | Self::IncompatibleBlasAabbPrimitiveCount(..)
253            | Self::UnalignedAabbPrimitiveOffset(..)
254            | Self::InvalidAabbStride(..)
255            | Self::TlasInstanceFlagsInvalid(..) => ErrorType::Validation,
256        }
257    }
258}
259
260#[derive(Clone, Debug, Error)]
261pub enum ValidateAsActionsError {
262    #[error(transparent)]
263    DestroyedResource(#[from] DestroyedResourceError),
264
265    #[error("Tlas {0:?} is used before it is built")]
266    UsedUnbuiltTlas(ResourceErrorIdent),
267
268    #[error("Blas {0:?} is used before it is built (in Tlas {1:?})")]
269    UsedUnbuiltBlas(ResourceErrorIdent, ResourceErrorIdent),
270
271    #[error("Blas {0:?} is newer than the containing Tlas {1:?}")]
272    BlasNewerThenTlas(ResourceErrorIdent, ResourceErrorIdent),
273
274    #[error("Tlas {0:?} has an intersection index {1:?} out of bounds of the length of the intersection array {2:?}")]
275    TlasIntersectionInvalid(ResourceErrorIdent, u32, u32),
276
277    #[error("An instance of Tlas {0:?} requires an intersection type of {1:?} for index {2}, but got {3:?}")]
278    TlasInstancesIntersectionIndicesDiffer(
279        ResourceErrorIdent,
280        crate::ray_tracing_pipeline::RayTracingIntersectionType,
281        u32,
282        Option<crate::ray_tracing_pipeline::RayTracingIntersectionType>,
283    ),
284}
285
286impl WebGpuError for ValidateAsActionsError {
287    fn webgpu_error_type(&self) -> ErrorType {
288        match self {
289            Self::DestroyedResource(e) => e.webgpu_error_type(),
290            Self::UsedUnbuiltTlas(..)
291            | Self::UsedUnbuiltBlas(..)
292            | Self::BlasNewerThenTlas(..)
293            | Self::TlasIntersectionInvalid(..)
294            | Self::TlasInstancesIntersectionIndicesDiffer(..) => ErrorType::Validation,
295        }
296    }
297}
298
299#[derive(Debug)]
300pub struct BlasTriangleGeometry<'a, Buffer = Arc<resource::Buffer>> {
301    pub size: &'a wgt::BlasTriangleGeometrySizeDescriptor,
302    pub vertex_buffer: Buffer,
303    pub index_buffer: Option<Buffer>,
304    pub transform_buffer: Option<Buffer>,
305    pub first_vertex: u32,
306    pub vertex_stride: BufferAddress,
307    pub first_index: Option<u32>,
308    pub transform_buffer_offset: Option<BufferAddress>,
309}
310
311#[derive(Debug)]
312pub struct BlasAabbGeometry<'a, Buffer = Arc<resource::Buffer>> {
313    pub size: &'a wgt::BlasAABBGeometrySizeDescriptor,
314    pub stride: BufferAddress,
315    pub aabb_buffer: Buffer,
316    pub primitive_offset: u32,
317}
318
319pub enum BlasGeometries<'a, Buffer = Arc<resource::Buffer>> {
320    TriangleGeometries(Box<dyn Iterator<Item = BlasTriangleGeometry<'a, Buffer>> + 'a>),
321    AabbGeometries(Box<dyn Iterator<Item = BlasAabbGeometry<'a, Buffer>> + 'a>),
322}
323
324pub struct BlasBuildEntry<'a, Blas = Arc<resource::Blas>, Buffer = Arc<resource::Buffer>> {
325    pub blas: Blas,
326    pub geometries: BlasGeometries<'a, Buffer>,
327}
328
329#[derive(Debug, Clone)]
330#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
331pub struct TlasBuildEntry<Tlas = Arc<resource::Tlas>, Buffer = Arc<resource::Buffer>> {
332    pub tlas: Tlas,
333    pub instance_buffer: Buffer,
334    pub instance_count: u32,
335}
336
337#[derive(Debug)]
338pub struct TlasInstance<'a, Blas = Arc<resource::Blas>> {
339    pub blas: Blas,
340    pub transform: &'a [f32; 12],
341    pub custom_data: u32,
342    pub mask: u8,
343    pub intersection_index: u32,
344}
345
346pub struct TlasPackage<'a, Tlas = Arc<resource::Tlas>, Blas = Arc<resource::Blas>> {
347    pub tlas: Tlas,
348    pub instances: Box<dyn Iterator<Item = Option<TlasInstance<'a, Blas>>> + 'a>,
349    pub lowest_unmodified: u32,
350}
351
352#[derive(Debug, Clone)]
353pub(crate) struct TlasBuild {
354    pub tlas: Arc<Tlas>,
355    pub dependencies: Vec<Arc<Blas>>,
356    pub max_intersection_idx: Option<u32>,
357    pub required_intersection_types: Vec<resource::TlasIntersectionType>,
358}
359
360#[derive(Debug, Clone, Default)]
361pub(crate) struct AsBuild {
362    pub blas_s_built: Vec<Arc<Blas>>,
363    pub tlas_s_built: Vec<TlasBuild>,
364}
365
366impl AsBuild {
367    pub(crate) fn with_capacity(blas: usize, tlas: usize) -> Self {
368        Self {
369            blas_s_built: Vec::with_capacity(blas),
370            tlas_s_built: Vec::with_capacity(tlas),
371        }
372    }
373}
374
375#[derive(Debug, Clone)]
376pub(crate) enum AsAction {
377    Build(AsBuild),
378    /// A [`Tlas`] has been bound and used by any pass. The [`Blas`]es it
379    /// was built with must be validated to have not been built after the
380    /// [`Tlas`] as backends have undefined behaviour on this (it would
381    /// cause AABBs to be incorrect, etc.)
382    BindTlas(Arc<Tlas>),
383    /// A [`RayTracingPipeline`] has had a `trace_rays` call on it.
384    /// This [`Tlas`] has been put in a bindgroup, and so the validation
385    /// must ensure that the maximum intersection index in the [`Tlas`] is
386    /// less than the length of the intersection group array and that the
387    /// types of the [`Blas`]es are the same as those of the
388    /// [`RayTracingPipeline`].
389    ///
390    /// [`RayTracingPipeline`]: crate::ray_tracing_pipeline::RayTracingPipeline
391    TraceTlas(
392        Arc<Tlas>,
393        Arc<[crate::ray_tracing_pipeline::RayTracingIntersectionType]>,
394    ),
395}
396
397/// Like [`BlasTriangleGeometry`], but with owned data.
398#[derive(Debug, Clone)]
399#[cfg_attr(feature = "serde", apply(serde_object_reference_struct))]
400pub struct OwnedBlasTriangleGeometry<R: ReferenceType> {
401    pub size: wgt::BlasTriangleGeometrySizeDescriptor,
402    pub vertex_buffer: R::Buffer,
403    pub index_buffer: Option<R::Buffer>,
404    pub transform_buffer: Option<R::Buffer>,
405    pub first_vertex: u32,
406    pub vertex_stride: BufferAddress,
407    pub first_index: Option<u32>,
408    pub transform_buffer_offset: Option<BufferAddress>,
409}
410
411pub type ArcBlasTriangleGeometry = OwnedBlasTriangleGeometry<ArcReferences>;
412
413#[derive(Debug, Clone)]
414#[cfg_attr(feature = "serde", apply(serde_object_reference_struct))]
415pub struct OwnedBlasAabbGeometry<R: ReferenceType> {
416    pub size: wgt::BlasAABBGeometrySizeDescriptor,
417    pub stride: BufferAddress,
418    pub aabb_buffer: R::Buffer,
419    pub primitive_offset: u32,
420}
421
422pub type ArcBlasAabbGeometry = OwnedBlasAabbGeometry<ArcReferences>;
423
424#[derive(Debug, Clone)]
425#[cfg_attr(feature = "serde", apply(serde_object_reference_struct))]
426pub enum OwnedBlasGeometries<R: ReferenceType> {
427    TriangleGeometries(Vec<OwnedBlasTriangleGeometry<R>>),
428    AabbGeometries(Vec<OwnedBlasAabbGeometry<R>>),
429}
430
431pub type ArcBlasGeometries = OwnedBlasGeometries<ArcReferences>;
432
433#[derive(Debug, Clone)]
434#[cfg_attr(feature = "serde", apply(serde_object_reference_struct))]
435pub struct OwnedBlasBuildEntry<R: ReferenceType> {
436    pub blas: R::Blas,
437    pub geometries: OwnedBlasGeometries<R>,
438}
439
440pub type ArcBlasBuildEntry = OwnedBlasBuildEntry<ArcReferences>;
441
442#[derive(Debug, Clone)]
443#[cfg_attr(feature = "serde", apply(serde_object_reference_struct))]
444pub struct OwnedTlasInstance<R: ReferenceType> {
445    pub blas: R::Blas,
446    pub transform: [f32; 12],
447    pub custom_data: u32,
448    pub mask: u8,
449    pub intersection_index: u32,
450    pub flags: wgt::AccelerationStructureInstanceFlags,
451}
452
453pub type ArcTlasInstance = OwnedTlasInstance<ArcReferences>;
454
455#[derive(Debug, Clone)]
456#[cfg_attr(feature = "serde", apply(serde_object_reference_struct))]
457pub struct OwnedTlasPackage<R: ReferenceType> {
458    pub tlas: R::Tlas,
459    pub instances: Vec<Option<OwnedTlasInstance<R>>>,
460    pub lowest_unmodified: u32,
461}
462
463pub type ArcTlasPackage = OwnedTlasPackage<ArcReferences>;
464
465/// [`BlasTriangleGeometry`], without the resources.
466#[derive(Debug, Clone)]
467pub struct BlasTriangleGeometryInfo {
468    pub size: wgt::BlasTriangleGeometrySizeDescriptor,
469    pub first_vertex: u32,
470    pub vertex_stride: BufferAddress,
471    pub first_index: Option<u32>,
472    pub transform_buffer_offset: Option<BufferAddress>,
473}
474
475#[derive(Clone, Debug, Error)]
476pub enum BlasPrepareCompactError {
477    #[error(transparent)]
478    Device(#[from] DeviceError),
479    #[error(transparent)]
480    InvalidResource(#[from] InvalidResourceError),
481    #[error("Compaction is already being prepared")]
482    CompactionPreparingAlready,
483    #[error("Cannot compact an already compacted BLAS")]
484    DoubleCompaction,
485    #[error("BLAS is not yet built")]
486    NotBuilt,
487    #[error("BLAS does not support compaction (is AccelerationStructureFlags::ALLOW_COMPACTION missing?)")]
488    CompactionUnsupported,
489}
490
491impl WebGpuError for BlasPrepareCompactError {
492    fn webgpu_error_type(&self) -> ErrorType {
493        match self {
494            Self::Device(e) => e.webgpu_error_type(),
495            Self::InvalidResource(e) => e.webgpu_error_type(),
496            Self::CompactionPreparingAlready
497            | Self::DoubleCompaction
498            | Self::NotBuilt
499            | Self::CompactionUnsupported => ErrorType::Validation,
500        }
501    }
502}
503
504#[derive(Clone, Debug, Error)]
505pub enum CompactBlasError {
506    #[error(transparent)]
507    Encoder(#[from] EncoderStateError),
508
509    #[error(transparent)]
510    Device(#[from] DeviceError),
511
512    #[error(transparent)]
513    InvalidResource(#[from] InvalidResourceError),
514
515    #[error(transparent)]
516    DestroyedResource(#[from] DestroyedResourceError),
517
518    #[error(transparent)]
519    MissingFeatures(#[from] MissingFeatures),
520
521    #[error("BLAS was not prepared for compaction")]
522    BlasNotReady,
523}
524
525impl WebGpuError for CompactBlasError {
526    fn webgpu_error_type(&self) -> ErrorType {
527        match self {
528            Self::Encoder(e) => e.webgpu_error_type(),
529            Self::Device(e) => e.webgpu_error_type(),
530            Self::InvalidResource(e) => e.webgpu_error_type(),
531            Self::DestroyedResource(e) => e.webgpu_error_type(),
532            Self::MissingFeatures(e) => e.webgpu_error_type(),
533            Self::BlasNotReady => ErrorType::Validation,
534        }
535    }
536}
537
538pub type BlasCompactReadyPendingClosure = (Option<BlasCompactCallback>, BlasPrepareCompactResult);