bevy_render/renderer/
render_device.rs

1use super::RenderQueue;
2use crate::render_resource::{
3    BindGroup, BindGroupLayout, Buffer, ComputePipeline, RawRenderPipelineDescriptor,
4    RenderPipeline, Sampler, Texture,
5};
6use crate::WgpuWrapper;
7use bevy_ecs::resource::Resource;
8use wgpu::{
9    util::DeviceExt, BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor,
10    BindGroupLayoutEntry, BufferAsyncError, BufferBindingType, MaintainResult,
11};
12
13/// This GPU device is responsible for the creation of most rendering and compute resources.
14#[derive(Resource, Clone)]
15pub struct RenderDevice {
16    device: WgpuWrapper<wgpu::Device>,
17}
18
19impl From<wgpu::Device> for RenderDevice {
20    fn from(device: wgpu::Device) -> Self {
21        Self::new(WgpuWrapper::new(device))
22    }
23}
24
25impl RenderDevice {
26    pub fn new(device: WgpuWrapper<wgpu::Device>) -> Self {
27        Self { device }
28    }
29
30    /// List all [`Features`](wgpu::Features) that may be used with this device.
31    ///
32    /// Functions may panic if you use unsupported features.
33    #[inline]
34    pub fn features(&self) -> wgpu::Features {
35        self.device.features()
36    }
37
38    /// List all [`Limits`](wgpu::Limits) that were requested of this device.
39    ///
40    /// If any of these limits are exceeded, functions may panic.
41    #[inline]
42    pub fn limits(&self) -> wgpu::Limits {
43        self.device.limits()
44    }
45
46    /// Creates a [`ShaderModule`](wgpu::ShaderModule) from either SPIR-V or WGSL source code.
47    ///
48    /// # Safety
49    ///
50    /// Creates a shader module with user-customizable runtime checks which allows shaders to
51    /// perform operations which can lead to undefined behavior like indexing out of bounds,
52    /// To avoid UB, ensure any unchecked shaders are sound!
53    /// This method should never be called for user-supplied shaders.
54    #[inline]
55    pub unsafe fn create_shader_module(
56        &self,
57        desc: wgpu::ShaderModuleDescriptor,
58    ) -> wgpu::ShaderModule {
59        #[cfg(feature = "spirv_shader_passthrough")]
60        match &desc.source {
61            wgpu::ShaderSource::SpirV(source)
62                if self
63                    .features()
64                    .contains(wgpu::Features::SPIRV_SHADER_PASSTHROUGH) =>
65            {
66                // SAFETY:
67                // This call passes binary data to the backend as-is and can potentially result in a driver crash or bogus behavior.
68                // No attempt is made to ensure that data is valid SPIR-V.
69                unsafe {
70                    self.device
71                        .create_shader_module_spirv(&wgpu::ShaderModuleDescriptorSpirV {
72                            label: desc.label,
73                            source: source.clone(),
74                        })
75                }
76            }
77            // SAFETY:
78            //
79            // This call passes binary data to the backend as-is and can potentially result in a driver crash or bogus behavior.
80            // No attempt is made to ensure that data is valid SPIR-V.
81            _ => unsafe {
82                self.device
83                    .create_shader_module_trusted(desc, wgpu::ShaderRuntimeChecks::unchecked())
84            },
85        }
86        #[cfg(not(feature = "spirv_shader_passthrough"))]
87        // SAFETY: the caller is responsible for upholding the safety requirements
88        unsafe {
89            self.device
90                .create_shader_module_trusted(desc, wgpu::ShaderRuntimeChecks::unchecked())
91        }
92    }
93
94    /// Creates and validates a [`ShaderModule`](wgpu::ShaderModule) from either SPIR-V or WGSL source code.
95    ///
96    /// See [`ValidateShader`](bevy_render::render_resource::ValidateShader) for more information on the tradeoffs involved with shader validation.
97    #[inline]
98    pub fn create_and_validate_shader_module(
99        &self,
100        desc: wgpu::ShaderModuleDescriptor,
101    ) -> wgpu::ShaderModule {
102        #[cfg(feature = "spirv_shader_passthrough")]
103        match &desc.source {
104            wgpu::ShaderSource::SpirV(_source) => panic!("no safety checks are performed for spirv shaders. use `create_shader_module` instead"),
105            _ => self.device.create_shader_module(desc),
106        }
107        #[cfg(not(feature = "spirv_shader_passthrough"))]
108        self.device.create_shader_module(desc)
109    }
110
111    /// Check for resource cleanups and mapping callbacks.
112    ///
113    /// Return `true` if the queue is empty, or `false` if there are more queue
114    /// submissions still in flight. (Note that, unless access to the [`wgpu::Queue`] is
115    /// coordinated somehow, this information could be out of date by the time
116    /// the caller receives it. `Queue`s can be shared between threads, so
117    /// other threads could submit new work at any time.)
118    ///
119    /// no-op on the web, device is automatically polled.
120    #[inline]
121    pub fn poll(&self, maintain: wgpu::Maintain) -> MaintainResult {
122        self.device.poll(maintain)
123    }
124
125    /// Creates an empty [`CommandEncoder`](wgpu::CommandEncoder).
126    #[inline]
127    pub fn create_command_encoder(
128        &self,
129        desc: &wgpu::CommandEncoderDescriptor,
130    ) -> wgpu::CommandEncoder {
131        self.device.create_command_encoder(desc)
132    }
133
134    /// Creates an empty [`RenderBundleEncoder`](wgpu::RenderBundleEncoder).
135    #[inline]
136    pub fn create_render_bundle_encoder(
137        &self,
138        desc: &wgpu::RenderBundleEncoderDescriptor,
139    ) -> wgpu::RenderBundleEncoder {
140        self.device.create_render_bundle_encoder(desc)
141    }
142
143    /// Creates a new [`BindGroup`](wgpu::BindGroup).
144    #[inline]
145    pub fn create_bind_group<'a>(
146        &self,
147        label: impl Into<wgpu::Label<'a>>,
148        layout: &'a BindGroupLayout,
149        entries: &'a [BindGroupEntry<'a>],
150    ) -> BindGroup {
151        let wgpu_bind_group = self.device.create_bind_group(&BindGroupDescriptor {
152            label: label.into(),
153            layout,
154            entries,
155        });
156        BindGroup::from(wgpu_bind_group)
157    }
158
159    /// Creates a [`BindGroupLayout`](wgpu::BindGroupLayout).
160    #[inline]
161    pub fn create_bind_group_layout<'a>(
162        &self,
163        label: impl Into<wgpu::Label<'a>>,
164        entries: &'a [BindGroupLayoutEntry],
165    ) -> BindGroupLayout {
166        BindGroupLayout::from(
167            self.device
168                .create_bind_group_layout(&BindGroupLayoutDescriptor {
169                    label: label.into(),
170                    entries,
171                }),
172        )
173    }
174
175    /// Creates a [`PipelineLayout`](wgpu::PipelineLayout).
176    #[inline]
177    pub fn create_pipeline_layout(
178        &self,
179        desc: &wgpu::PipelineLayoutDescriptor,
180    ) -> wgpu::PipelineLayout {
181        self.device.create_pipeline_layout(desc)
182    }
183
184    /// Creates a [`RenderPipeline`].
185    #[inline]
186    pub fn create_render_pipeline(&self, desc: &RawRenderPipelineDescriptor) -> RenderPipeline {
187        let wgpu_render_pipeline = self.device.create_render_pipeline(desc);
188        RenderPipeline::from(wgpu_render_pipeline)
189    }
190
191    /// Creates a [`ComputePipeline`].
192    #[inline]
193    pub fn create_compute_pipeline(
194        &self,
195        desc: &wgpu::ComputePipelineDescriptor,
196    ) -> ComputePipeline {
197        let wgpu_compute_pipeline = self.device.create_compute_pipeline(desc);
198        ComputePipeline::from(wgpu_compute_pipeline)
199    }
200
201    /// Creates a [`Buffer`].
202    pub fn create_buffer(&self, desc: &wgpu::BufferDescriptor) -> Buffer {
203        let wgpu_buffer = self.device.create_buffer(desc);
204        Buffer::from(wgpu_buffer)
205    }
206
207    /// Creates a [`Buffer`] and initializes it with the specified data.
208    pub fn create_buffer_with_data(&self, desc: &wgpu::util::BufferInitDescriptor) -> Buffer {
209        let wgpu_buffer = self.device.create_buffer_init(desc);
210        Buffer::from(wgpu_buffer)
211    }
212
213    /// Creates a new [`Texture`] and initializes it with the specified data.
214    ///
215    /// `desc` specifies the general format of the texture.
216    /// `data` is the raw data.
217    pub fn create_texture_with_data(
218        &self,
219        render_queue: &RenderQueue,
220        desc: &wgpu::TextureDescriptor,
221        order: wgpu::util::TextureDataOrder,
222        data: &[u8],
223    ) -> Texture {
224        let wgpu_texture =
225            self.device
226                .create_texture_with_data(render_queue.as_ref(), desc, order, data);
227        Texture::from(wgpu_texture)
228    }
229
230    /// Creates a new [`Texture`].
231    ///
232    /// `desc` specifies the general format of the texture.
233    pub fn create_texture(&self, desc: &wgpu::TextureDescriptor) -> Texture {
234        let wgpu_texture = self.device.create_texture(desc);
235        Texture::from(wgpu_texture)
236    }
237
238    /// Creates a new [`Sampler`].
239    ///
240    /// `desc` specifies the behavior of the sampler.
241    pub fn create_sampler(&self, desc: &wgpu::SamplerDescriptor) -> Sampler {
242        let wgpu_sampler = self.device.create_sampler(desc);
243        Sampler::from(wgpu_sampler)
244    }
245
246    /// Initializes [`Surface`](wgpu::Surface) for presentation.
247    ///
248    /// # Panics
249    ///
250    /// - A old [`SurfaceTexture`](wgpu::SurfaceTexture) is still alive referencing an old surface.
251    /// - Texture format requested is unsupported on the surface.
252    pub fn configure_surface(&self, surface: &wgpu::Surface, config: &wgpu::SurfaceConfiguration) {
253        surface.configure(&self.device, config);
254    }
255
256    /// Returns the wgpu [`Device`](wgpu::Device).
257    pub fn wgpu_device(&self) -> &wgpu::Device {
258        &self.device
259    }
260
261    pub fn map_buffer(
262        &self,
263        buffer: &wgpu::BufferSlice,
264        map_mode: wgpu::MapMode,
265        callback: impl FnOnce(Result<(), BufferAsyncError>) + Send + 'static,
266    ) {
267        buffer.map_async(map_mode, callback);
268    }
269
270    // Rounds up `row_bytes` to be a multiple of [`wgpu::COPY_BYTES_PER_ROW_ALIGNMENT`].
271    pub const fn align_copy_bytes_per_row(row_bytes: usize) -> usize {
272        let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
273
274        // If row_bytes is aligned calculate a value just under the next aligned value.
275        // Otherwise calculate a value greater than the next aligned value.
276        let over_aligned = row_bytes + align - 1;
277
278        // Round the number *down* to the nearest aligned value.
279        (over_aligned / align) * align
280    }
281
282    pub fn get_supported_read_only_binding_type(
283        &self,
284        buffers_per_shader_stage: u32,
285    ) -> BufferBindingType {
286        if self.limits().max_storage_buffers_per_shader_stage >= buffers_per_shader_stage {
287            BufferBindingType::Storage { read_only: true }
288        } else {
289            BufferBindingType::Uniform
290        }
291    }
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297
298    #[test]
299    fn align_copy_bytes_per_row() {
300        // Test for https://github.com/bevyengine/bevy/issues/16992
301        let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
302
303        assert_eq!(RenderDevice::align_copy_bytes_per_row(0), 0);
304        assert_eq!(RenderDevice::align_copy_bytes_per_row(1), align);
305        assert_eq!(RenderDevice::align_copy_bytes_per_row(align + 1), align * 2);
306        assert_eq!(RenderDevice::align_copy_bytes_per_row(align), align);
307    }
308}