wgpu/api/blas.rs
1#[cfg(wgpu_core)]
2use core::ops::Deref;
3
4use alloc::{boxed::Box, vec::Vec};
5
6use wgt::{WasmNotSend, WasmNotSendSync};
7
8use crate::dispatch;
9use crate::{Buffer, Label};
10
11/// Descriptor for the size defining attributes of a triangle geometry, for a bottom level acceleration structure.
12pub type BlasTriangleGeometrySizeDescriptor = wgt::BlasTriangleGeometrySizeDescriptor;
13static_assertions::assert_impl_all!(BlasTriangleGeometrySizeDescriptor: Send, Sync);
14
15/// Descriptor for the size defining attributes of an AABB geometry group in a bottom level acceleration structure.
16pub type BlasAABBGeometrySizeDescriptor = wgt::BlasAABBGeometrySizeDescriptor;
17static_assertions::assert_impl_all!(BlasAABBGeometrySizeDescriptor: Send, Sync);
18
19/// Minimum stride for AABB geometry (24 bytes: two `vec3<f32>`).
20pub use wgt::AABB_GEOMETRY_MIN_STRIDE;
21
22/// Descriptor for the size defining attributes, for a bottom level acceleration structure.
23pub type BlasGeometrySizeDescriptors = wgt::BlasGeometrySizeDescriptors;
24static_assertions::assert_impl_all!(BlasGeometrySizeDescriptors: Send, Sync);
25
26/// Flags for an acceleration structure.
27pub type AccelerationStructureFlags = wgt::AccelerationStructureFlags;
28static_assertions::assert_impl_all!(AccelerationStructureFlags: Send, Sync);
29
30/// Flags for a geometry inside a bottom level acceleration structure.
31pub type AccelerationStructureGeometryFlags = wgt::AccelerationStructureGeometryFlags;
32static_assertions::assert_impl_all!(AccelerationStructureGeometryFlags: Send, Sync);
33
34/// Update mode for acceleration structure builds.
35pub type AccelerationStructureUpdateMode = wgt::AccelerationStructureUpdateMode;
36static_assertions::assert_impl_all!(AccelerationStructureUpdateMode: Send, Sync);
37
38/// Descriptor to create bottom level acceleration structures.
39pub type CreateBlasDescriptor<'a> = wgt::CreateBlasDescriptor<Label<'a>>;
40static_assertions::assert_impl_all!(CreateBlasDescriptor<'_>: Send, Sync);
41
42/// Safe instance for a [Tlas].
43///
44/// A TlasInstance may be made invalid, if a TlasInstance is invalid, any attempt to build a [Tlas] containing an
45/// invalid TlasInstance will generate a validation error
46///
47/// Each one contains:
48/// - A reference to a BLAS, this ***must*** be interacted with using [TlasInstance::new] or [TlasInstance::set_blas], a
49/// TlasInstance that references a BLAS keeps that BLAS from being dropped
50/// - A user accessible transformation matrix
51/// - A user accessible mask
52/// - A user accessible custom index
53///
54/// [Tlas]: crate::Tlas
55#[derive(Debug, Clone)]
56pub struct TlasInstance {
57 pub(crate) blas: dispatch::DispatchBlas,
58 /// Affine transform matrix 3x4 (rows x columns, row major order).
59 pub transform: [f32; 12],
60 /// Custom index for the instance used inside the shader.
61 ///
62 /// This must only use the lower 24 bits, if any bits are outside that range (byte 4 does not equal 0) the TlasInstance becomes
63 /// invalid and generates a validation error when built
64 pub custom_data: u32,
65 /// Mask for the instance used inside the shader to filter instances.
66 /// Reports hit only if `(shader_cull_mask & tlas_instance.mask) != 0u`.
67 pub mask: u8,
68 /// Intersection group index into a ray tracing pipeline. Must be less than the number of intersection groups in any ray tracing
69 /// pipeline a tlas built with this is used for. This can be read in ray queries. If this field is non-zero,
70 /// [`Features::EXPERIMENTAL_RAY_TRACING_PIPELINES`] must be enabled. This must only use the lower 24 bits, if any bits are
71 /// outside that range (byte 4 does not equal 0) the TlasInstance becomes invalid and generates a validation error when built.
72 ///
73 /// [`Features::EXPERIMENTAL_RAY_TRACING_PIPELINES`]: wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES
74 pub intersection_index: u32,
75}
76
77impl TlasInstance {
78 /// Constructs a new TlasInstance from a [Blas]. Every other field
79 /// is set in a way that will mean the objects within the [Blas]
80 /// appear in their default positions.
81 pub fn from_blas_untransformed(blas: &Blas) -> Self {
82 // transform (an affine matrix with zero offset and an identity 3x3)
83 // 1.0, 0.0, 0.0, 0.0
84 // 0.0, 1.0, 0.0, 0.0
85 // 0.0, 0.0, 1.0, 0.0
86 Self::from_blas_transformed(
87 blas,
88 [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0],
89 )
90 }
91 /// Constructs a new TlasInstance from a [Blas]. Every other field
92 /// is set in a way that will mean the objects within the [Blas]
93 /// appear in their positions transformed by `transform`.
94 pub fn from_blas_transformed(blas: &Blas, transform: [f32; 12]) -> Self {
95 Self::new(blas, transform, 0, 0xff, 0)
96 }
97 /// Construct TlasInstance.
98 /// - blas: Reference to the bottom level acceleration structure
99 /// - transform: Transform buffer offset in bytes (optional, required if transform buffer is present)
100 /// - custom_data: Custom index for the instance used inside the shader (max 24 bits)
101 /// - mask: Mask for the instance used inside the shader to filter instances
102 /// - intersection_index: Either an index into an intersection group in a ray tracing pipeline or data for ray queries
103 ///
104 /// Note: while one of these contains a reference to a BLAS that BLAS will not be dropped,
105 /// but it can still be destroyed. Destroying a BLAS that is referenced by one or more
106 /// TlasInstance(s) will immediately make them invalid. If one or more of those invalid
107 /// TlasInstances is inside a TlasPackage that is attempted to be built, the build will
108 /// generate a validation error.
109 pub fn new(
110 blas: &Blas,
111 transform: [f32; 12],
112 custom_data: u32,
113 mask: u8,
114 intersection_index: u32,
115 ) -> Self {
116 Self {
117 blas: blas.inner.clone(),
118 transform,
119 custom_data,
120 mask,
121 intersection_index,
122 }
123 }
124
125 /// Set the bottom level acceleration structure.
126 ///
127 /// See the note on [TlasInstance] about the
128 /// guarantees of keeping a BLAS alive.
129 pub fn set_blas(&mut self, blas: &Blas) {
130 self.blas = blas.inner.clone();
131 }
132
133 /// Returns custom implementation of the BLAS referenced by this instance
134 /// (if the custom backend is active and the BLAS is internally of type T).
135 #[cfg(custom)]
136 pub fn blas_as_custom<T: crate::custom::BlasInterface>(&self) -> Option<&T> {
137 self.blas.as_custom()
138 }
139}
140
141#[derive(Debug)]
142/// Definition for a triangle geometry for a Bottom Level Acceleration Structure (BLAS).
143///
144/// The size must match the rest of the structures fields, otherwise the build will fail.
145/// (e.g. if index count is present in the size, the index buffer must be present as well.)
146pub struct BlasTriangleGeometry<'a> {
147 /// Sub descriptor for the size defining attributes of a triangle geometry.
148 pub size: &'a BlasTriangleGeometrySizeDescriptor,
149 /// Vertex buffer.
150 pub vertex_buffer: &'a Buffer,
151 /// Offset into the vertex buffer as a factor of the vertex stride.
152 pub first_vertex: u32,
153 /// Vertex stride, must be greater than [`wgpu_types::VertexFormat::min_acceleration_structure_vertex_stride`]
154 /// of the format and must be a multiple of [`wgpu_types::VertexFormat::acceleration_structure_stride_alignment`].
155 pub vertex_stride: wgt::BufferAddress,
156 /// Index buffer (optional).
157 pub index_buffer: Option<&'a Buffer>,
158 /// Number of indexes to skip in the index buffer (optional, required if index buffer is present).
159 pub first_index: Option<u32>,
160 /// Transform buffer containing 3x4 (rows x columns, row major) affine transform matrices `[f32; 12]` (optional).
161 pub transform_buffer: Option<&'a Buffer>,
162 /// Transform buffer offset in bytes (optional, required if transform buffer is present).
163 pub transform_buffer_offset: Option<wgt::BufferAddress>,
164}
165static_assertions::assert_impl_all!(BlasTriangleGeometry<'_>: WasmNotSendSync);
166
167/// Definition for an axis-aligned bounding box geometry group for a bottom level acceleration structure.
168///
169/// Buffer data must contain `size.primitive_count` primitives at `primitive_offset`, each `stride` bytes
170/// apart, with `stride` at least [`AABB_GEOMETRY_MIN_STRIDE`] and a multiple of 8.
171#[derive(Debug)]
172pub struct BlasAabbGeometry<'a> {
173 /// Sub descriptor for the size defining attributes of this geometry.
174 pub size: &'a BlasAABBGeometrySizeDescriptor,
175 /// Stride in bytes between consecutive AABB primitives in the buffer (at least
176 /// [`AABB_GEOMETRY_MIN_STRIDE`], and must be a multiple of 8).
177 pub stride: wgt::BufferAddress,
178 /// Buffer containing packed AABB primitives. Each primitive is a minimum corner
179 /// then a maximum corner, two consecutive `vec3<f32>` (24 bytes, the
180 /// [`AABB_GEOMETRY_MIN_STRIDE`]); consecutive primitives are `stride` bytes apart.
181 pub aabb_buffer: &'a Buffer,
182 /// Byte offset to the first AABB primitive (must be a multiple of 8).
183 pub primitive_offset: u32,
184}
185static_assertions::assert_impl_all!(BlasAabbGeometry<'_>: WasmNotSendSync);
186
187/// Contains the sets of geometry that go into a [Blas].
188#[derive(Debug)]
189pub enum BlasGeometries<'a> {
190 /// Triangle geometry variant.
191 TriangleGeometries(Vec<BlasTriangleGeometry<'a>>),
192 /// Procedural AABB geometry variant.
193 AabbGeometries(Vec<BlasAabbGeometry<'a>>),
194}
195static_assertions::assert_impl_all!(BlasGeometries<'_>: WasmNotSendSync);
196
197/// Builds the given sets of geometry into the given [Blas].
198#[derive(Debug)]
199pub struct BlasBuildEntry<'a> {
200 /// Reference to the acceleration structure.
201 pub blas: &'a Blas,
202 /// Geometries.
203 pub geometry: BlasGeometries<'a>,
204}
205static_assertions::assert_impl_all!(BlasBuildEntry<'_>: WasmNotSendSync);
206
207/// Bottom Level Acceleration Structure (BLAS).
208///
209/// A BLAS is a device-specific raytracing acceleration structure that contains geometry data.
210///
211/// These BLASes are combined with transform in a [TlasInstance] to create a [Tlas].
212///
213/// [Tlas]: crate::Tlas
214#[derive(Debug, Clone)]
215pub struct Blas {
216 pub(crate) handle: Option<u64>,
217 pub(crate) inner: dispatch::DispatchBlas,
218}
219static_assertions::assert_impl_all!(Blas: WasmNotSendSync);
220
221crate::cmp::impl_eq_ord_hash_proxy!(Blas => .inner);
222
223impl Blas {
224 /// Raw handle to the acceleration structure, used inside raw instance buffers.
225 pub fn handle(&self) -> Option<u64> {
226 self.handle
227 }
228
229 /// Get the [`wgpu_hal`] acceleration structure from this `Blas`.
230 ///
231 /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`],
232 /// and pass that struct to the to the `A` type parameter.
233 ///
234 /// Returns a guard that dereferences to the type of the hal backend
235 /// which implements [`A::AccelerationStructure`].
236 ///
237 /// # Types
238 ///
239 /// The returned type depends on the backend:
240 ///
241 #[doc = crate::macros::hal_type_vulkan!("AccelerationStructure")]
242 #[doc = crate::macros::hal_type_metal!("AccelerationStructure")]
243 #[doc = crate::macros::hal_type_dx12!("AccelerationStructure")]
244 #[doc = crate::macros::hal_type_gles!("AccelerationStructure")]
245 ///
246 /// # Deadlocks
247 ///
248 /// - The returned guard holds a read-lock on a device-local "destruction"
249 /// lock, which will cause all calls to `destroy` to block until the
250 /// guard is released.
251 ///
252 /// # Errors
253 ///
254 /// This method will return None if:
255 /// - The acceleration structure is not from the backend specified by `A`.
256 /// - The acceleration structure is from the `webgpu` or `custom` backend.
257 ///
258 /// # Safety
259 ///
260 /// - The returned resource must not be destroyed unless the guard
261 /// is the last reference to it and it is not in use by the GPU.
262 /// The guard and handle may be dropped at any time however.
263 /// - All the safety requirements of wgpu-hal must be upheld.
264 ///
265 /// [`A::AccelerationStructure`]: hal::Api::AccelerationStructure
266 #[cfg(wgpu_core)]
267 pub unsafe fn as_hal<A: hal::Api>(
268 &mut self,
269 ) -> Option<impl Deref<Target = A::AccelerationStructure> + WasmNotSendSync> {
270 let blas = self.inner.as_core_opt()?;
271 unsafe { blas.as_hal::<A>() }
272 }
273
274 #[cfg(custom)]
275 /// Returns custom implementation of Blas (if custom backend and is internally T)
276 pub fn as_custom<T: crate::custom::BlasInterface>(&self) -> Option<&T> {
277 self.inner.as_custom()
278 }
279}
280
281/// Context version of [BlasTriangleGeometry].
282#[expect(missing_debug_implementations)]
283pub struct ContextBlasTriangleGeometry<'a> {
284 #[expect(dead_code)]
285 pub(crate) size: &'a BlasTriangleGeometrySizeDescriptor,
286 #[expect(dead_code)]
287 pub(crate) vertex_buffer: &'a dispatch::DispatchBuffer,
288 #[expect(dead_code)]
289 pub(crate) index_buffer: Option<&'a dispatch::DispatchBuffer>,
290 #[expect(dead_code)]
291 pub(crate) transform_buffer: Option<&'a dispatch::DispatchBuffer>,
292 #[expect(dead_code)]
293 pub(crate) first_vertex: u32,
294 #[expect(dead_code)]
295 pub(crate) vertex_stride: wgt::BufferAddress,
296 #[expect(dead_code)]
297 pub(crate) index_buffer_offset: Option<wgt::BufferAddress>,
298 #[expect(dead_code)]
299 pub(crate) transform_buffer_offset: Option<wgt::BufferAddress>,
300}
301
302/// Context version of [BlasGeometries].
303#[expect(missing_debug_implementations)]
304pub enum ContextBlasGeometries<'a> {
305 /// Triangle geometries.
306 TriangleGeometries(Box<dyn Iterator<Item = ContextBlasTriangleGeometry<'a>> + 'a>),
307 /// AABB geometries.
308 AabbGeometries(Box<dyn Iterator<Item = ContextBlasAabbGeometry<'a>> + 'a>),
309}
310
311/// Context version of [BlasAabbGeometry].
312#[expect(missing_debug_implementations)]
313pub struct ContextBlasAabbGeometry<'a> {
314 #[expect(dead_code)]
315 pub(crate) size: &'a BlasAABBGeometrySizeDescriptor,
316 #[expect(dead_code)]
317 pub(crate) stride: wgt::BufferAddress,
318 #[expect(dead_code)]
319 pub(crate) aabb_buffer: &'a dispatch::DispatchBuffer,
320 #[expect(dead_code)]
321 pub(crate) primitive_offset: u32,
322}
323
324/// Context version see [BlasBuildEntry].
325#[expect(missing_debug_implementations)]
326pub struct ContextBlasBuildEntry<'a> {
327 #[expect(dead_code)]
328 pub(crate) blas: &'a dispatch::DispatchBlas,
329 #[expect(dead_code)]
330 pub(crate) geometries: ContextBlasGeometries<'a>,
331}
332
333/// Error occurred when trying to asynchronously prepare a blas for compaction.
334#[derive(Clone, PartialEq, Eq, Debug)]
335pub struct BlasAsyncError;
336static_assertions::assert_impl_all!(BlasAsyncError: Send, Sync);
337
338impl core::fmt::Display for BlasAsyncError {
339 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
340 write!(
341 f,
342 "Error occurred when trying to asynchronously prepare a blas for compaction"
343 )
344 }
345}
346
347impl core::error::Error for BlasAsyncError {}
348
349impl Blas {
350 /// Asynchronously prepares this BLAS for compaction. The callback is called once all builds
351 /// using this BLAS are finished and the BLAS is compactable. This can be checked using
352 /// [`Blas::ready_for_compaction`]. Rebuilding this BLAS will reset its compacted state, and it
353 /// will need to be prepared again.
354 ///
355 /// ### Interaction with other functions
356 /// On native, `queue.submit(..)` and polling devices (that is calling `instance.poll_all` or
357 /// `device.poll`) with [`PollType::Poll`] may call the callback. On native, polling devices with
358 /// [`PollType::Wait`] (optionally with a submission index greater
359 /// than the last submit the BLAS was used in) will guarantee callback is called.
360 ///
361 /// [`PollType::Poll`]: wgpu_types::PollType::Poll
362 /// [`PollType::Wait`]: wgpu_types::PollType::Wait
363 pub fn prepare_compaction_async(
364 &self,
365 callback: impl FnOnce(Result<(), BlasAsyncError>) + WasmNotSend + 'static,
366 ) {
367 self.inner.prepare_compact_async(Box::new(callback));
368 }
369
370 /// Checks whether this BLAS is ready for compaction. The returned value is `true` if
371 /// [`Blas::prepare_compaction_async`]'s callback was called with a non-error value, otherwise
372 /// this is `false`.
373 pub fn ready_for_compaction(&self) -> bool {
374 self.inner.ready_for_compaction()
375 }
376}