wgpu/util/
device.rs

1use alloc::borrow::ToOwned as _;
2
3use wgt::TextureDataOrder;
4
5/// Describes a [Buffer](crate::Buffer) when allocating.
6#[derive(Clone, Debug, PartialEq, Eq, Hash)]
7pub struct BufferInitDescriptor<'a> {
8    /// Debug label of a buffer. This will show up in graphics debuggers for easy identification.
9    pub label: crate::Label<'a>,
10    /// Contents of a buffer on creation.
11    pub contents: &'a [u8],
12    /// Usages of a buffer. If the buffer is used in any way that isn't specified here, the operation
13    /// will panic.
14    pub usage: wgt::BufferUsages,
15}
16
17/// Utility methods not meant to be in the main API.
18pub trait DeviceExt {
19    /// Creates a [Buffer](crate::Buffer) with data to initialize it.
20    fn create_buffer_init(&self, desc: &BufferInitDescriptor<'_>) -> crate::Buffer;
21
22    /// Upload an entire texture and its mipmaps from a source buffer.
23    ///
24    /// Expects all mipmaps to be tightly packed in the data buffer.
25    ///
26    /// See [`TextureDataOrder`] for the order in which the data is laid out in memory.
27    ///
28    /// Implicitly adds the `COPY_DST` usage if it is not present in the descriptor,
29    /// as it is required to be able to upload the data to the gpu.
30    fn create_texture_with_data(
31        &self,
32        queue: &crate::Queue,
33        desc: &crate::TextureDescriptor<'_>,
34        order: TextureDataOrder,
35        data: &[u8],
36    ) -> crate::Texture;
37}
38
39impl DeviceExt for crate::Device {
40    fn create_buffer_init(&self, descriptor: &BufferInitDescriptor<'_>) -> crate::Buffer {
41        // Skip mapping if the buffer is zero sized
42        if descriptor.contents.is_empty() {
43            let wgt_descriptor = crate::BufferDescriptor {
44                label: descriptor.label,
45                size: 0,
46                usage: descriptor.usage,
47                mapped_at_creation: false,
48            };
49
50            self.create_buffer(&wgt_descriptor)
51        } else {
52            let unpadded_size = descriptor.contents.len() as crate::BufferAddress;
53            // Valid vulkan usage is
54            // 1. buffer size must be a multiple of COPY_BUFFER_ALIGNMENT.
55            // 2. buffer size must be greater than 0.
56            // Therefore we round the value up to the nearest multiple, and ensure it's at least COPY_BUFFER_ALIGNMENT.
57            let align_mask = crate::COPY_BUFFER_ALIGNMENT - 1;
58            let padded_size =
59                ((unpadded_size + align_mask) & !align_mask).max(crate::COPY_BUFFER_ALIGNMENT);
60
61            let wgt_descriptor = crate::BufferDescriptor {
62                label: descriptor.label,
63                size: padded_size,
64                usage: descriptor.usage,
65                mapped_at_creation: true,
66            };
67
68            let buffer = self.create_buffer(&wgt_descriptor);
69
70            buffer
71                .get_mapped_range_mut(..)
72                .slice(..unpadded_size as usize)
73                .copy_from_slice(descriptor.contents);
74            buffer.unmap();
75
76            buffer
77        }
78    }
79
80    fn create_texture_with_data(
81        &self,
82        queue: &crate::Queue,
83        desc: &crate::TextureDescriptor<'_>,
84        order: TextureDataOrder,
85        data: &[u8],
86    ) -> crate::Texture {
87        // Implicitly add the COPY_DST usage
88        let mut desc = desc.to_owned();
89        desc.usage |= crate::TextureUsages::COPY_DST;
90        let texture = self.create_texture(&desc);
91
92        // Will return None only if it's a combined depth-stencil format
93        // If so, default to 4, validation will fail later anyway since the depth or stencil
94        // aspect needs to be written to individually
95        let block_size = desc.format.block_copy_size(None).unwrap_or(4);
96        let (block_width, block_height) = desc.format.block_dimensions();
97        let layer_iterations = desc.array_layer_count();
98
99        let outer_iteration;
100        let inner_iteration;
101        match order {
102            TextureDataOrder::LayerMajor => {
103                outer_iteration = layer_iterations;
104                inner_iteration = desc.mip_level_count;
105            }
106            TextureDataOrder::MipMajor => {
107                outer_iteration = desc.mip_level_count;
108                inner_iteration = layer_iterations;
109            }
110        }
111
112        let mut binary_offset = 0;
113        for outer in 0..outer_iteration {
114            for inner in 0..inner_iteration {
115                let (layer, mip) = match order {
116                    TextureDataOrder::LayerMajor => (outer, inner),
117                    TextureDataOrder::MipMajor => (inner, outer),
118                };
119
120                let mut mip_size = desc.mip_level_size(mip).unwrap();
121                // copying layers separately
122                if desc.dimension != wgt::TextureDimension::D3 {
123                    mip_size.depth_or_array_layers = 1;
124                }
125
126                // When uploading mips of compressed textures and the mip is supposed to be
127                // a size that isn't a multiple of the block size, the mip needs to be uploaded
128                // as its "physical size" which is the size rounded up to the nearest block size.
129                let mip_physical = mip_size.physical_size(desc.format);
130
131                // All these calculations are performed on the physical size as that's the
132                // data that exists in the buffer.
133                let width_blocks = mip_physical.width / block_width;
134                let height_blocks = mip_physical.height / block_height;
135
136                let bytes_per_row = width_blocks * block_size;
137                let data_size = bytes_per_row * height_blocks * mip_size.depth_or_array_layers;
138
139                let end_offset = binary_offset + data_size as usize;
140
141                queue.write_texture(
142                    crate::TexelCopyTextureInfo {
143                        texture: &texture,
144                        mip_level: mip,
145                        origin: crate::Origin3d {
146                            x: 0,
147                            y: 0,
148                            z: layer,
149                        },
150                        aspect: wgt::TextureAspect::All,
151                    },
152                    &data[binary_offset..end_offset],
153                    crate::TexelCopyBufferLayout {
154                        offset: 0,
155                        bytes_per_row: Some(bytes_per_row),
156                        rows_per_image: Some(height_blocks),
157                    },
158                    mip_physical,
159                );
160
161                binary_offset = end_offset;
162            }
163        }
164
165        texture
166    }
167}