From 995ee7b3f1adfc3729d3fda2122f930c1e6b697f Mon Sep 17 00:00:00 2001 From: teoxoy <28601907+teoxoy@users.noreply.github.com> Date: Mon, 22 Jun 2026 20:18:33 +0200 Subject: [PATCH] add `Limits::max_buffers_and_acceleration_structures_per_shader_stage` --- CHANGELOG.md | 1 + .../tests/wgpu-gpu/buffer_resource_limits.rs | 339 ++++++++++++++++++ tests/tests/wgpu-gpu/main.rs | 2 + wgpu-core/src/binding_model.rs | 32 +- wgpu-core/src/device/resource.rs | 28 +- wgpu-core/src/limits.rs | 1 + wgpu-core/src/pipeline.rs | 3 + wgpu-hal/src/dx12/adapter.rs | 1 + wgpu-hal/src/gles/adapter.rs | 1 + wgpu-hal/src/metal/adapter.rs | 65 ++-- wgpu-hal/src/metal/command.rs | 4 +- wgpu-hal/src/metal/device.rs | 6 +- wgpu-hal/src/metal/mod.rs | 22 +- wgpu-hal/src/vulkan/adapter.rs | 1 + wgpu-info/src/human.rs | 2 + wgpu-types/src/limits.rs | 18 + wgpu/src/backend/webgpu.rs | 2 + 17 files changed, 489 insertions(+), 39 deletions(-) create mode 100644 tests/tests/wgpu-gpu/buffer_resource_limits.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ab39132d..3f726adab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -168,6 +168,7 @@ By @stuartparmenter in [#9658](https://github.com/gfx-rs/wgpu/pull/9658). - Implemented `QuerySet::destroy` by @sagudev in [#9671](https://github.com/gfx-rs/wgpu/pull/9671) - Implemented query set initialization tracking, ensuring unwritten query slots resolve to 0; avoiding UB. By @teoxoy in [#9664](https://github.com/gfx-rs/wgpu/pull/9664). - Add `Surface::display_hdr_info`, a read-only snapshot of the backing display's HDR characteristics (luminance in nits, EDR headroom, primaries, bit depth, and a coarse dynamic-range/gamut bucket) for tone-mapping. `DisplayHdrInfo::tone_map_headroom()` folds it into the one multiplier most tone-mappers want; whether to request an HDR surface at all is a separate, capability question answered by `SurfaceCapabilities`, not by this live value. Populated on DX12 and Vulkan on Windows, Metal on macOS, and the web. By @stuartparmenter. +- Added `Limits::max_buffers_and_acceleration_structures_per_shader_stage`, a combined limit for all buffer types (storage, uniform, vertex buffers, and acceleration structures) that share Metal's buffer argument table. On Metal without `InstanceFlags::STRICT_WEBGPU_COMPLIANCE` set, the new limit and the individual per-type limits (`max_storage_buffers_per_shader_stage`, `max_uniform_buffers_per_shader_stage`, `max_vertex_buffers`, `max_acceleration_structures_per_shader_stage`) are set to 29. By @teoxoy in [#9709](https://github.com/gfx-rs/wgpu/pull/9709). #### Metal diff --git a/tests/tests/wgpu-gpu/buffer_resource_limits.rs b/tests/tests/wgpu-gpu/buffer_resource_limits.rs new file mode 100644 index 000000000..cc7008f03 --- /dev/null +++ b/tests/tests/wgpu-gpu/buffer_resource_limits.rs @@ -0,0 +1,339 @@ +/// Tests for `max_buffers_and_acceleration_structures_per_shader_stage`. +/// +/// This limit only has a meaningful finite value on Metal (non-strict mode), where all buffer +/// types (storage, uniform, vertex buffers, acceleration structures) share a single argument +/// table of 31 slots with 2 reserved for internal use, leaving 29 user-visible slots. +/// +/// On all other backends the limit is `u32::MAX`, so these tests are skipped there to avoid +/// hitting other, lower per-type limits while trying to reach the combined limit. +use wgpu_test::{ + fail, gpu_test, valid, FailureCase, GpuTestConfiguration, GpuTestInitializer, TestParameters, +}; + +pub fn all_tests(vec: &mut Vec) { + vec.extend([ + BUFFERS_AND_ACCEL_STRUCTS_VALID_WITHIN_LIMIT, + BUFFERS_AND_ACCEL_STRUCTS_VALID_VERTEX_STAGE_AT_LIMIT, + BUFFERS_AND_ACCEL_STRUCTS_EXCEEDS_SINGLE_BGL, + BUFFERS_AND_ACCEL_STRUCTS_EXCEEDS_ACROSS_BGLS, + BUFFERS_AND_ACCEL_STRUCTS_VERTEX_STAGE_EXCEEDS_WITH_VERTEX_BUFFERS, + ]); +} + +/// Skip on every backend except Metal. The combined limit is `u32::MAX` on other backends, +/// so reaching it would require an impractical number of resources and would run into the +/// individual per-type limits instead. +fn skip_non_metal() -> FailureCase { + FailureCase::backend(!wgpu::Backends::METAL) +} + +/// Device limits that reflect Metal's combined buffer slot constraint. +/// +/// `max_buffers_and_acceleration_structures_per_shader_stage` is set to 29 (Metal's limit). +/// The per-type limits are raised above the default 8/12 so that tests can exercise the +/// *combined* limit without being blocked by an individual per-type limit first. +/// +/// Setting `max_storage_buffers_per_shader_stage: 29` also means the test is automatically +/// skipped on Metal in STRICT_WEBGPU_COMPLIANCE mode, where the adapter only supports 8. +fn metal_limits() -> wgpu::Limits { + wgpu::Limits { + max_storage_buffers_per_shader_stage: 29, + max_uniform_buffers_per_shader_stage: 29, + max_vertex_buffers: 16, + max_buffers_and_acceleration_structures_per_shader_stage: 29, + ..wgpu::Limits::defaults() + } +} + +fn storage_entries(n: u32, visibility: wgpu::ShaderStages) -> Vec { + (0..n) + .map(|i| wgpu::BindGroupLayoutEntry { + binding: i, + visibility, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: true }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }) + .collect() +} + +fn uniform_entries( + n: u32, + binding_offset: u32, + visibility: wgpu::ShaderStages, +) -> Vec { + (0..n) + .map(|i| wgpu::BindGroupLayoutEntry { + binding: binding_offset + i, + visibility, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }) + .collect() +} + +/// 14 storage + 14 uniform = 28 combined in a BGL. +/// Pipeline layout creation must succeed since 28 < 29. +#[gpu_test] +static BUFFERS_AND_ACCEL_STRUCTS_VALID_WITHIN_LIMIT: GpuTestConfiguration = + GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .limits(metal_limits()) + .skip(skip_non_metal()), + ) + .run_sync(|ctx| { + let mut entries = storage_entries(14, wgpu::ShaderStages::COMPUTE); + entries.extend(uniform_entries(14, 14, wgpu::ShaderStages::COMPUTE)); + + valid(&ctx.device, || { + let bgl = ctx + .device + .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, + entries: &entries, + }); + let _ = ctx + .device + .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + }); + }); + +/// 20 storage buffers + 9 vertex buffers = 29 combined. +/// Render pipeline creation must succeed since 29 == limit. +#[gpu_test] +static BUFFERS_AND_ACCEL_STRUCTS_VALID_VERTEX_STAGE_AT_LIMIT: GpuTestConfiguration = + GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .limits(metal_limits()) + .skip(skip_non_metal()), + ) + .run_sync(|ctx| { + let entries = storage_entries(20, wgpu::ShaderStages::VERTEX); + + let bgl = ctx + .device + .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, + entries: &entries, + }); + let pipeline_layout = + ctx.device + .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + + let shader = ctx + .device + .create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl( + "@vertex fn vs() -> @builtin(position) vec4f { return vec4f(0.0); } + @fragment fn fs() -> @location(0) vec4f { return vec4f(0.0); }" + .into(), + ), + }); + + const EMPTY_VB: Option> = + Some(wgpu::VertexBufferLayout { + array_stride: 4, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &[], + }); + + valid(&ctx.device, || { + let _ = ctx + .device + .create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: None, + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs"), + compilation_options: Default::default(), + buffers: &[EMPTY_VB; 9], + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: wgpu::TextureFormat::Rgba8Unorm, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, + }); + }); + }); + +/// 15 storage + 15 uniform = 30 combined in a single BGL. +/// Must fail at BGL creation since the combined limit is 29. +#[gpu_test] +static BUFFERS_AND_ACCEL_STRUCTS_EXCEEDS_SINGLE_BGL: GpuTestConfiguration = + GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .limits(metal_limits()) + .skip(skip_non_metal()), + ) + .run_sync(|ctx| { + let mut entries = storage_entries(15, wgpu::ShaderStages::COMPUTE); + entries.extend(uniform_entries(15, 15, wgpu::ShaderStages::COMPUTE)); + + fail( + &ctx.device, + || { + let _ = ctx + .device + .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, + entries: &entries, + }); + }, + Some("max_buffers_and_acceleration_structures_per_shader_stage"), + ); + }); + +/// Two BGLs where one has 15 storage buffers and the other has 15 uniform +/// buffers. Each individual BGL is within the combined limit, and neither +/// per-type limit is exceeded across both BGLs. However their combined use +/// in a pipeline layout adds up to 30 total buffer slots, exceeding the limit. +#[gpu_test] +static BUFFERS_AND_ACCEL_STRUCTS_EXCEEDS_ACROSS_BGLS: GpuTestConfiguration = + GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .limits(metal_limits()) + .skip(skip_non_metal()), + ) + .run_sync(|ctx| { + let storage = storage_entries(15, wgpu::ShaderStages::COMPUTE); + let uniform = uniform_entries(15, 0, wgpu::ShaderStages::COMPUTE); + + let bgl_a = ctx + .device + .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("bgl_a"), + entries: &storage, + }); + let bgl_b = ctx + .device + .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("bgl_b"), + entries: &uniform, + }); + + fail( + &ctx.device, + || { + let _ = ctx + .device + .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&bgl_a), Some(&bgl_b)], + immediate_size: 0, + }); + }, + Some("max_buffers_and_acceleration_structures_per_shader_stage"), + ); + }); + +/// 20 storage buffers + 10 vertex buffers = 30 combined in the vertex stage, +/// which exceeds the limit of 29. Render pipeline creation must fail. +#[gpu_test] +static BUFFERS_AND_ACCEL_STRUCTS_VERTEX_STAGE_EXCEEDS_WITH_VERTEX_BUFFERS: GpuTestConfiguration = + GpuTestConfiguration::new() + .parameters( + TestParameters::default() + .limits(metal_limits()) + .skip(skip_non_metal()), + ) + .run_sync(|ctx| { + let entries = storage_entries(20, wgpu::ShaderStages::VERTEX); + + let bgl = ctx + .device + .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, + entries: &entries, + }); + let pipeline_layout = + ctx.device + .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + + let shader = ctx + .device + .create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl( + "@vertex fn vs() -> @builtin(position) vec4f { return vec4f(0.0); } + @fragment fn fs() -> @location(0) vec4f { return vec4f(0.0); }" + .into(), + ), + }); + + const EMPTY_VB: Option> = + Some(wgpu::VertexBufferLayout { + array_stride: 4, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &[], + }); + + fail( + &ctx.device, + || { + let _ = ctx + .device + .create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: None, + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs"), + compilation_options: Default::default(), + buffers: &[EMPTY_VB; 10], + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: wgpu::TextureFormat::Rgba8Unorm, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, + }); + }, + Some("vertex-stage buffers and acceleration structures"), + ); + }); diff --git a/tests/tests/wgpu-gpu/main.rs b/tests/tests/wgpu-gpu/main.rs index f4fd8ae7e..a9e6a3547 100644 --- a/tests/tests/wgpu-gpu/main.rs +++ b/tests/tests/wgpu-gpu/main.rs @@ -20,6 +20,7 @@ mod bind_groups; mod binding_array; mod buffer; mod buffer_copy; +mod buffer_resource_limits; mod buffer_usages; mod clear_texture; mod clip_distances; @@ -90,6 +91,7 @@ fn all_tests() -> Vec { adapter::all_tests(&mut tests); bgra8unorm_storage::all_tests(&mut tests); + buffer_resource_limits::all_tests(&mut tests); bind_group_layout_dedup::all_tests(&mut tests); bind_groups::all_tests(&mut tests); binding_array::all_tests(&mut tests); diff --git a/wgpu-core/src/binding_model.rs b/wgpu-core/src/binding_model.rs index 127d8677c..576357d25 100644 --- a/wgpu-core/src/binding_model.rs +++ b/wgpu-core/src/binding_model.rs @@ -334,6 +334,7 @@ pub enum BindingTypeMaxCountErrorKind { BindingArraySamplerElements, BindingArrayAccelerationStructureElements, AccelerationStructures, + BuffersAndAccelerationStructures, } impl BindingTypeMaxCountErrorKind { @@ -366,6 +367,9 @@ impl BindingTypeMaxCountErrorKind { BindingTypeMaxCountErrorKind::AccelerationStructures => { "max_acceleration_structures_per_shader_stage" } + BindingTypeMaxCountErrorKind::BuffersAndAccelerationStructures => { + "max_buffers_and_acceleration_structures_per_shader_stage" + } } } } @@ -534,7 +538,11 @@ impl BindingTypeMaxCountValidator { .merge(&other.binding_array_acceleration_structure_elements); } - pub(crate) fn validate(&self, limits: &wgt::Limits) -> Result<(), BindingTypeMaxCountError> { + pub(crate) fn validate( + &self, + limits: &wgt::Limits, + instance_flags: wgt::InstanceFlags, + ) -> Result<(), BindingTypeMaxCountError> { if limits.max_dynamic_uniform_buffers_per_pipeline_layout < self.dynamic_uniform_buffers { return Err(BindingTypeMaxCountError { kind: BindingTypeMaxCountErrorKind::DynamicUniformBuffers, @@ -588,9 +596,29 @@ impl BindingTypeMaxCountValidator { limits.max_acceleration_structures_per_shader_stage, BindingTypeMaxCountErrorKind::AccelerationStructures, )?; + + if !instance_flags.contains(wgt::InstanceFlags::STRICT_WEBGPU_COMPLIANCE) { + self.buffers_and_acceleration_structures().validate( + limits.max_buffers_and_acceleration_structures_per_shader_stage, + BindingTypeMaxCountErrorKind::BuffersAndAccelerationStructures, + )?; + } + Ok(()) } + fn buffers_and_acceleration_structures(&self) -> PerStageBindingTypeCounter { + let mut buffers_and_acceleration_structures = PerStageBindingTypeCounter::default(); + buffers_and_acceleration_structures.merge(&self.uniform_buffers); + buffers_and_acceleration_structures.merge(&self.storage_buffers); + buffers_and_acceleration_structures.merge(&self.acceleration_structures); + buffers_and_acceleration_structures + } + + pub(crate) fn buffers_and_acceleration_structures_in_vertex_stage(&self) -> u32 { + self.buffers_and_acceleration_structures().vertex.0 + } + /// Validate that the bind group layout does not contain both a binding array and a dynamic offset array. /// /// This allows us to use `UPDATE_AFTER_BIND` on vulkan for bindless arrays. Vulkan does not allow @@ -1005,6 +1033,7 @@ pub struct PipelineLayout { pub(crate) label: String, pub(crate) bind_group_layouts: ArrayVec>, { hal::MAX_BIND_GROUPS }>, pub(crate) immediate_size: u32, + pub(crate) buffers_and_acceleration_structures_in_vertex_stage: u32, } impl Drop for PipelineLayout { @@ -1111,6 +1140,7 @@ impl PipelineLayout { label, bind_group_layouts: ArrayVec::new(), immediate_size: 0, + buffers_and_acceleration_structures_in_vertex_stage: 0, }) } } diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index e577b4ea8..2e09f25f3 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -2952,7 +2952,7 @@ impl Device { // If a single bind group layout violates limits, the pipeline layout is // definitely going to violate limits too, lets catch it now. count_validator - .validate(&self.limits) + .validate(&self.limits, self.instance_flags) .map_err(CreateBindGroupLayoutError::TooManyBindings)?; // Validate that binding arrays don't conflict with dynamic offsets. @@ -3902,9 +3902,12 @@ impl Device { } count_validator - .validate(&self.limits) + .validate(&self.limits, self.instance_flags) .map_err(Error::TooManyBindings)?; + let buffers_and_acceleration_structures_in_vertex_stage = + count_validator.buffers_and_acceleration_structures_in_vertex_stage(); + let get_bgl_iter = || { desc.bind_group_layouts .iter() @@ -3945,6 +3948,7 @@ impl Device { label: desc.label.to_string(), bind_group_layouts, immediate_size: desc.immediate_size, + buffers_and_acceleration_structures_in_vertex_stage, }; let layout = Arc::new(layout); @@ -4900,6 +4904,26 @@ impl Device { }, ); } + + let given = pipeline_layout + .buffers_and_acceleration_structures_in_vertex_stage + .saturating_add(vertex.buffers.len() as u32); + if !self + .instance_flags + .contains(wgt::InstanceFlags::STRICT_WEBGPU_COMPLIANCE) + { + let limit = self + .limits + .max_buffers_and_acceleration_structures_per_shader_stage; + if given > limit { + return Err( + pipeline::CreateRenderPipelineError::TooManyBuffersAndAccelerationStructuresInVertexStage { + given, + limit, + }, + ); + } + } } // Multiview is only supported if the feature is enabled diff --git a/wgpu-core/src/limits.rs b/wgpu-core/src/limits.rs index 8b034249c..a0a80fed9 100644 --- a/wgpu-core/src/limits.rs +++ b/wgpu-core/src/limits.rs @@ -362,6 +362,7 @@ const BUCKET_M1: Bucket = Bucket { max_dynamic_uniform_buffers_per_pipeline_layout: 12, max_sampled_textures_per_shader_stage: 48, max_storage_buffer_binding_size: 1 << 30, // 1 GB, + max_storage_buffers_per_shader_stage: 9, max_vertex_attributes: 31, ..UPLEVEL.limits }, diff --git a/wgpu-core/src/pipeline.rs b/wgpu-core/src/pipeline.rs index a03a32f0a..710a7ea4a 100644 --- a/wgpu-core/src/pipeline.rs +++ b/wgpu-core/src/pipeline.rs @@ -772,6 +772,8 @@ pub enum CreateRenderPipelineError { TooManyVertexBuffers { given: u32, limit: u32 }, #[error("The number of bind groups + vertex buffers {given} exceeds the limit {limit}")] TooManyBindGroupsPlusVertexBuffers { given: u32, limit: u32 }, + #[error("The number of vertex-stage buffers and acceleration structures {given} exceeds the limit {limit}")] + TooManyBuffersAndAccelerationStructuresInVertexStage { given: u32, limit: u32 }, #[error("The total number of vertex attributes {given} exceeds the limit {limit}")] TooManyVertexAttributes { given: u32, limit: u32 }, #[error("Vertex attribute location {given} must be less than limit {limit}")] @@ -853,6 +855,7 @@ impl WebGpuError for CreateRenderPipelineError { | Self::InvalidSampleCount(_) | Self::TooManyVertexBuffers { .. } | Self::TooManyBindGroupsPlusVertexBuffers { .. } + | Self::TooManyBuffersAndAccelerationStructuresInVertexStage { .. } | Self::TooManyVertexAttributes { .. } | Self::VertexAttributeLocationTooLarge { .. } | Self::VertexStrideTooLarge { .. } diff --git a/wgpu-hal/src/dx12/adapter.rs b/wgpu-hal/src/dx12/adapter.rs index e1d436ab1..621eea4ca 100644 --- a/wgpu-hal/src/dx12/adapter.rs +++ b/wgpu-hal/src/dx12/adapter.rs @@ -1013,6 +1013,7 @@ impl super::Adapter { 0 }, max_acceleration_structures_per_shader_stage, + max_buffers_and_acceleration_structures_per_shader_stage: u32::MAX, max_binding_array_acceleration_structure_elements_per_shader_stage: max_acceleration_structures_per_shader_stage, max_multiview_view_count, diff --git a/wgpu-hal/src/gles/adapter.rs b/wgpu-hal/src/gles/adapter.rs index 072415075..47b8115a8 100644 --- a/wgpu-hal/src/gles/adapter.rs +++ b/wgpu-hal/src/gles/adapter.rs @@ -904,6 +904,7 @@ impl super::Adapter { max_blas_geometry_count: 0, max_tlas_instance_count: 0, max_acceleration_structures_per_shader_stage: 0, + max_buffers_and_acceleration_structures_per_shader_stage: u32::MAX, max_multiview_view_count: 0, diff --git a/wgpu-hal/src/metal/adapter.rs b/wgpu-hal/src/metal/adapter.rs index 4332bbf91..c9c48c359 100644 --- a/wgpu-hal/src/metal/adapter.rs +++ b/wgpu-hal/src/metal/adapter.rs @@ -47,22 +47,11 @@ fn device_class_responds_to(device: &ProtocolObject, sel: Sel) -> /// [new command buffer]: https://developer.apple.com/documentation/metal/mtlcommandqueue/makecommandbuffer()?language=objc pub(super) const MAX_COMMAND_BUFFERS: usize = 4096; -// Metal has a single buffer limit that we must split across 3 WebGPU limits: -// The Metal limit is: 31 "Maximum number of entries in the buffer argument table, per graphics or kernel function". -// We must split it across: -// - maxStorageBuffersPerShaderStage; must be at least 8 -// - maxUniformBuffersPerShaderStage; must be at least 12 -// - maxVertexBuffers; must be at least 8 -// We require 2 additional internal buffers: -// - one for immediate data -// - one for sizes of other buffers -// We use the last buffer for an acceleration structure. -const MAX_STORAGE_BUFFERS_PER_SHADER_STAGE: u32 = 8; -const MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE: u32 = 12; -const MAX_VERTEX_BUFFERS: u32 = 8; -const MAX_ACCELERATION_STRUCTURES_PER_SHADER_STAGE: u32 = 1; -// Use the end of the range for vertex buffers. -pub const VERTEX_BUFFER_SLOT_START: u32 = 31 - 8; +/// "Maximum number of entries in the buffer argument table, per graphics or kernel function" +/// +/// Vertex buffers are placed at the end of the table (highest indices), +/// counting down from MAX_BUFFERS - 1. +pub const MAX_BUFFERS: u32 = 31; impl super::Adapter { pub(super) fn new(shared: Arc) -> Self { @@ -1341,7 +1330,7 @@ impl super::CapabilitiesQuery { features } - pub fn capabilities(&self) -> crate::Capabilities { + pub fn capabilities(&self, instance_flags: wgt::InstanceFlags) -> crate::Capabilities { let mut downlevel = wgt::DownlevelCapabilities::default(); downlevel.flags.set( wgt::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE, @@ -1378,6 +1367,34 @@ impl super::CapabilitiesQuery { self.format_bc || (self.format_eac_etc && self.format_astc), ); + let max_storage_buffers_per_shader_stage; + let max_uniform_buffers_per_shader_stage; + let max_vertex_buffers; + let max_acceleration_structures_per_shader_stage; + let max_buffers_and_acceleration_structures_per_shader_stage; + + // Metal has a single buffer limit that we must split across 3 WebGPU limits: + // - maxStorageBuffersPerShaderStage; must be at least 8 + // - maxUniformBuffersPerShaderStage; must be at least 12 + // - maxVertexBuffers; must be at least 8 + // We also have to reserve 2 additional internal buffers: + // - one for immediate data + // - one for sizes of other buffers + if instance_flags.contains(wgt::InstanceFlags::STRICT_WEBGPU_COMPLIANCE) { + max_storage_buffers_per_shader_stage = 9; + max_uniform_buffers_per_shader_stage = 12; + max_vertex_buffers = 8; + max_acceleration_structures_per_shader_stage = 0; + max_buffers_and_acceleration_structures_per_shader_stage = u32::MAX; + } else { + const MAX_USABLE_BUFFERS: u32 = MAX_BUFFERS - 2; + max_storage_buffers_per_shader_stage = MAX_USABLE_BUFFERS; + max_uniform_buffers_per_shader_stage = MAX_USABLE_BUFFERS; + max_vertex_buffers = MAX_USABLE_BUFFERS; + max_acceleration_structures_per_shader_stage = MAX_USABLE_BUFFERS; + max_buffers_and_acceleration_structures_per_shader_stage = MAX_USABLE_BUFFERS; + } + let limits = crate::auxil::adjust_raw_limits(wgt::Limits { // // WebGPU LIMITS: @@ -1394,16 +1411,16 @@ impl super::CapabilitiesQuery { // No limit. max_bindings_per_bind_group: u32::MAX, // No limit, use maxUniformBuffersPerShaderStage. - max_dynamic_uniform_buffers_per_pipeline_layout: MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE, + max_dynamic_uniform_buffers_per_pipeline_layout: max_uniform_buffers_per_shader_stage, // No limit, use maxStorageBuffersPerShaderStage. - max_dynamic_storage_buffers_per_pipeline_layout: MAX_STORAGE_BUFFERS_PER_SHADER_STAGE, + max_dynamic_storage_buffers_per_pipeline_layout: max_storage_buffers_per_shader_stage, // "Maximum number of entries in the sampler state argument table, per graphics or kernel function" max_samplers_per_shader_stage: 16, max_sampled_textures_per_shader_stage: self.max_textures_per_stage.0, max_storage_textures_per_shader_stage: self.max_textures_per_stage.1, - max_storage_buffers_per_shader_stage: MAX_STORAGE_BUFFERS_PER_SHADER_STAGE, - max_uniform_buffers_per_shader_stage: MAX_UNIFORM_BUFFERS_PER_SHADER_STAGE, - max_vertex_buffers: MAX_VERTEX_BUFFERS, + max_storage_buffers_per_shader_stage, + max_uniform_buffers_per_shader_stage, + max_vertex_buffers, max_buffer_size: self.max_buffer_size, // No limit, use maxBufferSize. max_uniform_buffer_binding_size: self.max_buffer_size, @@ -1445,8 +1462,8 @@ impl super::CapabilitiesQuery { // From 2.17.7 in https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf // > [Acceleration structures] are opaque objects that can be bound directly using // buffer binding points or via argument buffers - max_acceleration_structures_per_shader_stage: - MAX_ACCELERATION_STRUCTURES_PER_SHADER_STAGE, + max_acceleration_structures_per_shader_stage, + max_buffers_and_acceleration_structures_per_shader_stage, max_multiview_view_count: if self.supported_vertex_amplification_factor > 1 { self.supported_vertex_amplification_factor diff --git a/wgpu-hal/src/metal/command.rs b/wgpu-hal/src/metal/command.rs index 0613302c4..ba41a6312 100644 --- a/wgpu-hal/src/metal/command.rs +++ b/wgpu-hal/src/metal/command.rs @@ -14,7 +14,7 @@ use objc2_metal::{ }; use super::{ - adapter::{self, VERTEX_BUFFER_SLOT_START}, + adapter::{self, MAX_BUFFERS}, conv, TimestampQuerySupport, }; use crate::CommandEncoder as _; @@ -1411,7 +1411,7 @@ impl crate::CommandEncoder for super::CommandEncoder { index: u32, binding: crate::BufferBinding<'a, super::Buffer>, ) { - let buffer_index = VERTEX_BUFFER_SLOT_START + index; + let buffer_index = MAX_BUFFERS - 1 - index; let encoder = self.state.render.as_ref().unwrap(); unsafe { encoder.setVertexBuffer_offset_atIndex( diff --git a/wgpu-hal/src/metal/device.rs b/wgpu-hal/src/metal/device.rs index c567073fc..d7287b977 100644 --- a/wgpu-hal/src/metal/device.rs +++ b/wgpu-hal/src/metal/device.rs @@ -24,7 +24,7 @@ use objc2_metal::{ }; use parking_lot::{Condvar, Mutex, RwLock}; -use super::{adapter::VERTEX_BUFFER_SLOT_START, conv, PassthroughShader, ShaderModuleSource}; +use super::{adapter::MAX_BUFFERS, conv, PassthroughShader, ShaderModuleSource}; use crate::{auxil::map_naga_stage, DropCallback, DropGuard, TlasInstance}; type DeviceResult = Result; @@ -1423,7 +1423,7 @@ impl crate::Device for super::Device { } let mapping = naga::back::msl::VertexBufferMapping { - id: VERTEX_BUFFER_SLOT_START + i as u32, + id: MAX_BUFFERS - 1 - i as u32, stride: if vbl.array_stride > 0 { vbl.array_stride.try_into().unwrap() } else { @@ -1491,7 +1491,7 @@ impl crate::Device for super::Device { continue; }; - let buffer_index = VERTEX_BUFFER_SLOT_START as usize + i; + let buffer_index = MAX_BUFFERS as usize - 1 - i; let buffer_desc = unsafe { vertex_descriptor .layouts() diff --git a/wgpu-hal/src/metal/mod.rs b/wgpu-hal/src/metal/mod.rs index 4c897c277..e227590e5 100644 --- a/wgpu-hal/src/metal/mod.rs +++ b/wgpu-hal/src/metal/mod.rs @@ -137,7 +137,9 @@ impl OsFeatures { } #[derive(Debug)] -pub struct Instance {} +pub struct Instance { + flags: wgt::InstanceFlags, +} impl Instance { pub fn create_surface_from_layer(&self, layer: &CAMetalLayer) -> Surface { @@ -148,11 +150,11 @@ impl Instance { impl crate::Instance for Instance { type A = Api; - unsafe fn init(_desc: &crate::InstanceDescriptor<'_>) -> Result { + unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result { profiling::scope!("Init Metal Backend"); // We do not enable metal validation based on the validation flags as it affects the entire // process. Instead, we enable the validation inside the test harness itself in tests/src/native.rs. - Ok(Instance {}) + Ok(Instance { flags: desc.flags }) } unsafe fn create_surface( @@ -190,8 +192,11 @@ impl crate::Instance for Instance { _surface_hint: Option<&Surface>, ) -> Vec> { let devices = objc2_metal::MTLCopyAllDevices(); - let mut adapters: Vec> = - devices.into_iter().map(AdapterShared::expose).collect(); + let instance_flags = self.flags; + let mut adapters: Vec> = devices + .into_iter() + .map(|d| AdapterShared::expose(d, instance_flags)) + .collect(); adapters.sort_by_key(|ad| { ( ad.adapter.shared.private_caps.low_power, @@ -420,13 +425,16 @@ impl AdapterShared { } } - fn expose(device: Retained>) -> crate::ExposedAdapter { + fn expose( + device: Retained>, + instance_flags: wgt::InstanceFlags, + ) -> crate::ExposedAdapter { autoreleasepool(|_| { let name = device.name().to_string(); let capabilities_query = CapabilitiesQuery::new(&device); let shared = AdapterShared::new(device, &capabilities_query); let features = capabilities_query.features(); - let capabilities = capabilities_query.capabilities(); + let capabilities = capabilities_query.capabilities(instance_flags); crate::ExposedAdapter { info: wgt::AdapterInfo { name, diff --git a/wgpu-hal/src/vulkan/adapter.rs b/wgpu-hal/src/vulkan/adapter.rs index 0346afe69..1cb5e8e55 100644 --- a/wgpu-hal/src/vulkan/adapter.rs +++ b/wgpu-hal/src/vulkan/adapter.rs @@ -1780,6 +1780,7 @@ impl PhysicalDeviceProperties { max_blas_geometry_count, max_tlas_instance_count, max_acceleration_structures_per_shader_stage, + max_buffers_and_acceleration_structures_per_shader_stage: u32::MAX, max_multiview_view_count, diff --git a/wgpu-info/src/human.rs b/wgpu-info/src/human.rs index daa8d34d3..baf689007 100644 --- a/wgpu-info/src/human.rs +++ b/wgpu-info/src/human.rs @@ -201,6 +201,7 @@ fn print_adapter(output: &mut impl io::Write, report: &AdapterReport, idx: usize max_blas_geometry_count, max_tlas_instance_count, max_acceleration_structures_per_shader_stage, + max_buffers_and_acceleration_structures_per_shader_stage, max_multiview_view_count, @@ -262,6 +263,7 @@ fn print_adapter(output: &mut impl io::Write, report: &AdapterReport, idx: usize writeln!(output, "\t\t Max BLAS Geometry count: {max_blas_geometry_count}")?; writeln!(output, "\t\t Max TLAS Instance count: {max_tlas_instance_count}")?; writeln!(output, "\t\t Max Acceleration Structures Per Shader Stage: {max_acceleration_structures_per_shader_stage}")?; + writeln!(output, " Max Buffers And Acceleration Structures Per Shader Stage: {max_buffers_and_acceleration_structures_per_shader_stage}")?; writeln!(output, "\t\t Max Multiview View Count: {max_multiview_view_count}")?; writeln!(output, "\t\t Max Ray Dispatch Count: {max_ray_dispatch_count}")?; diff --git a/wgpu-types/src/limits.rs b/wgpu-types/src/limits.rs index f6042d0a7..8fb64f271 100644 --- a/wgpu-types/src/limits.rs +++ b/wgpu-types/src/limits.rs @@ -87,6 +87,10 @@ macro_rules! with_limits { $macro_name!(max_blas_geometry_count, Ordering::Less); $macro_name!(max_tlas_instance_count, Ordering::Less); $macro_name!(max_acceleration_structures_per_shader_stage, Ordering::Less); + $macro_name!( + max_buffers_and_acceleration_structures_per_shader_stage, + Ordering::Less + ); $macro_name!(max_multiview_view_count, Ordering::Less); @@ -316,6 +320,9 @@ pub struct Limits { /// Requesting more than 0 during device creation only makes sense if [`Features::EXPERIMENTAL_RAY_QUERY`] /// is enabled. pub max_acceleration_structures_per_shader_stage: u32, + /// The combined number of buffers (storage and uniform), vertex buffers, and acceleration + /// structures that can be bound in a single shader stage. + pub max_buffers_and_acceleration_structures_per_shader_stage: u32, /// The maximum number of views that can be used in multiview rendering pub max_multiview_view_count: u32, @@ -401,6 +408,7 @@ impl Limits { /// max_blas_geometry_count: 0, /// max_tlas_instance_count: 0, /// max_acceleration_structures_per_shader_stage: 0, + /// max_buffers_and_acceleration_structures_per_shader_stage: 28, // sum of storage buffers, uniform buffers and vertex buffers limits /// max_multiview_view_count: 0, /// max_ray_dispatch_count: 0, /// max_ray_recursion_depth: 0, @@ -467,6 +475,7 @@ impl Limits { max_blas_geometry_count: 0, max_tlas_instance_count: 0, max_acceleration_structures_per_shader_stage: 0, + max_buffers_and_acceleration_structures_per_shader_stage: 28, max_multiview_view_count: 0, @@ -536,6 +545,7 @@ impl Limits { /// max_blas_geometry_count: 0, /// max_tlas_instance_count: 0, /// max_acceleration_structures_per_shader_stage: 0, + /// max_buffers_and_acceleration_structures_per_shader_stage: 24, // * sum of storage buffers, uniform buffers and vertex buffers limits /// /// max_multiview_view_count: 0, /// @@ -555,6 +565,7 @@ impl Limits { max_color_attachments: 4, // see: https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=7 max_compute_workgroup_storage_size: 16352, + max_buffers_and_acceleration_structures_per_shader_stage: 24, ..Self::defaults() } } @@ -621,6 +632,7 @@ impl Limits { /// max_blas_geometry_count: 0, /// max_tlas_instance_count: 0, /// max_acceleration_structures_per_shader_stage: 0, + /// max_buffers_and_acceleration_structures_per_shader_stage: 19, // * sum of storage buffers, uniform buffers and vertex buffers limits /// /// max_multiview_view_count: 0, /// @@ -647,6 +659,8 @@ impl Limits { // Value supported by Intel Celeron B830 on Windows (OpenGL 3.1) max_inter_stage_shader_variables: 15, + max_buffers_and_acceleration_structures_per_shader_stage: 19, + // Most of the values should be the same as the downlevel defaults ..Self::downlevel_defaults() } @@ -722,6 +736,7 @@ impl Limits { max_blas_geometry_count: ALLOC_MAX_U32, max_tlas_instance_count: ALLOC_MAX_U32, max_acceleration_structures_per_shader_stage: ALLOC_MAX_U32, + max_buffers_and_acceleration_structures_per_shader_stage: ALLOC_MAX_U32, max_multiview_view_count: ALLOC_MAX_U32, max_ray_dispatch_count: ALLOC_MAX_U32, @@ -765,6 +780,7 @@ impl Limits { max_blas_primitive_count: 1 << 28, // 2^28: Metal's minimum // On metal acceleration structures are limited because they share buffer slots max_acceleration_structures_per_shader_stage: 1, + max_buffers_and_acceleration_structures_per_shader_stage: 29, ..self } } @@ -779,6 +795,8 @@ impl Limits { max_blas_primitive_count: other.max_blas_primitive_count, max_acceleration_structures_per_shader_stage: other .max_acceleration_structures_per_shader_stage, + max_buffers_and_acceleration_structures_per_shader_stage: other + .max_buffers_and_acceleration_structures_per_shader_stage, ..self } } diff --git a/wgpu/src/backend/webgpu.rs b/wgpu/src/backend/webgpu.rs index e1a71120a..8fe0d5fba 100644 --- a/wgpu/src/backend/webgpu.rs +++ b/wgpu/src/backend/webgpu.rs @@ -907,6 +907,8 @@ fn map_wgt_limits(limits: webgpu_sys::GpuSupportedLimits) -> wgt::Limits { max_tlas_instance_count: wgt::Limits::default().max_tlas_instance_count, max_acceleration_structures_per_shader_stage: wgt::Limits::default() .max_acceleration_structures_per_shader_stage, + max_buffers_and_acceleration_structures_per_shader_stage: wgt::Limits::default() + .max_buffers_and_acceleration_structures_per_shader_stage, max_multiview_view_count: wgt::Limits::default().max_multiview_view_count,