Skip to main content

wgpu_hal/dynamic/
mod.rs

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