From 76bcd9c494a4359853bc2caec8eebbaa990a34e3 Mon Sep 17 00:00:00 2001 From: Luke Street Date: Wed, 8 Sep 2021 13:53:02 -0400 Subject: [PATCH] Implement min_{uniform,storage}_buffer_offset_alignment limits (#1923) * Implement min_{uniform,storage}_buffer_offset_alignment limits * Add Limits::using_alignment * Update docs & examples * Create binding_model::buffer_binding_type_alignment fn --- wgpu-core/src/binding_model.rs | 42 ++++++++++++++++++++++++++----- wgpu-core/src/command/bundle.rs | 26 ++++++++++++------- wgpu-core/src/command/compute.rs | 2 +- wgpu-core/src/command/draw.rs | 4 +-- wgpu-core/src/command/render.rs | 2 +- wgpu-core/src/device/mod.rs | 11 ++++++-- wgpu-core/src/instance.rs | 14 +++-------- wgpu-hal/examples/halmark/main.rs | 26 ++++++++++++++----- wgpu-hal/src/dx12/adapter.rs | 8 +++--- wgpu-hal/src/gles/adapter.rs | 12 +++------ wgpu-hal/src/lib.rs | 2 -- wgpu-hal/src/metal/adapter.rs | 7 +++--- wgpu-hal/src/vulkan/adapter.rs | 6 ++--- wgpu-info/src/main.rs | 42 +++++++++++++++++-------------- wgpu-types/src/lib.rs | 25 ++++++++++++++++-- wgpu/examples/bunnymark/main.rs | 11 +++++--- wgpu/examples/shadow/main.rs | 10 +++++--- wgpu/src/lib.rs | 13 ++++++---- wgpu/tests/common/mod.rs | 2 ++ 19 files changed, 169 insertions(+), 96 deletions(-) diff --git a/wgpu-core/src/binding_model.rs b/wgpu-core/src/binding_model.rs index f25e030e5..e745374ff 100644 --- a/wgpu-core/src/binding_model.rs +++ b/wgpu-core/src/binding_model.rs @@ -93,8 +93,8 @@ pub enum CreateBindGroupError { MissingTextureUsage(#[from] MissingTextureUsageError), #[error("binding declared as a single item, but bind group is using it as an array")] SingleBindingExpected, - #[error("buffer offset {0} does not respect `BIND_BUFFER_ALIGNMENT`")] - UnalignedBufferOffset(wgt::BufferAddress), + #[error("buffer offset {0} does not respect device's requested `{1}` limit {2}")] + UnalignedBufferOffset(wgt::BufferAddress, &'static str, u32), #[error( "buffer binding {binding} range {given} exceeds `max_*_buffer_binding_size` limit {limit}" )] @@ -655,9 +655,14 @@ pub enum BindError { #[error("number of dynamic offsets ({actual}) doesn't match the number of dynamic bindings in the bind group layout ({expected})")] MismatchedDynamicOffsetCount { actual: usize, expected: usize }, #[error( - "dynamic binding at index {idx}: offset {offset} does not respect `BIND_BUFFER_ALIGNMENT`" + "dynamic binding at index {idx}: offset {offset} does not respect device's requested `{limit_name}` limit {alignment}" )] - UnalignedDynamicBinding { idx: usize, offset: u32 }, + UnalignedDynamicBinding { + idx: usize, + offset: u32, + alignment: u32, + limit_name: &'static str, + }, #[error("dynamic binding at index {idx} with offset {offset} would overrun the buffer (limit: {max})")] DynamicBindingOutOfBounds { idx: usize, offset: u32, max: u64 }, } @@ -666,6 +671,24 @@ pub enum BindError { pub struct BindGroupDynamicBindingData { /// The maximum value the dynamic offset can have before running off the end of the buffer. pub(crate) maximum_dynamic_offset: wgt::BufferAddress, + /// The binding type. + pub(crate) binding_type: wgt::BufferBindingType, +} + +pub(crate) fn buffer_binding_type_alignment( + limits: &wgt::Limits, + binding_type: wgt::BufferBindingType, +) -> (u32, &'static str) { + match binding_type { + wgt::BufferBindingType::Uniform => ( + limits.min_uniform_buffer_offset_alignment, + "min_uniform_buffer_offset_alignment", + ), + wgt::BufferBindingType::Storage { .. } => ( + limits.min_storage_buffer_offset_alignment, + "min_storage_buffer_offset_alignment", + ), + } } #[derive(Debug)] @@ -683,6 +706,7 @@ impl BindGroup { pub(crate) fn validate_dynamic_bindings( &self, offsets: &[wgt::DynamicOffset], + limits: &wgt::Limits, ) -> Result<(), BindError> { if self.dynamic_binding_info.len() != offsets.len() { return Err(BindError::MismatchedDynamicOffsetCount { @@ -697,8 +721,14 @@ impl BindGroup { .zip(offsets.iter()) .enumerate() { - if offset as wgt::BufferAddress % wgt::BIND_BUFFER_ALIGNMENT != 0 { - return Err(BindError::UnalignedDynamicBinding { idx, offset }); + let (alignment, limit_name) = buffer_binding_type_alignment(limits, info.binding_type); + if offset as wgt::BufferAddress % alignment as u64 != 0 { + return Err(BindError::UnalignedDynamicBinding { + idx, + offset, + alignment, + limit_name, + }); } if offset as wgt::BufferAddress > info.maximum_dynamic_offset { diff --git a/wgpu-core/src/command/bundle.rs b/wgpu-core/src/command/bundle.rs index fd28ca16b..8531d0849 100644 --- a/wgpu-core/src/command/bundle.rs +++ b/wgpu-core/src/command/bundle.rs @@ -34,6 +34,7 @@ #![allow(clippy::reversed_empty_ranges)] use crate::{ + binding_model::buffer_binding_type_alignment, command::{ BasePass, DrawError, MapPassErr, PassErrorScope, RenderCommand, RenderCommandError, StateChange, @@ -196,15 +197,6 @@ impl RenderBundleEncoder { let offsets = &base.dynamic_offsets[..num_dynamic_offsets as usize]; base.dynamic_offsets = &base.dynamic_offsets[num_dynamic_offsets as usize..]; - // Check for misaligned offsets. - if let Some(offset) = offsets - .iter() - .map(|offset| *offset as wgt::BufferAddress) - .find(|offset| offset % wgt::BIND_BUFFER_ALIGNMENT != 0) - { - return Err(RenderCommandError::UnalignedBufferOffset(offset)) - .map_pass_err(scope); - } let bind_group = state .trackers @@ -220,6 +212,22 @@ impl RenderBundleEncoder { .map_pass_err(scope); } + // Check for misaligned offsets. + for (offset, info) in offsets + .iter() + .map(|offset| *offset as wgt::BufferAddress) + .zip(bind_group.dynamic_binding_info.iter()) + { + let (alignment, limit_name) = + buffer_binding_type_alignment(&device.limits, info.binding_type); + if offset % alignment as u64 != 0 { + return Err(RenderCommandError::UnalignedBufferOffset( + offset, limit_name, alignment, + )) + .map_pass_err(scope); + } + } + buffer_memory_init_actions.extend_from_slice(&bind_group.used_buffer_ranges); state.set_bind_group(index, bind_group_id, bind_group.layout_id, offsets); diff --git a/wgpu-core/src/command/compute.rs b/wgpu-core/src/command/compute.rs index 970e5d885..c2a3e1f0e 100644 --- a/wgpu-core/src/command/compute.rs +++ b/wgpu-core/src/command/compute.rs @@ -360,7 +360,7 @@ impl Global { .map_err(|_| ComputePassErrorInner::InvalidBindGroup(bind_group_id)) .map_pass_err(scope)?; bind_group - .validate_dynamic_bindings(&temp_offsets) + .validate_dynamic_bindings(&temp_offsets, &cmd_buf.limits) .map_pass_err(scope)?; cmd_buf.buffer_memory_init_actions.extend( diff --git a/wgpu-core/src/command/draw.rs b/wgpu-core/src/command/draw.rs index 0a1e422e8..f7a40a020 100644 --- a/wgpu-core/src/command/draw.rs +++ b/wgpu-core/src/command/draw.rs @@ -65,8 +65,8 @@ pub enum RenderCommandError { InvalidRenderBundle(id::RenderBundleId), #[error("bind group index {index} is greater than the device's requested `max_bind_group` limit {max}")] BindGroupIndexOutOfRange { index: u8, max: u32 }, - #[error("dynamic buffer offset {0} does not respect `BIND_BUFFER_ALIGNMENT`")] - UnalignedBufferOffset(u64), + #[error("dynamic buffer offset {0} does not respect device's requested `{1}` limit {2}")] + UnalignedBufferOffset(u64, &'static str, u32), #[error("number of buffer offsets ({actual}) does not match the number of dynamic bindings ({expected})")] InvalidDynamicOffsetCount { actual: usize, expected: usize }, #[error("render pipeline {0:?} is invalid")] diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index 8c8958cd1..6ac1f42a8 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -882,7 +882,7 @@ impl Global { .map_err(|_| RenderCommandError::InvalidBindGroup(bind_group_id)) .map_pass_err(scope)?; bind_group - .validate_dynamic_bindings(&temp_offsets) + .validate_dynamic_bindings(&temp_offsets, &cmd_buf.limits) .map_pass_err(scope)?; // merge the resource tracker in diff --git a/wgpu-core/src/device/mod.rs b/wgpu-core/src/device/mod.rs index e3d4d6581..7dd6b2860 100644 --- a/wgpu-core/src/device/mod.rs +++ b/wgpu-core/src/device/mod.rs @@ -1258,8 +1258,14 @@ impl Device { ), }; - if bb.offset % wgt::BIND_BUFFER_ALIGNMENT != 0 { - return Err(Error::UnalignedBufferOffset(bb.offset)); + let (align, align_limit_name) = + binding_model::buffer_binding_type_alignment(limits, binding_ty); + if bb.offset % align as u64 != 0 { + return Err(Error::UnalignedBufferOffset( + bb.offset, + align_limit_name, + align, + )); } let buffer = used @@ -1299,6 +1305,7 @@ impl Device { if dynamic { dynamic_binding_info.push(binding_model::BindGroupDynamicBindingData { maximum_dynamic_offset: buffer.size - bind_end, + binding_type: binding_ty, }); } diff --git a/wgpu-core/src/instance.rs b/wgpu-core/src/instance.rs index 6272df975..6407259a5 100644 --- a/wgpu-core/src/instance.rs +++ b/wgpu-core/src/instance.rs @@ -6,7 +6,7 @@ use crate::{ LabelHelpers, LifeGuard, Stored, DOWNLEVEL_WARNING_MESSAGE, }; -use wgt::{Backend, Backends, PowerPreference, BIND_BUFFER_ALIGNMENT}; +use wgt::{Backend, Backends, PowerPreference}; use hal::{Adapter as _, Instance as _}; use thiserror::Error; @@ -62,6 +62,8 @@ fn check_limits(requested: &wgt::Limits, allowed: &wgt::Limits) -> Vec Adapter { //TODO } - assert_eq!( - 0, - BIND_BUFFER_ALIGNMENT % caps.alignments.storage_buffer_offset, - "Adapter storage buffer offset alignment not compatible with WGPU" - ); - assert_eq!( - 0, - BIND_BUFFER_ALIGNMENT % caps.alignments.uniform_buffer_offset, - "Adapter uniform buffer offset alignment not compatible with WGPU" - ); if let Some(failed) = check_limits(&desc.limits, &caps.limits).pop() { return Err(RequestDeviceError::LimitsExceeded(failed)); } diff --git a/wgpu-hal/examples/halmark/main.rs b/wgpu-hal/examples/halmark/main.rs index 4e0f2a9d4..694ac118f 100644 --- a/wgpu-hal/examples/halmark/main.rs +++ b/wgpu-hal/examples/halmark/main.rs @@ -66,6 +66,7 @@ struct Example { pipeline: A::RenderPipeline, bunnies: Vec, local_buffer: A::Buffer, + local_alignment: wgt::BufferAddress, global_buffer: A::Buffer, sampler: A::Sampler, texture: A::Texture, @@ -89,7 +90,7 @@ impl Example { let instance = unsafe { A::Instance::init(&instance_desc)? }; let mut surface = unsafe { instance.create_surface(window).unwrap() }; - let adapter = unsafe { + let (adapter, capabilities) = unsafe { let mut adapters = instance.enumerate_adapters(); if adapters.is_empty() { return Err(hal::InstanceError); @@ -99,7 +100,7 @@ impl Example { "Surface caps: {:?}", exposed.adapter.surface_capabilities(&surface) ); - exposed.adapter + (exposed.adapter, exposed.capabilities) }; let hal::OpenDevice { device, mut queue } = unsafe { adapter.open(wgt::Features::empty()).unwrap() }; @@ -366,9 +367,22 @@ impl Example { buffer }; + fn align_to( + value: wgt::BufferAddress, + alignment: wgt::BufferAddress, + ) -> wgt::BufferAddress { + match value % alignment { + 0 => value, + other => value - other + alignment, + } + } + let local_alignment = align_to( + mem::size_of::() as _, + capabilities.limits.min_uniform_buffer_offset_alignment as _, + ); let local_buffer_desc = hal::BufferDescriptor { label: Some("local"), - size: (MAX_BUNNIES as wgt::BufferAddress) * wgt::BIND_BUFFER_ALIGNMENT, + size: (MAX_BUNNIES as wgt::BufferAddress) * local_alignment, usage: hal::BufferUses::MAP_WRITE | hal::BufferUses::UNIFORM, memory_flags: hal::MemoryFlags::PREFER_COHERENT, }; @@ -466,6 +480,7 @@ impl Example { local_group_layout, bunnies: Vec::new(), local_buffer, + local_alignment, global_buffer, sampler, texture, @@ -575,7 +590,7 @@ impl Example { } if !self.bunnies.is_empty() { - let size = self.bunnies.len() * wgt::BIND_BUFFER_ALIGNMENT as usize; + let size = self.bunnies.len() * self.local_alignment as usize; unsafe { let mapping = self .device @@ -649,8 +664,7 @@ impl Example { } for i in 0..self.bunnies.len() { - let offset = - (i as wgt::DynamicOffset) * (wgt::BIND_BUFFER_ALIGNMENT as wgt::DynamicOffset); + let offset = (i as wgt::DynamicOffset) * (self.local_alignment as wgt::DynamicOffset); unsafe { ctx.encoder .set_bind_group(&self.pipeline_layout, 1, &self.local_group, &[offset]); diff --git a/wgpu-hal/src/dx12/adapter.rs b/wgpu-hal/src/dx12/adapter.rs index f8668ddbd..ee33a1b1f 100644 --- a/wgpu-hal/src/dx12/adapter.rs +++ b/wgpu-hal/src/dx12/adapter.rs @@ -238,6 +238,9 @@ impl super::Adapter { max_vertex_attributes: d3d12::D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT, max_vertex_buffer_array_stride: d3d12::D3D12_SO_BUFFER_MAX_STRIDE_IN_BYTES, max_push_constant_size: 0, + min_uniform_buffer_offset_alignment: + d3d12::D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT, + min_storage_buffer_offset_alignment: 4, // TODO? }, alignments: crate::Alignments { buffer_copy_offset: wgt::BufferSize::new( @@ -248,11 +251,6 @@ impl super::Adapter { d3d12::D3D12_TEXTURE_DATA_PITCH_ALIGNMENT as u64, ) .unwrap(), - uniform_buffer_offset: wgt::BufferSize::new( - d3d12::D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT as u64, - ) - .unwrap(), - storage_buffer_offset: wgt::BufferSize::new(4).unwrap(), //TODO? }, downlevel: wgt::DownlevelCapabilities::default(), }, diff --git a/wgpu-hal/src/gles/adapter.rs b/wgpu-hal/src/gles/adapter.rs index c92ecf6bb..6271c2625 100644 --- a/wgpu-hal/src/gles/adapter.rs +++ b/wgpu-hal/src/gles/adapter.rs @@ -288,7 +288,7 @@ impl super::Adapter { let max_texture_3d_size = gl.get_parameter_i32(glow::MAX_3D_TEXTURE_SIZE) as u32; let min_uniform_buffer_offset_alignment = - gl.get_parameter_i32(glow::UNIFORM_BUFFER_OFFSET_ALIGNMENT); + gl.get_parameter_i32(glow::UNIFORM_BUFFER_OFFSET_ALIGNMENT) as u32; let min_storage_buffer_offset_alignment = if ver >= (3, 1) { gl.get_parameter_i32(glow::SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT) as u32 } else { @@ -335,6 +335,8 @@ impl super::Adapter { !0 }, max_push_constant_size: 0, + min_uniform_buffer_offset_alignment, + min_storage_buffer_offset_alignment, }; let mut workarounds = super::Workarounds::empty(); @@ -379,14 +381,6 @@ impl super::Adapter { alignments: crate::Alignments { buffer_copy_offset: wgt::BufferSize::new(4).unwrap(), buffer_copy_pitch: wgt::BufferSize::new(4).unwrap(), - uniform_buffer_offset: wgt::BufferSize::new( - min_storage_buffer_offset_alignment as u64, - ) - .unwrap(), - storage_buffer_offset: wgt::BufferSize::new( - min_uniform_buffer_offset_alignment as u64, - ) - .unwrap(), }, }, }) diff --git a/wgpu-hal/src/lib.rs b/wgpu-hal/src/lib.rs index bc64545f6..0ba2ba9ea 100644 --- a/wgpu-hal/src/lib.rs +++ b/wgpu-hal/src/lib.rs @@ -665,8 +665,6 @@ pub struct Alignments { /// The alignment of the row pitch of the texture data stored in a buffer that is /// used in a GPU copy operation. pub buffer_copy_pitch: wgt::BufferSize, - pub uniform_buffer_offset: wgt::BufferSize, - pub storage_buffer_offset: wgt::BufferSize, } #[derive(Clone, Debug)] diff --git a/wgpu-hal/src/metal/adapter.rs b/wgpu-hal/src/metal/adapter.rs index 1c30af4c0..2a6688920 100644 --- a/wgpu-hal/src/metal/adapter.rs +++ b/wgpu-hal/src/metal/adapter.rs @@ -889,7 +889,6 @@ impl super::PrivateCapabilities { } pub fn capabilities(&self) -> crate::Capabilities { - let buffer_alignment = wgt::BufferSize::new(self.buffer_alignment).unwrap(); let mut downlevel = wgt::DownlevelCapabilities::default(); downlevel.flags.set( wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES, @@ -927,12 +926,12 @@ impl super::PrivateCapabilities { max_vertex_attributes: base.max_vertex_attributes, max_vertex_buffer_array_stride: base.max_vertex_buffer_array_stride, max_push_constant_size: 0x1000, + min_uniform_buffer_offset_alignment: self.buffer_alignment as u32, + min_storage_buffer_offset_alignment: self.buffer_alignment as u32, }, alignments: crate::Alignments { - buffer_copy_offset: buffer_alignment, + buffer_copy_offset: wgt::BufferSize::new(self.buffer_alignment).unwrap(), buffer_copy_pitch: wgt::BufferSize::new(4).unwrap(), - uniform_buffer_offset: buffer_alignment, - storage_buffer_offset: buffer_alignment, }, downlevel, } diff --git a/wgpu-hal/src/vulkan/adapter.rs b/wgpu-hal/src/vulkan/adapter.rs index 5de00bc06..ff6e1a30d 100644 --- a/wgpu-hal/src/vulkan/adapter.rs +++ b/wgpu-hal/src/vulkan/adapter.rs @@ -503,6 +503,8 @@ impl PhysicalDeviceCapabilities { max_vertex_attributes: limits.max_vertex_input_attributes, max_vertex_buffer_array_stride: limits.max_vertex_input_binding_stride, max_push_constant_size: limits.max_push_constants_size, + min_uniform_buffer_offset_alignment: limits.min_uniform_buffer_offset_alignment as u32, + min_storage_buffer_offset_alignment: limits.min_storage_buffer_offset_alignment as u32, } } @@ -513,10 +515,6 @@ impl PhysicalDeviceCapabilities { .unwrap(), buffer_copy_pitch: wgt::BufferSize::new(limits.optimal_buffer_copy_row_pitch_alignment) .unwrap(), - storage_buffer_offset: wgt::BufferSize::new(limits.min_storage_buffer_offset_alignment) - .unwrap(), - uniform_buffer_offset: wgt::BufferSize::new(limits.min_uniform_buffer_offset_alignment) - .unwrap(), } } } diff --git a/wgpu-info/src/main.rs b/wgpu-info/src/main.rs index 1c69e61a2..e780c0e41 100644 --- a/wgpu-info/src/main.rs +++ b/wgpu-info/src/main.rs @@ -29,25 +29,27 @@ fn print_info_from_adapter(adapter: &wgpu::Adapter, idx: usize) { } } println!("\tLimits:"); - let wgpu::Limits { - max_texture_dimension_1d, - max_texture_dimension_2d, - max_texture_dimension_3d, - max_texture_array_layers, - max_bind_groups, - max_dynamic_uniform_buffers_per_pipeline_layout, - max_dynamic_storage_buffers_per_pipeline_layout, - max_sampled_textures_per_shader_stage, - max_samplers_per_shader_stage, - max_storage_buffers_per_shader_stage, - max_storage_textures_per_shader_stage, - max_uniform_buffers_per_shader_stage, - max_uniform_buffer_binding_size, - max_storage_buffer_binding_size, - max_vertex_buffers, - max_vertex_attributes, - max_vertex_buffer_array_stride, - max_push_constant_size, + let wgpu::Limits { + max_texture_dimension_1d, + max_texture_dimension_2d, + max_texture_dimension_3d, + max_texture_array_layers, + max_bind_groups, + max_dynamic_uniform_buffers_per_pipeline_layout, + max_dynamic_storage_buffers_per_pipeline_layout, + max_sampled_textures_per_shader_stage, + max_samplers_per_shader_stage, + max_storage_buffers_per_shader_stage, + max_storage_textures_per_shader_stage, + max_uniform_buffers_per_shader_stage, + max_uniform_buffer_binding_size, + max_storage_buffer_binding_size, + max_vertex_buffers, + max_vertex_attributes, + max_vertex_buffer_array_stride, + max_push_constant_size, + min_uniform_buffer_offset_alignment, + min_storage_buffer_offset_alignment, } = limits; println!("\t\tMax Texture Dimension 1d: {}", max_texture_dimension_1d); println!("\t\tMax Texture Dimension 2d: {}", max_texture_dimension_2d); @@ -67,6 +69,8 @@ fn print_info_from_adapter(adapter: &wgpu::Adapter, idx: usize) { println!("\t\tMax Vertex Attributes: {}", max_vertex_attributes); println!("\t\tMax Vertex Buffer Array Stride: {}", max_vertex_buffer_array_stride); println!("\t\tMax Push Constant Size: {}", max_push_constant_size); + println!("\t\tMin Uniform Buffer Offset Alignment: {}", min_uniform_buffer_offset_alignment); + println!("\t\tMin Storage Buffer Offset Alignment: {}", min_storage_buffer_offset_alignment); println!("\tDownlevel Properties:"); let wgpu::DownlevelCapabilities { shader_model, diff --git a/wgpu-types/src/lib.rs b/wgpu-types/src/lib.rs index 77bbf83d2..b5706325a 100644 --- a/wgpu-types/src/lib.rs +++ b/wgpu-types/src/lib.rs @@ -32,8 +32,6 @@ pub type DynamicOffset = u32; /// /// [`bytes_per_row`]: ImageDataLayout::bytes_per_row pub const COPY_BYTES_PER_ROW_ALIGNMENT: u32 = 256; -/// Bound uniform/storage buffer offsets must be aligned to this number. -pub const BIND_BUFFER_ALIGNMENT: BufferAddress = 256; /// An offset into the query resolve buffer has to be aligned to this. pub const QUERY_RESOLVE_BUFFER_ALIGNMENT: BufferAddress = 256; /// Buffer to buffer copy as well as buffer clear offsets and sizes must be aligned to this number. @@ -629,6 +627,14 @@ pub struct Limits { /// - DX11 & OpenGL don't natively support push constants, and are emulated with uniforms, /// so this number is less useful but likely 256. pub max_push_constant_size: u32, + /// Required `BufferBindingType::Uniform` alignment for `BufferBinding::offset` + /// when creating a `BindGroup`, or for `set_bind_group` `dynamicOffsets`. + /// Defaults to 256. Lower is "better". + pub min_uniform_buffer_offset_alignment: u32, + /// Required `BufferBindingType::Storage` alignment for `BufferBinding::offset` + /// when creating a `BindGroup`, or for `set_bind_group` `dynamicOffsets`. + /// Defaults to 256. Lower is "better". + pub min_storage_buffer_offset_alignment: u32, } impl Default for Limits { @@ -652,6 +658,8 @@ impl Default for Limits { max_vertex_attributes: 16, max_vertex_buffer_array_stride: 2048, max_push_constant_size: 0, + min_uniform_buffer_offset_alignment: 256, + min_storage_buffer_offset_alignment: 256, } } } @@ -678,6 +686,8 @@ impl Limits { max_vertex_attributes: 16, max_vertex_buffer_array_stride: 2048, max_push_constant_size: 0, + min_uniform_buffer_offset_alignment: 256, + min_storage_buffer_offset_alignment: 256, } } @@ -694,6 +704,17 @@ impl Limits { ..self } } + + /// Modify the current limits to use the buffer alignment limits of the adapter. + /// + /// This is useful for when you'd like to dynamically use the "best" supported buffer alignments. + pub fn using_alignment(self, other: Self) -> Self { + Self { + min_uniform_buffer_offset_alignment: other.min_uniform_buffer_offset_alignment, + min_storage_buffer_offset_alignment: other.min_storage_buffer_offset_alignment, + ..self + } + } } /// Represents the sets of additional limits on an adapter, diff --git a/wgpu/examples/bunnymark/main.rs b/wgpu/examples/bunnymark/main.rs index 2677c88d5..f8c1c2b87 100644 --- a/wgpu/examples/bunnymark/main.rs +++ b/wgpu/examples/bunnymark/main.rs @@ -194,9 +194,11 @@ impl framework::Example for Example { contents: bytemuck::bytes_of(&globals), usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::UNIFORM, }); + let uniform_alignment = + device.limits().min_uniform_buffer_offset_alignment as wgpu::BufferAddress; let local_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("local"), - size: (MAX_BUNNIES as wgpu::BufferAddress) * wgpu::BIND_BUFFER_ALIGNMENT, + size: (MAX_BUNNIES as wgpu::BufferAddress) * uniform_alignment, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::UNIFORM, mapped_at_creation: false, }); @@ -305,10 +307,11 @@ impl framework::Example for Example { } } + let uniform_alignment = device.limits().min_uniform_buffer_offset_alignment; queue.write_buffer(&self.local_buffer, 0, unsafe { std::slice::from_raw_parts( self.bunnies.as_ptr() as *const u8, - self.bunnies.len() * wgpu::BIND_BUFFER_ALIGNMENT as usize, + self.bunnies.len() * uniform_alignment as usize, ) }); @@ -335,8 +338,8 @@ impl framework::Example for Example { rpass.set_pipeline(&self.pipeline); rpass.set_bind_group(0, &self.global_group, &[]); for i in 0..self.bunnies.len() { - let offset = (i as wgpu::DynamicOffset) - * (wgpu::BIND_BUFFER_ALIGNMENT as wgpu::DynamicOffset); + let offset = + (i as wgpu::DynamicOffset) * (uniform_alignment as wgpu::DynamicOffset); rpass.set_bind_group(1, &self.local_group, &[offset]); rpass.draw(0..4, 0..1); } diff --git a/wgpu/examples/shadow/main.rs b/wgpu/examples/shadow/main.rs index ecbae99d0..be6ae25ec 100644 --- a/wgpu/examples/shadow/main.rs +++ b/wgpu/examples/shadow/main.rs @@ -286,11 +286,13 @@ impl framework::Example for Example { let entity_uniform_size = mem::size_of::() as wgpu::BufferAddress; let num_entities = 1 + cube_descs.len() as wgpu::BufferAddress; - assert!(entity_uniform_size <= wgpu::BIND_BUFFER_ALIGNMENT); - //Note: dynamic offsets also have to be aligned to `BIND_BUFFER_ALIGNMENT`. + let uniform_alignment = + device.limits().min_uniform_buffer_offset_alignment as wgpu::BufferAddress; + assert!(entity_uniform_size <= uniform_alignment); + // Note: dynamic uniform offsets also have to be aligned to `Limits::min_uniform_buffer_offset_alignment`. let entity_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor { label: None, - size: num_entities * wgpu::BIND_BUFFER_ALIGNMENT, + size: num_entities * uniform_alignment, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); @@ -327,7 +329,7 @@ impl framework::Example for Example { index_buf: Rc::clone(&cube_index_buf), index_format, index_count: cube_index_data.len(), - uniform_offset: ((i + 1) * wgpu::BIND_BUFFER_ALIGNMENT as usize) as _, + uniform_offset: ((i + 1) * uniform_alignment as usize) as _, }); } diff --git a/wgpu/src/lib.rs b/wgpu/src/lib.rs index af3eca44f..2d829e51c 100644 --- a/wgpu/src/lib.rs +++ b/wgpu/src/lib.rs @@ -37,8 +37,8 @@ pub use wgt::{ StorageTextureAccess, SurfaceConfiguration, SurfaceStatus, TextureAspect, TextureDimension, TextureFormat, TextureFormatFeatureFlags, TextureFormatFeatures, TextureSampleType, TextureUsages, TextureViewDimension, VertexAttribute, VertexFormat, VertexStepMode, - BIND_BUFFER_ALIGNMENT, COPY_BUFFER_ALIGNMENT, COPY_BYTES_PER_ROW_ALIGNMENT, MAP_ALIGNMENT, - PUSH_CONSTANT_ALIGNMENT, QUERY_SET_MAX_QUERIES, QUERY_SIZE, VERTEX_STRIDE_ALIGNMENT, + COPY_BUFFER_ALIGNMENT, COPY_BYTES_PER_ROW_ALIGNMENT, MAP_ALIGNMENT, PUSH_CONSTANT_ALIGNMENT, + QUERY_SET_MAX_QUERIES, QUERY_SIZE, VERTEX_STRIDE_ALIGNMENT, }; use backend::{BufferMappedRange, Context as C}; @@ -1008,7 +1008,8 @@ pub struct BufferBinding<'a> { /// Base offset of the buffer. For bindings with `dynamic == true`, this offset /// will be added to the dynamic offset provided in [`RenderPass::set_bind_group`]. /// - /// The offset has to be aligned to [`BIND_BUFFER_ALIGNMENT`]. + /// The offset has to be aligned to [`Limits::min_uniform_buffer_offset_alignment`] + /// or [`Limits::min_storage_buffer_offset_alignment`] appropriately. pub offset: BufferAddress, /// Size of the binding, or `None` for using the rest of the buffer. pub size: Option, @@ -2365,7 +2366,8 @@ impl<'a> RenderPass<'a> { /// in the active pipeline when any `draw()` function is called must match the layout of this bind group. /// /// If the bind group have dynamic offsets, provide them in order of their declaration. - /// These offsets have to be aligned to [`BIND_BUFFER_ALIGNMENT`]. + /// These offsets have to be aligned to [`Limits::min_uniform_buffer_offset_alignment`] + /// or [`Limits::min_storage_buffer_offset_alignment`] appropriately. pub fn set_bind_group( &mut self, index: u32, @@ -2769,7 +2771,8 @@ impl<'a> ComputePass<'a> { /// in the active pipeline when the `dispatch()` function is called must match the layout of this bind group. /// /// If the bind group have dynamic offsets, provide them in order of their declaration. - /// These offsets have to be aligned to [`BIND_BUFFER_ALIGNMENT`]. + /// These offsets have to be aligned to [`Limits::min_uniform_buffer_offset_alignment`] + /// or [`Limits::min_storage_buffer_offset_alignment`] appropriately. pub fn set_bind_group( &mut self, index: u32, diff --git a/wgpu/tests/common/mod.rs b/wgpu/tests/common/mod.rs index 9ee1840ba..20ece7f84 100644 --- a/wgpu/tests/common/mod.rs +++ b/wgpu/tests/common/mod.rs @@ -60,6 +60,8 @@ pub fn lowest_reasonable_limits() -> Limits { max_vertex_attributes: 4, max_vertex_buffer_array_stride: 32, max_push_constant_size: 0, + min_uniform_buffer_offset_alignment: 256, + min_storage_buffer_offset_alignment: 256, } }