From bbc5ba3050076e326b9f9d1b3769e85518f8ae1c Mon Sep 17 00:00:00 2001 From: Imbris Date: Mon, 3 May 2021 22:13:40 -0400 Subject: [PATCH] [rs] Skip mapping of zero sized buffers in create_buffer_init to avoid a panic and avoid creating an unused padded buffer --- wgpu/src/util/device.rs | 60 +++++++++++++++++++++++++---------------- 1 file changed, 37 insertions(+), 23 deletions(-) diff --git a/wgpu/src/util/device.rs b/wgpu/src/util/device.rs index 2c7f4c93e7..fd9f3c77d6 100644 --- a/wgpu/src/util/device.rs +++ b/wgpu/src/util/device.rs @@ -36,29 +36,43 @@ pub trait DeviceExt { impl DeviceExt for crate::Device { fn create_buffer_init(&self, descriptor: &BufferInitDescriptor<'_>) -> crate::Buffer { - let unpadded_size = descriptor.contents.len() as crate::BufferAddress; - // Valid vulkan usage is - // 1. buffer size must be a multiple of COPY_BUFFER_ALIGNMENT. - // 2. buffer size must be greater than 0. - // Therefore we round the value up to the nearest multiple, and ensure it's at least COPY_BUFFER_ALIGNMENT. - let align_mask = crate::COPY_BUFFER_ALIGNMENT - 1; - let padded_size = - ((unpadded_size + align_mask) & !align_mask).max(crate::COPY_BUFFER_ALIGNMENT); - - let wgt_descriptor = crate::BufferDescriptor { - label: descriptor.label, - size: padded_size, - usage: descriptor.usage, - mapped_at_creation: true, - }; - - let buffer = self.create_buffer(&wgt_descriptor); - buffer - .slice(..unpadded_size) - .get_mapped_range_mut() - .copy_from_slice(descriptor.contents); - buffer.unmap(); - buffer + // Skip mapping if the buffer is zero sized + if descriptor.contents.is_empty() { + let wgt_descriptor = crate::BufferDescriptor { + label: descriptor.label, + size: 0, + usage: descriptor.usage, + mapped_at_creation: false, + }; + + self.create_buffer(&wgt_descriptor) + } else { + let unpadded_size = descriptor.contents.len() as crate::BufferAddress; + // Valid vulkan usage is + // 1. buffer size must be a multiple of COPY_BUFFER_ALIGNMENT. + // 2. buffer size must be greater than 0. + // Therefore we round the value up to the nearest multiple, and ensure it's at least COPY_BUFFER_ALIGNMENT. + let align_mask = crate::COPY_BUFFER_ALIGNMENT - 1; + let padded_size = + ((unpadded_size + align_mask) & !align_mask).max(crate::COPY_BUFFER_ALIGNMENT); + + let wgt_descriptor = crate::BufferDescriptor { + label: descriptor.label, + size: padded_size, + usage: descriptor.usage, + mapped_at_creation: true, + }; + + let buffer = self.create_buffer(&wgt_descriptor); + + buffer + .slice(..unpadded_size) + .get_mapped_range_mut() + .copy_from_slice(descriptor.contents); + buffer.unmap(); + + buffer + } } fn create_texture_with_data(