wgpu_hal/dynamic/
mod.rs

1mod adapter;
2mod command;
3mod device;
4mod instance;
5mod queue;
6mod surface;
7
8pub use adapter::{DynAdapter, DynOpenDevice};
9pub use command::DynCommandEncoder;
10pub use device::DynDevice;
11pub use instance::{DynExposedAdapter, DynInstance};
12pub use queue::DynQueue;
13pub use surface::{DynAcquiredSurfaceTexture, DynSurface};
14
15use alloc::boxed::Box;
16use core::{
17    any::{Any, TypeId},
18    fmt,
19};
20
21use wgt::WasmNotSendSync;
22
23use crate::{
24    AccelerationStructureAABBs, AccelerationStructureEntries, AccelerationStructureInstances,
25    AccelerationStructureTriangleIndices, AccelerationStructureTriangleTransform,
26    AccelerationStructureTriangles, BufferBinding, ExternalTextureBinding, ProgrammableStage,
27    TextureBinding,
28};
29
30/// Base trait for all resources, allows downcasting via [`Any`].
31pub trait DynResource: Any + WasmNotSendSync + 'static {
32    fn as_any(&self) -> &dyn Any;
33    fn as_any_mut(&mut self) -> &mut dyn Any;
34}
35
36/// Utility macro for implementing `DynResource` for a list of types.
37macro_rules! impl_dyn_resource {
38    ($($type:ty),*) => {
39        $(
40            impl crate::DynResource for $type {
41                fn as_any(&self) -> &dyn ::core::any::Any {
42                    self
43                }
44
45                fn as_any_mut(&mut self) -> &mut dyn ::core::any::Any {
46                    self
47                }
48            }
49        )*
50    };
51}
52pub(crate) use impl_dyn_resource;
53
54/// Extension trait for `DynResource` used by implementations of various dynamic resource traits.
55trait DynResourceExt {
56    /// # Panics
57    ///
58    /// - Panics if `self` is not downcastable to `T`.
59    fn expect_downcast_ref<T: DynResource>(&self) -> &T;
60
61    /// Unboxes a `Box<dyn DynResource>` to a concrete type.
62    ///
63    /// # Safety
64    ///
65    /// - `self` must be the correct concrete type.
66    unsafe fn unbox<T: DynResource + 'static>(self: Box<Self>) -> T;
67}
68
69impl<R: DynResource + ?Sized> DynResourceExt for R {
70    fn expect_downcast_ref<'a, T: DynResource>(&'a self) -> &'a T {
71        self.as_any()
72            .downcast_ref()
73            .expect("Resource doesn't have the expected backend type.")
74    }
75
76    unsafe fn unbox<T: DynResource + 'static>(self: Box<Self>) -> T {
77        debug_assert!(
78            <Self as Any>::type_id(self.as_ref()) == TypeId::of::<T>(),
79            "Resource doesn't have the expected type, expected {:?}, got {:?}",
80            TypeId::of::<T>(),
81            <Self as Any>::type_id(self.as_ref())
82        );
83
84        let casted_ptr = Box::into_raw(self).cast::<T>();
85        // SAFETY: This is adheres to the safety contract of `Box::from_raw` because:
86        //
87        // - We are casting the value of a previously `Box`ed value, which guarantees:
88        //   - `casted_ptr` is not null.
89        //   - `casted_ptr` is valid for reads and writes, though by itself this does not mean
90        //     valid reads and writes for `T` (read on for that).
91        // - We don't change the allocator.
92        // - The contract of `Box::from_raw` requires that an initialized and aligned `T` is stored
93        //   within `casted_ptr`.
94        *unsafe { Box::from_raw(casted_ptr) }
95    }
96}
97
98pub trait DynAccelerationStructure: DynResource + fmt::Debug {}
99pub trait DynBindGroup: DynResource + fmt::Debug {}
100pub trait DynBindGroupLayout: DynResource + fmt::Debug {}
101pub trait DynBuffer: DynResource + fmt::Debug {}
102pub trait DynCommandBuffer: DynResource + fmt::Debug {}
103pub trait DynComputePipeline: DynResource + fmt::Debug {}
104pub trait DynFence: DynResource + fmt::Debug {}
105pub trait DynPipelineCache: DynResource + fmt::Debug {}
106pub trait DynPipelineLayout: DynResource + fmt::Debug {}
107pub trait DynQuerySet: DynResource + fmt::Debug {}
108pub trait DynRenderPipeline: DynResource + fmt::Debug {}
109pub trait DynSampler: DynResource + fmt::Debug {}
110pub trait DynShaderModule: DynResource + fmt::Debug {}
111pub trait DynSurfaceTexture:
112    DynResource + core::borrow::Borrow<dyn DynTexture> + fmt::Debug
113{
114}
115pub trait DynTexture: DynResource + fmt::Debug {}
116pub trait DynTextureView: DynResource + fmt::Debug {}
117
118impl<'a> BufferBinding<'a, dyn DynBuffer> {
119    pub fn expect_downcast<B: DynBuffer>(self) -> BufferBinding<'a, B> {
120        BufferBinding {
121            buffer: self.buffer.expect_downcast_ref(),
122            offset: self.offset,
123            size: self.size,
124        }
125    }
126}
127
128impl<'a> TextureBinding<'a, dyn DynTextureView> {
129    pub fn expect_downcast<T: DynTextureView>(self) -> TextureBinding<'a, T> {
130        TextureBinding {
131            view: self.view.expect_downcast_ref(),
132            usage: self.usage,
133        }
134    }
135}
136
137impl<'a> ExternalTextureBinding<'a, dyn DynBuffer, dyn DynTextureView> {
138    pub fn expect_downcast<B: DynBuffer, T: DynTextureView>(
139        self,
140    ) -> ExternalTextureBinding<'a, B, T> {
141        let planes = self.planes.map(|plane| plane.expect_downcast());
142        let params = self.params.expect_downcast();
143        ExternalTextureBinding { planes, params }
144    }
145}
146
147impl<'a> ProgrammableStage<'a, dyn DynShaderModule> {
148    fn expect_downcast<T: DynShaderModule>(self) -> ProgrammableStage<'a, T> {
149        ProgrammableStage {
150            module: self.module.expect_downcast_ref(),
151            entry_point: self.entry_point,
152            constants: self.constants,
153            zero_initialize_workgroup_memory: self.zero_initialize_workgroup_memory,
154        }
155    }
156}
157
158impl<'a> AccelerationStructureEntries<'a, dyn DynBuffer> {
159    fn expect_downcast<B: DynBuffer>(&self) -> AccelerationStructureEntries<'a, B> {
160        match self {
161            AccelerationStructureEntries::Instances(instances) => {
162                AccelerationStructureEntries::Instances(AccelerationStructureInstances {
163                    buffer: instances.buffer.map(|b| b.expect_downcast_ref()),
164                    offset: instances.offset,
165                    count: instances.count,
166                })
167            }
168            AccelerationStructureEntries::Triangles(triangles) => {
169                AccelerationStructureEntries::Triangles(
170                    triangles
171                        .iter()
172                        .map(|t| AccelerationStructureTriangles {
173                            vertex_buffer: t.vertex_buffer.map(|b| b.expect_downcast_ref()),
174                            vertex_format: t.vertex_format,
175                            first_vertex: t.first_vertex,
176                            vertex_count: t.vertex_count,
177                            vertex_stride: t.vertex_stride,
178                            indices: t.indices.as_ref().map(|i| {
179                                AccelerationStructureTriangleIndices {
180                                    buffer: i.buffer.map(|b| b.expect_downcast_ref()),
181                                    format: i.format,
182                                    offset: i.offset,
183                                    count: i.count,
184                                }
185                            }),
186                            transform: t.transform.as_ref().map(|t| {
187                                AccelerationStructureTriangleTransform {
188                                    buffer: t.buffer.expect_downcast_ref(),
189                                    offset: t.offset,
190                                }
191                            }),
192                            flags: t.flags,
193                        })
194                        .collect(),
195                )
196            }
197            AccelerationStructureEntries::AABBs(entries) => AccelerationStructureEntries::AABBs(
198                entries
199                    .iter()
200                    .map(|e| AccelerationStructureAABBs {
201                        buffer: e.buffer.map(|b| b.expect_downcast_ref()),
202                        offset: e.offset,
203                        count: e.count,
204                        stride: e.stride,
205                        flags: e.flags,
206                    })
207                    .collect(),
208            ),
209        }
210    }
211}