Add support for gaps in bind group layouts & update relevant validation (#9034)

* [wgpu-core] add support for optional BG & BGL entries

* [wgpu] allow gaps in bind group layouts

And allow unbinding in the web backend.

* adapt tests

* add changelog entry

* [wgpu] remove generic from `PipelineLayoutDescriptor`
This commit is contained in:
Teodor Tanasoaia authored and GitHub committed 2026-02-25 19:47:36 +01:00
1 parent aad2a00f4d
commit e114d2f0a7
90 files changed
+567 -397

No files matched your search

+19
View File
@@ -44,6 +44,25 @@ Bottom level categories:
### Major Changes
#### Bind group layouts now optional in `PipelineLayoutDescriptor`
Allow gaps in bind group layouts and added full support for unbinding. As a result of this `PipelineLayoutDescriptor`'s `bind_group_layouts` field now has type of `&[Option<&BindGroupLayout>]`, making this a breaking change. To migrate wrap bind group layout references in `Some`:
```diff
let pl_desc = wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[
- &bind_group_layout
+ Some(&bind_group_layout)
],
immediate_size: 0,
});
```
By @teoxoy in [#9034](https://github.com/gfx-rs/wgpu/pull/9034).
#### MSRV update
`wgpu` now has a new MSRV policy. This release has an MSRV of **1.87**. This is lower than v27's 1.88 and v28's 1.92. Going forward, we will only bump wgpu's MSRV if it has tangible benefits for the code, and we will never bump to an MSRV higher than `stable - 3`. So if stable is at 1.97 and 1.94 brought benefit to our code, we could bump it no higher than 1.94. As before, MSRV bumps will always be breaking changes.
By @cwfitzgerald in [#8999](https://github.com/gfx-rs/wgpu/pull/8999).
@@ -250,7 +250,7 @@ impl ComputepassState {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
@@ -345,7 +345,7 @@ impl ComputepassState {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bindless_bind_group_layout],
bind_group_layouts: &[Some(&bindless_bind_group_layout)],
immediate_size: 0,
});
+2 -2
View File
@@ -150,7 +150,7 @@ impl RenderpassState {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
@@ -286,7 +286,7 @@ impl RenderpassState {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bindless_bind_group_layout],
bind_group_layouts: &[Some(&bindless_bind_group_layout)],
immediate_size: 0,
});
+1 -6
View File
@@ -27,7 +27,7 @@ webgpu:api,validation,createBindGroupLayout:max_resources_per_stage,in_pipeline_
webgpu:api,validation,createBindGroupLayout:visibility,VERTEX_shader_stage_buffer_type:* // 25%, writable storage buffers not allowed in VERTEX
webgpu:api,validation,createBindGroupLayout:visibility,VERTEX_shader_stage_storage_texture_access:* // 25%, write-access storage textures not allowed in VERTEX
webgpu:api,validation,createBindGroupLayout:visibility:* // 25%, missing per-stage storage limits
webgpu:api,validation,createPipelineLayout:* // 33%, https://github.com/gfx-rs/wgpu/issues/4738, and at least 1 more issue
webgpu:api,validation,createPipelineLayout:number_of_dynamic_buffers_exceeds_the_maximum_value:* // limits issue
webgpu:api,validation,createView:texture_state:* // 0%, https://github.com/gfx-rs/wgpu/issues/7881
webgpu:api,validation,encoding,cmds,copyTextureToTexture:copy_ranges:* // ***, https://github.com/gfx-rs/wgpu/issues/8118
webgpu:api,validation,encoding,cmds,debug:* // 92%, https://github.com/gfx-rs/wgpu/issues/8039
@@ -40,13 +40,8 @@ webgpu:api,validation,encoding,cmds,setBindGroup:u32array_start_and_length:* //
webgpu:api,validation,encoding,cmds,setImmediates:* // 0%, feature not implemented
webgpu:api,validation,encoding,createRenderBundleEncoder:* // 26%, empty attachments, format compatibility
webgpu:api,validation,encoding,encoder_open_state:* // https://github.com/gfx-rs/wgpu/issues/7857
webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:default_bind_group_layouts_never_match,compute_pass:* // 75%, empty bind group layouts compatibility
webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:default_bind_group_layouts_never_match,render_pass:* // 75%, empty bind group layouts compatibility
webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:empty_bind_group_layouts_never_requires_empty_bind_groups,compute_pass:* // 17%, null bind groups, https://github.com/gfx-rs/wgpu/issues/4738
webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:empty_bind_group_layouts_never_requires_empty_bind_groups,render_pass:* // 17%, null bind groups, https://github.com/gfx-rs/wgpu/issues/4738
webgpu:api,validation,encoding,queries,resolveQuerySet:* // 93%, https://github.com/gfx-rs/wgpu/issues/7881
webgpu:api,validation,encoding,render_bundle:* // 81%, readonly flag normalization mismatch
webgpu:api,validation,getBindGroupLayout:* // 29%, rejects valid indices beyond defined layouts
webgpu:api,validation,image_copy,buffer_texture_copies:* // https://github.com/gfx-rs/wgpu/issues/7946
webgpu:api,validation,layout_shader_compat:pipeline_layout_shader_exact_match:* // 99%, storage texture read-write bindings not compatible with write-only shaders
webgpu:api,validation,non_filterable_texture:non_filterable_texture_with_filtering_sampler:* // 80%, depth textures with filtering samplers
+7 -6
View File
@@ -107,6 +107,11 @@ webgpu:api,validation,createBindGroupLayout:maximum_binding_limit:*
webgpu:api,validation,createBindGroupLayout:multisampled_validation:*
webgpu:api,validation,createBindGroupLayout:storage_texture,formats:*
webgpu:api,validation,createBindGroupLayout:storage_texture,layout_dimension:*
webgpu:api,validation,createPipelineLayout:bind_group_layouts,create_pipeline_with_null_bind_group_layouts:*
webgpu:api,validation,createPipelineLayout:bind_group_layouts,device_mismatch:*
webgpu:api,validation,createPipelineLayout:bind_group_layouts,null_bind_group_layouts:*
webgpu:api,validation,createPipelineLayout:bind_group_layouts,set_pipeline_with_null_bind_group_layouts:*
webgpu:api,validation,createPipelineLayout:number_of_bind_group_layouts_exceeds_the_maximum_value:*
webgpu:api,validation,createSampler:*
webgpu:api,validation,createTexture:*
webgpu:api,validation,createView:array_layers:*
@@ -169,15 +174,11 @@ webgpu:api,validation,encoding,encoder_open_state:non_pass_commands:*
// https://github.com/gfx-rs/wgpu/issues/7857
webgpu:api,validation,encoding,encoder_open_state:render_pass_commands:*
webgpu:api,validation,encoding,encoder_state:*
webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:bgl_binding_mismatch:*
webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:bgl_resource_type_mismatch:*
webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:bgl_visibility_mismatch:*
webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:bind_groups_and_pipeline_layout_mismatch:*
webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:buffer_binding,render_pipeline:*
webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:sampler_binding,render_pipeline:*
webgpu:api,validation,encoding,programmable,pipeline_bind_group_compat:*
webgpu:api,validation,encoding,queries,begin_end:occlusion_query,*
webgpu:api,validation,encoding,queries,general:occlusion_query,*
webgpu:api,validation,error_scope:*
webgpu:api,validation,getBindGroupLayout:*
webgpu:api,validation,image_copy,buffer_related:*
// image_copy depth/stencil failures on dx12: https://github.com/gfx-rs/wgpu/issues/8133
fails-if(dx12) webgpu:api,validation,image_copy,buffer_texture_copies:depth_stencil_format,copy_buffer_offset:format="depth24plus-stencil8";aspect="stencil-only";copyType="CopyB2T"
+5 -1
View File
@@ -379,7 +379,11 @@ impl GPUDevice {
let bind_group_layouts = descriptor
.bind_group_layouts
.into_iter()
.map(|bind_group_layout| bind_group_layout.id)
.map(|bind_group_layout| {
bind_group_layout
.into_option()
.map(|bind_group_layout| bind_group_layout.id)
})
.collect();
let wgpu_descriptor = wgpu_core::binding_model::PipelineLayoutDescriptor {
+2 -1
View File
@@ -2,6 +2,7 @@
use deno_core::cppgc::Ptr;
use deno_core::op2;
use deno_core::webidl::Nullable;
use deno_core::webidl::WebIdlInterfaceConverter;
use deno_core::GarbageCollected;
use deno_core::WebIDL;
@@ -58,5 +59,5 @@ pub(crate) struct GPUPipelineLayoutDescriptor {
pub label: String,
pub bind_group_layouts:
Vec<Ptr<super::bind_group_layout::GPUBindGroupLayout>>,
Vec<Nullable<Ptr<super::bind_group_layout::GPUBindGroupLayout>>>,
}
@@ -126,7 +126,7 @@ fn setup_pipeline(
) -> wgpu::ComputePipeline {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Compute Pipeline Layout"),
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
+1 -1
View File
@@ -106,7 +106,7 @@ impl crate::framework::Example for Example {
let compute_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("compute"),
bind_group_layouts: &[&compute_bind_group_layout],
bind_group_layouts: &[Some(&compute_bind_group_layout)],
immediate_size: 0,
});
+4 -1
View File
@@ -200,7 +200,10 @@ impl crate::framework::Example for Example {
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&global_bind_group_layout, &local_bind_group_layout],
bind_group_layouts: &[
Some(&global_bind_group_layout),
Some(&local_bind_group_layout),
],
immediate_size: 0,
});
@@ -194,7 +194,7 @@ impl crate::framework::Example for Example {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
let shader = device.create_shader_module(wgpu::include_wgsl!("upscale.wgsl"));
@@ -364,7 +364,7 @@ async fn execute(
// Create compute pipeline
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Cooperative Matrix Pipeline Layout"),
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
+1 -1
View File
@@ -157,7 +157,7 @@ impl crate::framework::Example for Example {
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
@@ -90,7 +90,7 @@ async fn execute(
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
let patient_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
@@ -99,7 +99,7 @@ async fn run() {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
@@ -111,7 +111,7 @@ impl MultiTargetRenderer {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&texture_bind_group_layout],
bind_group_layouts: &[Some(&texture_bind_group_layout)],
immediate_size: 0,
});
@@ -231,7 +231,7 @@ impl TargetRenderer {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&texture_bind_group_layout],
bind_group_layouts: &[Some(&texture_bind_group_layout)],
immediate_size: 0,
});
+1 -1
View File
@@ -185,7 +185,7 @@ impl crate::framework::Example for Example {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 16,
});
@@ -268,7 +268,7 @@ impl crate::framework::Example for Example {
let compute_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("pipeline layout for shader.wgsl"),
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
@@ -283,7 +283,7 @@ impl crate::framework::Example for Example {
let blit_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("pipeline layout for blit.wgsl"),
bind_group_layouts: &[&blit_bgl],
bind_group_layouts: &[Some(&blit_bgl)],
immediate_size: 0,
});
@@ -228,7 +228,7 @@ impl WgpuContext {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+2 -2
View File
@@ -465,7 +465,7 @@ impl crate::framework::Example for Example {
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("shadow"),
bind_group_layouts: &[&bind_group_layout, &local_bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout), Some(&local_bind_group_layout)],
immediate_size: 0,
});
@@ -581,7 +581,7 @@ impl crate::framework::Example for Example {
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("main"),
bind_group_layouts: &[&bind_group_layout, &local_bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout), Some(&local_bind_group_layout)],
immediate_size: 0,
});
+1 -1
View File
@@ -186,7 +186,7 @@ impl crate::framework::Example for Example {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
+1 -1
View File
@@ -91,7 +91,7 @@ impl<const SRGB: bool> crate::framework::Example for Example<SRGB> {
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
+1 -1
View File
@@ -89,7 +89,7 @@ async fn run(_path: Option<String>) {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+1 -1
View File
@@ -327,7 +327,7 @@ impl crate::framework::Example for Example {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("main"),
bind_group_layouts: &[&bind_group_layout, &uniform_bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout), Some(&uniform_bind_group_layout)],
immediate_size: 0,
});
+1 -1
View File
@@ -161,7 +161,7 @@ impl WgpuContext {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
// (4)
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
+2 -2
View File
@@ -427,14 +427,14 @@ impl crate::framework::Example for Example {
let water_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("water"),
bind_group_layouts: &[&water_bind_group_layout],
bind_group_layouts: &[Some(&water_bind_group_layout)],
immediate_size: 0,
});
let terrain_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("terrain"),
bind_group_layouts: &[&terrain_bind_group_layout],
bind_group_layouts: &[Some(&terrain_bind_group_layout)],
immediate_size: 0,
});
@@ -167,7 +167,7 @@ fn main() {
// The pipeline layout describes the bind groups that a pipeline expects
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
+2 -2
View File
@@ -214,11 +214,11 @@ impl Player {
.expect("invalid bind group layout");
}
Action::CreatePipelineLayout(id, desc) => {
let bind_group_layouts: Vec<Arc<wgc::binding_model::BindGroupLayout>> = desc
let bind_group_layouts: Vec<_> = desc
.bind_group_layouts
.to_vec()
.into_iter()
.map(|bgl_id| self.resolve_bind_group_layout_id(bgl_id))
.map(|bgl_id| bgl_id.map(|bgl_id| self.resolve_bind_group_layout_id(bgl_id)))
.collect();
let resolved_desc = wgc::binding_model::ResolvedPipelineLayoutDescriptor {
+1 -1
View File
@@ -37,7 +37,7 @@
CreatePipelineLayout(PointerId(0x10), (
label: Some("empty"),
bind_group_layouts: [
PointerId(0x10),
Some(PointerId(0x10)),
],
immediate_size: 0,
)),
@@ -120,7 +120,7 @@
CreatePipelineLayout(PointerId(0x10), (
label: None,
bind_group_layouts: [
PointerId(0x10),
Some(PointerId(0x10)),
],
immediate_size: 0,
)),
@@ -115,7 +115,7 @@
CreatePipelineLayout(PointerId(0x10), (
label: None,
bind_group_layouts: [
PointerId(0x10),
Some(PointerId(0x10)),
],
immediate_size: 0,
)),
+1 -1
View File
@@ -346,7 +346,7 @@ fn copy_via_compute(
let pll = device.create_pipeline_layout(&PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
+1 -1
View File
@@ -88,7 +88,7 @@ static BGRA8_UNORM_STORAGE: GpuTestConfiguration = GpuTestConfiguration::new()
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
@@ -80,7 +80,7 @@ async fn bgl_dedupe(ctx: TestingContext) {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bgl_1b],
bind_group_layouts: &[Some(&bgl_1b)],
immediate_size: 0,
});
@@ -144,7 +144,7 @@ fn bgl_dedupe_with_dropped_user_handle(ctx: TestingContext) {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bgl_1],
bind_group_layouts: &[Some(&bgl_1)],
immediate_size: 0,
});
+1 -1
View File
@@ -69,7 +69,7 @@ fn multiple_bindings_with_differing_sizes(ctx: TestingContext) {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("pipeline_layout"),
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
@@ -227,7 +227,7 @@ async fn binding_array_buffers(
.device
.create_pipeline_layout(&PipelineLayoutDescriptor {
label: Some("Pipeline Layout"),
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
@@ -180,7 +180,7 @@ async fn binding_array_sampled_textures(ctx: TestingContext, partially_bound: bo
.device
.create_pipeline_layout(&PipelineLayoutDescriptor {
label: Some("Pipeline Layout"),
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
@@ -213,7 +213,7 @@ async fn binding_array_samplers(ctx: TestingContext, partially_bound: bool) {
.device
.create_pipeline_layout(&PipelineLayoutDescriptor {
label: Some("Pipeline Layout"),
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
@@ -173,7 +173,7 @@ async fn binding_array_storage_textures(ctx: TestingContext, partially_bound: bo
.device
.create_pipeline_layout(&PipelineLayoutDescriptor {
label: Some("Pipeline Layout"),
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
+2 -2
View File
@@ -232,7 +232,7 @@ static MINIMUM_BUFFER_BINDING_SIZE_LAYOUT: GpuTestConfiguration = GpuTestConfigu
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
@@ -306,7 +306,7 @@ static MINIMUM_BUFFER_BINDING_SIZE_DISPATCH: GpuTestConfiguration = GpuTestConfi
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
@@ -322,7 +322,7 @@ fn resource_setup(ctx: &TestingContext) -> ResourceSetup {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("pipeline_layout"),
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
+1 -1
View File
@@ -439,7 +439,7 @@ static DEVICE_DESTROY_THEN_MORE: GpuTestConfiguration = GpuTestConfiguration::ne
ctx.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&invalid_bind_group_layout],
bind_group_layouts: &[Some(&invalid_bind_group_layout)],
immediate_size: 0,
});
@@ -206,7 +206,7 @@ impl TestResources {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 4,
});
+1 -1
View File
@@ -100,7 +100,7 @@ async fn test_format(
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
let shader = ctx.device.create_shader_module(desc);
+3 -3
View File
@@ -98,7 +98,7 @@ async fn partial_update_test(ctx: TestingContext) {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("pipeline_layout"),
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 32,
});
@@ -267,9 +267,9 @@ async fn render_pass_test(ctx: &TestingContext, use_render_bundle: bool) {
let render_pipeline_layout = ctx
.device
.create_pipeline_layout(&PipelineLayoutDescriptor {
bind_group_layouts: &[&bind_group_layout],
label: None,
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 8 * size_of::<u32>() as u32,
..Default::default()
});
let pipeline = ctx
+1 -1
View File
@@ -91,7 +91,7 @@ async fn draw_test_with_reports(
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
+2 -2
View File
@@ -177,7 +177,7 @@ impl TestResources {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
@@ -341,7 +341,7 @@ async fn d3d12_restrict_dynamic_buffers(ctx: TestingContext) {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
+4 -4
View File
@@ -92,9 +92,9 @@ static COMPUTE_PIPELINE_DEFAULT_LAYOUT_BAD_BGL_INDEX: GpuTestConfiguration =
cache: None,
});
pipeline.get_bind_group_layout(0);
pipeline.get_bind_group_layout(u32::MAX);
},
Some("Invalid group index 0"),
Some("Bind group layout index 4294967295 is greater than the device's configured `max_bind_groups` limit"),
);
});
@@ -178,9 +178,9 @@ static RENDER_PIPELINE_DEFAULT_LAYOUT_BAD_BGL_INDEX: GpuTestConfiguration =
cache: None,
});
pipeline.get_bind_group_layout(0);
pipeline.get_bind_group_layout(u32::MAX);
},
Some("Invalid group index 0"),
Some("Bind group layout index 4294967295 is greater than the device's configured `max_bind_groups` limit"),
);
});
+1 -1
View File
@@ -97,7 +97,7 @@ async fn pipeline_cache_test(ctx: TestingContext) {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("pipeline_layout"),
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
@@ -92,7 +92,7 @@ async fn multi_stage_data_binding_test(ctx: TestingContext) {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("pll"),
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 16,
});
@@ -463,7 +463,7 @@ fn resource_setup(ctx: &TestingContext) -> ResourceSetup {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("pipeline_layout"),
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
+2 -2
View File
@@ -326,9 +326,9 @@ fn sampler_bind_group(ctx: TestingContext, group_type: GroupType) {
}],
});
let mut bgl_references: Vec<_> = bind_group_layouts.iter().collect();
let mut bgl_references: Vec<_> = bind_group_layouts.iter().map(Some).collect();
bgl_references.push(&output_bgl);
bgl_references.push(Some(&output_bgl));
let pipeline_layout = ctx
.device
+1 -1
View File
@@ -279,7 +279,7 @@ async fn shader_input_output_test(
.device
.create_pipeline_layout(&PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: match storage_type {
InputStorageType::Immediate => MAX_BUFFER_SIZE as u32,
_ => 0,
@@ -69,7 +69,7 @@ static ZERO_INIT_WORKGROUP_MEMORY: GpuTestConfiguration = GpuTestConfiguration::
.device
.create_pipeline_layout(&PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
@@ -68,7 +68,7 @@ static SUBGROUP_OPERATIONS: GpuTestConfiguration = GpuTestConfiguration::new()
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("main"),
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
+1 -1
View File
@@ -253,7 +253,7 @@ async fn vertex_formats_common(ctx: TestingContext, tests: &[Test<'_>]) {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
+1 -1
View File
@@ -233,7 +233,7 @@ async fn vertex_index_common(ctx: TestingContext) {
.device
.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
+80 -21
View File
@@ -690,7 +690,7 @@ pub struct BindGroupLayoutDescriptor<'a> {
/// Used by [`BindGroupLayout`]. It indicates whether the BGL must be
/// used with a specific pipeline. This constraint only happens when
/// the BGLs have been derived from a pipeline without a layout.
#[derive(Debug)]
#[derive(Clone, Debug)]
pub(crate) enum ExclusivePipeline {
None,
Render(Weak<RenderPipeline>),
@@ -719,10 +719,17 @@ impl fmt::Display for ExclusivePipeline {
}
}
#[derive(Debug)]
pub enum RawBindGroupLayout {
Owning(ManuallyDrop<Box<dyn hal::DynBindGroupLayout>>),
/// The empty BGL was created by the device and will be destroyed by the device.
RefDeviceEmptyBGL,
}
/// Bind group layout.
#[derive(Debug)]
pub struct BindGroupLayout {
pub(crate) raw: ManuallyDrop<Box<dyn hal::DynBindGroupLayout>>,
pub(crate) raw: RawBindGroupLayout,
pub(crate) device: Arc<Device>,
pub(crate) entries: bgl::EntryMap,
/// It is very important that we know if the bind group comes from the BGL pool.
@@ -744,10 +751,15 @@ impl Drop for BindGroupLayout {
if matches!(self.origin, bgl::Origin::Pool) {
self.device.bgl_pool.remove(&self.entries);
}
// SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
let raw = unsafe { ManuallyDrop::take(&mut self.raw) };
unsafe {
self.device.raw().destroy_bind_group_layout(raw);
match self.raw {
RawBindGroupLayout::Owning(ref mut raw) => {
// SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
let raw = unsafe { ManuallyDrop::take(raw) };
unsafe {
self.device.raw().destroy_bind_group_layout(raw);
}
}
RawBindGroupLayout::RefDeviceEmptyBGL => {}
}
}
}
@@ -759,7 +771,24 @@ crate::impl_storage_item!(BindGroupLayout);
impl BindGroupLayout {
pub(crate) fn raw(&self) -> &dyn hal::DynBindGroupLayout {
self.raw.as_ref()
match &self.raw {
RawBindGroupLayout::Owning(raw) => raw.as_ref(),
RawBindGroupLayout::RefDeviceEmptyBGL => self.device.empty_bgl.as_ref(),
}
}
fn empty(device: &Arc<Device>) -> Arc<Self> {
let exclusive_pipeline = crate::OnceCellOrLock::new();
exclusive_pipeline.set(ExclusivePipeline::None).unwrap();
Arc::new(Self {
raw: RawBindGroupLayout::RefDeviceEmptyBGL,
device: device.clone(),
entries: bgl::EntryMap::default(),
origin: bgl::Origin::Derived,
exclusive_pipeline,
binding_count_validator: BindingTypeMaxCountValidator::default(),
label: String::new(),
})
}
}
@@ -785,6 +814,8 @@ pub enum CreatePipelineLayoutError {
TooManyGroups { actual: usize, max: usize },
#[error(transparent)]
InvalidResource(#[from] InvalidResourceError),
#[error("Bind group layout at index {index} has an exclusive pipeline: {pipeline}")]
BglHasExclusivePipeline { index: usize, pipeline: String },
}
impl WebGpuError for CreatePipelineLayoutError {
@@ -796,7 +827,8 @@ impl WebGpuError for CreatePipelineLayoutError {
Self::TooManyBindings(e) => e,
Self::MisalignedImmediateSize { .. }
| Self::ImmediateRangeTooLarge { .. }
| Self::TooManyGroups { .. } => return ErrorType::Validation,
| Self::TooManyGroups { .. }
| Self::BglHasExclusivePipeline { .. } => return ErrorType::Validation,
};
e.webgpu_error_type()
}
@@ -832,8 +864,8 @@ impl WebGpuError for ImmediateUploadError {
#[cfg_attr(feature = "serde", serde(bound = "BGL: Serialize"))]
pub struct PipelineLayoutDescriptor<'a, BGL = BindGroupLayoutId>
where
[BGL]: ToOwned,
<[BGL] as ToOwned>::Owned: fmt::Debug,
[Option<BGL>]: ToOwned,
<[Option<BGL>] as ToOwned>::Owned: fmt::Debug,
{
/// Debug label of the pipeline layout.
///
@@ -843,9 +875,9 @@ where
/// "set = 0", second entry will provide all the bindings for "set = 1" etc.
#[cfg_attr(
feature = "serde",
serde(bound(deserialize = "<[BGL] as ToOwned>::Owned: Deserialize<'de>"))
serde(bound(deserialize = "<[Option<BGL>] as ToOwned>::Owned: Deserialize<'de>"))
)]
pub bind_group_layouts: Cow<'a, [BGL]>,
pub bind_group_layouts: Cow<'a, [Option<BGL>]>,
/// The number of bytes of immediate data that are allocated for use
/// in the shader. The `var<immediate>`s in the shader attached to
/// this pipeline must be equal or smaller than this size.
@@ -864,7 +896,7 @@ pub struct PipelineLayout {
pub(crate) device: Arc<Device>,
/// The `label` from the descriptor used to create the resource.
pub(crate) label: String,
pub(crate) bind_group_layouts: ArrayVec<Arc<BindGroupLayout>, { hal::MAX_BIND_GROUPS }>,
pub(crate) bind_group_layouts: ArrayVec<Option<Arc<BindGroupLayout>>, { hal::MAX_BIND_GROUPS }>,
pub(crate) immediate_size: u32,
}
@@ -884,11 +916,33 @@ impl PipelineLayout {
self.raw.as_ref()
}
pub(crate) fn get_binding_maps(&self) -> ArrayVec<&bgl::EntryMap, { hal::MAX_BIND_GROUPS }> {
self.bind_group_layouts
.iter()
.map(|bgl| &bgl.entries)
.collect()
pub fn get_bind_group_layout(
self: &Arc<Self>,
index: u32,
) -> Result<Arc<BindGroupLayout>, GetBindGroupLayoutError> {
let max_bind_groups = self.device.limits.max_bind_groups;
if index >= max_bind_groups {
return Err(GetBindGroupLayoutError::IndexOutOfRange {
index,
max: max_bind_groups,
});
}
Ok(self
.bind_group_layouts
.get(index as usize)
.cloned()
.flatten()
.unwrap_or_else(|| BindGroupLayout::empty(&self.device)))
}
pub(crate) fn get_bgl_entry(
&self,
group: u32,
binding: u32,
) -> Option<&wgt::BindGroupLayoutEntry> {
let bgl = self.bind_group_layouts.get(group as usize)?;
let bgl = bgl.as_ref()?;
bgl.entries.get(binding)
}
/// Validate immediates match up with expected ranges.
@@ -993,6 +1047,11 @@ pub type ResolvedBindingResource<'a> = BindingResource<
#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum BindError {
#[error(
"Dynamic offsets not expected with null bind group at index {group}. However {actual} dynamic offset{s1} were provided.",
s1 = if *.actual >= 2 { "s" } else { "" },
)]
DynamicOffsetCountNotZero { group: u32, actual: usize },
#[error(
"{bind_group} {group} expects {expected} dynamic offset{s0}. However {actual} dynamic offset{s1} were provided.",
s0 = if *.expected >= 2 { "s" } else { "" },
@@ -1201,8 +1260,8 @@ crate::impl_trackable!(BindGroup);
#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum GetBindGroupLayoutError {
#[error("Invalid group index {0}")]
InvalidGroupIndex(u32),
#[error("Bind group layout index {index} is greater than the device's configured `max_bind_groups` limit {max}")]
IndexOutOfRange { index: u32, max: u32 },
#[error(transparent)]
InvalidResource(#[from] InvalidResourceError),
}
@@ -1210,7 +1269,7 @@ pub enum GetBindGroupLayoutError {
impl WebGpuError for GetBindGroupLayoutError {
fn webgpu_error_type(&self) -> ErrorType {
match self {
Self::InvalidGroupIndex(_) => ErrorType::Validation,
Self::IndexOutOfRange { .. } => ErrorType::Validation,
Self::InvalidResource(e) => e.webgpu_error_type(),
}
}
+81 -62
View File
@@ -1,5 +1,3 @@
use core::{iter::zip, ops::Range};
use alloc::{boxed::Box, sync::Arc, vec::Vec};
use thiserror::Error;
@@ -16,9 +14,8 @@ mod compat {
sync::{Arc, Weak},
vec::Vec,
};
use core::{num::NonZeroU32, ops::Range};
use core::num::NonZeroU32;
use arrayvec::ArrayVec;
use thiserror::Error;
use wgt::{BindingType, ShaderStages};
@@ -44,12 +41,13 @@ mod compat {
}
impl Entry {
fn empty() -> Self {
const fn empty() -> Self {
Self {
assigned: None,
expected: None,
}
}
fn is_active(&self) -> bool {
self.assigned.is_some() && self.expected.is_some()
}
@@ -62,14 +60,10 @@ mod compat {
false
}
} else {
true
false
}
}
fn is_incompatible(&self) -> bool {
self.expected.is_none() || !self.is_valid()
}
fn check(&self) -> Result<(), Error> {
if let Some(expected_bgl) = self.expected.as_ref() {
if let Some(assigned_bgl) = self.assigned.as_ref() {
@@ -191,64 +185,69 @@ mod compat {
}
}
#[derive(Debug, Default)]
#[derive(Debug)]
pub(super) struct BoundBindGroupLayouts {
entries: ArrayVec<Entry, { hal::MAX_BIND_GROUPS }>,
entries: [Entry; hal::MAX_BIND_GROUPS],
rebind_start: usize,
}
impl BoundBindGroupLayouts {
pub fn new() -> Self {
Self {
entries: (0..hal::MAX_BIND_GROUPS).map(|_| Entry::empty()).collect(),
entries: [const { Entry::empty() }; hal::MAX_BIND_GROUPS],
rebind_start: 0,
}
}
pub fn num_valid_entries(&self) -> usize {
// find first incompatible entry
self.entries
.iter()
.position(|e| e.is_incompatible())
.unwrap_or(self.entries.len())
}
/// Get the range of entries that needs to be rebound, and clears it.
pub fn take_rebind_range(&mut self) -> Range<usize> {
let end = self.num_valid_entries();
/// Takes the start index of the bind group range to be rebound, and clears it.
pub fn take_rebind_start_index(&mut self) -> usize {
let start = self.rebind_start;
self.rebind_start = end;
start..end.max(start)
self.rebind_start = self.entries.len();
start
}
pub fn update_start_index(&mut self, start_index: usize) {
pub fn update_rebind_start_index(&mut self, start_index: usize) {
self.rebind_start = self.rebind_start.min(start_index);
}
pub fn update_expectations(&mut self, expectations: &[Arc<BindGroupLayout>]) {
let start_index = self
pub fn update_expectations(&mut self, expectations: &[Option<Arc<BindGroupLayout>>]) {
let mut rebind_start_index = None;
for (i, (e, new_expected_bgl)) in self
.entries
.iter()
.zip(expectations)
.position(|(e, expect)| {
e.expected.is_none() || !e.expected.as_ref().unwrap().is_equal(expect)
})
.unwrap_or(expectations.len());
for (e, expect) in self.entries[start_index..]
.iter_mut()
.zip(expectations[start_index..].iter())
.zip(expectations.iter().chain(core::iter::repeat(&None)))
.enumerate()
{
e.expected = Some(expect.clone());
let (must_set, must_rebind) = match (&mut e.expected, new_expected_bgl) {
(None, None) => (false, false),
(None, Some(_)) => (true, true),
(Some(_), None) => (true, false),
(Some(old_expected_bgl), Some(new_expected_bgl)) => {
let is_different = !old_expected_bgl.is_equal(new_expected_bgl);
(is_different, is_different)
}
};
if must_set {
e.expected = new_expected_bgl.clone();
}
if must_rebind && rebind_start_index.is_none() {
rebind_start_index = Some(i);
}
}
for e in self.entries[expectations.len()..].iter_mut() {
e.expected = None;
if let Some(rebind_start_index) = rebind_start_index {
self.update_rebind_start_index(rebind_start_index);
}
self.update_start_index(start_index);
}
pub fn assign(&mut self, index: usize, value: Arc<BindGroupLayout>) {
self.entries[index].assigned = Some(value);
self.update_start_index(index);
self.update_rebind_start_index(index);
}
pub fn clear(&mut self, index: usize) {
self.entries[index].assigned = None;
}
pub fn list_active(&self) -> impl Iterator<Item = usize> + '_ {
@@ -258,6 +257,13 @@ mod compat {
.filter_map(|(i, e)| if e.is_active() { Some(i) } else { None })
}
pub fn list_valid(&self) -> impl Iterator<Item = usize> + '_ {
self.entries
.iter()
.enumerate()
.filter_map(|(i, e)| if e.is_valid() { Some(i) } else { None })
}
#[allow(clippy::result_large_err)]
pub fn get_invalid(&self) -> Result<(), (usize, Error)> {
for (index, entry) in self.entries.iter().enumerate() {
@@ -295,13 +301,13 @@ struct LateBufferBinding {
}
#[derive(Debug, Default)]
pub(super) struct EntryPayload {
pub(super) group: Option<Arc<BindGroup>>,
pub(super) dynamic_offsets: Vec<wgt::DynamicOffset>,
struct EntryPayload {
group: Option<Arc<BindGroup>>,
dynamic_offsets: Vec<wgt::DynamicOffset>,
late_buffer_bindings: Vec<LateBufferBinding>,
/// Since `LateBufferBinding` may contain information about the bindings
/// not used by the pipeline, we need to know when to stop validating.
pub(super) late_bindings_effective_count: usize,
late_bindings_effective_count: usize,
}
impl EntryPayload {
@@ -313,7 +319,7 @@ impl EntryPayload {
}
}
#[derive(Debug, Default)]
#[derive(Debug)]
pub(super) struct Binder {
pub(super) pipeline_layout: Option<Arc<PipelineLayout>>,
manager: compat::BoundBindGroupLayouts,
@@ -383,7 +389,7 @@ impl Binder {
if let Some(old) = old {
// root constants are the base compatibility property
if old.immediate_size != new.immediate_size {
self.manager.update_start_index(0);
self.manager.update_rebind_start_index(0);
}
}
@@ -431,31 +437,44 @@ impl Binder {
self.manager.assign(index, bind_group.layout.clone());
}
/// Get the range of entries that needs to be rebound, and clears it.
pub(super) fn take_rebind_range(&mut self) -> Range<usize> {
self.manager.take_rebind_range()
pub(super) fn clear_group(&mut self, index: usize) {
self.payloads[index].reset();
self.manager.clear(index);
}
pub(super) fn entries(
/// Takes the start index of the bind group range to be rebound, and clears it.
pub(super) fn take_rebind_start_index(&mut self) -> usize {
self.manager.take_rebind_start_index()
}
pub(super) fn list_valid_with_start(
&self,
range: Range<usize>,
) -> impl ExactSizeIterator<Item = (usize, &'_ EntryPayload)> + Clone + '_ {
let payloads = &self.payloads[range.clone()];
zip(range, payloads)
start: usize,
) -> impl Iterator<Item = (usize, &Arc<BindGroup>, &[wgt::DynamicOffset])> + '_ {
let payloads = &self.payloads;
self.manager
.list_valid()
.filter(move |i| *i >= start)
.map(move |index| {
(
index,
payloads[index].group.as_ref().unwrap(),
payloads[index].dynamic_offsets.as_slice(),
)
})
}
pub(super) fn list_active<'a>(&'a self) -> impl Iterator<Item = &'a Arc<BindGroup>> + 'a {
pub(super) fn list_active(&self) -> impl Iterator<Item = &Arc<BindGroup>> + '_ {
let payloads = &self.payloads;
self.manager
.list_active()
.map(move |index| payloads[index].group.as_ref().unwrap())
}
pub(super) fn list_valid<'a>(&'a self) -> impl Iterator<Item = (usize, &'a EntryPayload)> + 'a {
self.payloads
.iter()
.take(self.manager.num_valid_entries())
.enumerate()
pub(super) fn list_valid(
&self,
) -> impl Iterator<Item = (usize, &Arc<BindGroup>, &[wgt::DynamicOffset])> + '_ {
self.list_valid_with_start(0)
}
pub(super) fn check_compatibility<T: Labeled>(
+40 -41
View File
@@ -522,17 +522,6 @@ fn set_bind_group(
num_dynamic_offsets: usize,
bind_group_id: Option<id::Id<id::markers::BindGroup>>,
) -> Result<(), RenderBundleErrorInner> {
if bind_group_id.is_none() {
// TODO: do appropriate cleanup for null bind_group.
return Ok(());
}
let bind_group_id = bind_group_id.unwrap();
let bind_group = bind_group_guard.get(bind_group_id).get()?;
bind_group.same_device(&state.device)?;
let max_bind_groups = state.device.limits.max_bind_groups;
if index >= max_bind_groups {
return Err(
@@ -549,14 +538,31 @@ fn set_bind_group(
state.next_dynamic_offset = offsets_range.end;
let offsets = &dynamic_offsets[offsets_range.clone()];
bind_group.validate_dynamic_bindings(index, offsets)?;
let bind_group = bind_group_id.map(|id| bind_group_guard.get(id));
unsafe { state.trackers.merge_bind_group(&bind_group.used)? };
let bind_group = state.trackers.bind_groups.insert_single(bind_group);
if let Some(bind_group) = bind_group {
let bind_group = bind_group.get()?;
bind_group.same_device(&state.device)?;
bind_group.validate_dynamic_bindings(index, offsets)?;
state
.binder
.assign_group(index as usize, bind_group, offsets);
unsafe { state.trackers.merge_bind_group(&bind_group.used)? };
let bind_group = state.trackers.bind_groups.insert_single(bind_group);
state
.binder
.assign_group(index as usize, bind_group, offsets);
} else {
if !offsets.is_empty() {
return Err(RenderBundleErrorInner::Bind(
BindError::DynamicOffsetCountNotZero {
group: index,
actual: offsets.len(),
},
));
}
state.binder.clear_group(index as usize);
}
Ok(())
}
@@ -977,17 +983,12 @@ impl RenderBundle {
num_dynamic_offsets,
bind_group,
} => {
let mut bg = None;
if bind_group.is_some() {
let bind_group = bind_group.as_ref().unwrap();
let raw_bg = bind_group.try_raw(snatch_guard)?;
bg = Some(raw_bg);
}
let raw_bg = bind_group.as_ref().unwrap().try_raw(snatch_guard)?;
unsafe {
raw.set_bind_group(
pipeline_layout.as_ref().unwrap().raw(),
*index,
bg,
raw_bg,
&offsets[..*num_dynamic_offsets],
)
};
@@ -1435,26 +1436,24 @@ impl State {
///
/// This should be further deduplicated with similar code on render/compute passes.
fn flush_bindings(&mut self) {
let range = self.binder.take_rebind_range();
let entries = self.binder.entries(range);
let start = self.binder.take_rebind_start_index();
let entries = self.binder.list_valid_with_start(start);
self.commands.extend(entries.map(|(i, entry)| {
let bind_group = entry.group.as_ref().unwrap();
self.commands
.extend(entries.map(|(i, bind_group, dynamic_offsets)| {
self.buffer_memory_init_actions
.extend_from_slice(&bind_group.used_buffer_ranges);
self.texture_memory_init_actions
.extend_from_slice(&bind_group.used_texture_ranges);
self.buffer_memory_init_actions
.extend_from_slice(&bind_group.used_buffer_ranges);
self.texture_memory_init_actions
.extend_from_slice(&bind_group.used_texture_ranges);
self.flat_dynamic_offsets.extend_from_slice(dynamic_offsets);
self.flat_dynamic_offsets
.extend_from_slice(&entry.dynamic_offsets);
ArcRenderCommand::SetBindGroup {
index: i.try_into().unwrap(),
bind_group: Some(bind_group.clone()),
num_dynamic_offsets: entry.dynamic_offsets.len(),
}
}));
ArcRenderCommand::SetBindGroup {
index: i.try_into().unwrap(),
bind_group: Some(bind_group.clone()),
num_dynamic_offsets: dynamic_offsets.len(),
}
}));
}
fn vertex_buffer_sizes(&self) -> impl Iterator<Item = Option<wgt::BufferAddress>> + '_ {
+10 -13
View File
@@ -933,7 +933,7 @@ fn dispatch_indirect(
state.pass.base.raw_encoder.set_bind_group(
params.pipeline_layout,
0,
Some(params.dst_bind_group),
params.dst_bind_group,
&[],
);
}
@@ -941,14 +941,12 @@ fn dispatch_indirect(
state.pass.base.raw_encoder.set_bind_group(
params.pipeline_layout,
1,
Some(
buffer
.indirect_validation_bind_groups
.get(state.pass.base.snatch_guard)
.unwrap()
.dispatch
.as_ref(),
),
buffer
.indirect_validation_bind_groups
.get(state.pass.base.snatch_guard)
.unwrap()
.dispatch
.as_ref(),
&[params.aligned_offset as u32],
);
}
@@ -1007,15 +1005,14 @@ fn dispatch_indirect(
}
}
for (i, e) in state.pass.binder.list_valid() {
let group = e.group.as_ref().unwrap();
for (i, group, dynamic_offsets) in state.pass.binder.list_valid() {
let raw_bg = group.try_raw(state.pass.base.snatch_guard)?;
unsafe {
state.pass.base.raw_encoder.set_bind_group(
pipeline.layout.raw(),
i as u32,
Some(raw_bg),
&e.dynamic_offsets,
raw_bg,
dynamic_offsets,
);
}
}
+44 -48
View File
@@ -20,7 +20,7 @@ use wgt::DynamicOffset;
#[derive(Clone, Debug, Error)]
#[error(
"Bind group index {index} is greater than the device's requested `max_bind_group` limit {max}"
"Bind group index {index} is greater than the device's configured `max_bind_groups` limit {max}"
)]
pub struct BindGroupIndexOutOfRange {
pub index: u32,
@@ -97,35 +97,42 @@ where
);
state.dynamic_offset_count += num_dynamic_offsets;
let Some(bind_group) = bind_group else {
// TODO: Handle bind_group None.
return Ok(());
};
if let Some(bind_group) = bind_group {
// Add the bind group to the tracker. This is done for both compute and
// render passes, and is used to fail submission of the command buffer if
// any resource in any of the bind groups has been destroyed, whether or
// not the bind group is actually used by the pipeline.
let bind_group = state.base.tracker.bind_groups.insert_single(bind_group);
// Add the bind group to the tracker. This is done for both compute and
// render passes, and is used to fail submission of the command buffer if
// any resource in any of the bind groups has been destroyed, whether or
// not the bind group is actually used by the pipeline.
let bind_group = state.base.tracker.bind_groups.insert_single(bind_group);
bind_group.same_device(device)?;
bind_group.same_device(device)?;
bind_group.validate_dynamic_bindings(index, &state.temp_offsets)?;
bind_group.validate_dynamic_bindings(index, &state.temp_offsets)?;
if merge_bind_groups {
// Merge the bind group's resources into the tracker. We only do this
// for render passes. For compute passes it is done per dispatch in
// [`flush_bindings`].
unsafe {
state.scope.merge_bind_group(&bind_group.used)?;
if merge_bind_groups {
// Merge the bind group's resources into the tracker. We only do this
// for render passes. For compute passes it is done per dispatch in
// [`flush_bindings`].
unsafe {
state.scope.merge_bind_group(&bind_group.used)?;
}
}
}
//Note: stateless trackers are not merged: the lifetime reference
// is held to the bind group itself.
//Note: stateless trackers are not merged: the lifetime reference
// is held to the bind group itself.
state
.binder
.assign_group(index as usize, bind_group, &state.temp_offsets);
state
.binder
.assign_group(index as usize, bind_group, &state.temp_offsets);
} else {
if !state.temp_offsets.is_empty() {
return Err(BindError::DynamicOffsetCountNotZero {
group: index,
actual: state.temp_offsets.len(),
}
.into());
}
state.binder.clear_group(index as usize);
};
Ok(())
}
@@ -135,16 +142,11 @@ where
/// See the compute pass version of `State::flush_bindings` for an explanation
/// of some differences in handling the two types of passes.
pub(super) fn flush_bindings_helper(state: &mut PassState) -> Result<(), DestroyedResourceError> {
let range = state.binder.take_rebind_range();
if range.is_empty() {
return Ok(());
}
let entries = state.binder.entries(range);
for (_, entry) in entries.clone() {
let bind_group = entry.group.as_ref().unwrap();
let start = state.binder.take_rebind_start_index();
let entries = state.binder.list_valid_with_start(start);
let pipeline_layout = state.binder.pipeline_layout.as_ref().unwrap();
for (i, bind_group, dynamic_offsets) in entries {
state.base.buffer_memory_init_actions.extend(
bind_group.used_buffer_ranges.iter().filter_map(|action| {
action
@@ -170,21 +172,15 @@ pub(super) fn flush_bindings_helper(state: &mut PassState) -> Result<(), Destroy
.map(|tlas| crate::ray_tracing::AsAction::UseTlas(tlas.clone()));
state.base.as_actions.extend(used_resource);
}
if let Some(pipeline_layout) = state.binder.pipeline_layout.as_ref() {
for (i, e) in entries {
if let Some(group) = e.group.as_ref() {
let raw_bg = group.try_raw(state.base.snatch_guard)?;
unsafe {
state.base.raw_encoder.set_bind_group(
pipeline_layout.raw(),
i as u32,
Some(raw_bg),
&e.dynamic_offsets,
);
}
}
let raw_bg = bind_group.try_raw(state.base.snatch_guard)?;
unsafe {
state.base.raw_encoder.set_bind_group(
pipeline_layout.raw(),
i as u32,
raw_bg,
dynamic_offsets,
);
}
}
+4 -1
View File
@@ -732,7 +732,10 @@ impl Global {
let bind_group_layouts_guard = hub.bind_group_layouts.read();
desc.bind_group_layouts
.iter()
.map(|bgl_id| bind_group_layouts_guard.get(*bgl_id).get())
.map(|bgl_id| match bgl_id {
Some(bgl_id) => bind_group_layouts_guard.get(*bgl_id).get().map(Some),
None => Ok(None),
})
.collect::<Result<Vec<_>, _>>()
};
+80 -36
View File
@@ -209,6 +209,7 @@ pub struct Device {
pub(crate) adapter: Arc<Adapter>,
pub(crate) queue: OnceCellOrLock<Weak<Queue>>,
pub(crate) zero_buffer: ManuallyDrop<Box<dyn hal::DynBuffer>>,
pub(crate) empty_bgl: ManuallyDrop<Box<dyn hal::DynBindGroupLayout>>,
/// The `label` from the descriptor used to create the resource.
label: String,
@@ -298,6 +299,8 @@ impl Drop for Device {
// SAFETY: We are in the Drop impl and we don't use self.zero_buffer anymore after this point.
let zero_buffer = unsafe { ManuallyDrop::take(&mut self.zero_buffer) };
// SAFETY: We are in the Drop impl and we don't use self.empty_bgl anymore after this point.
let empty_bgl = unsafe { ManuallyDrop::take(&mut self.empty_bgl) };
// SAFETY: We are in the Drop impl and we don't use
// self.default_external_texture_params_buffer anymore after this point.
let default_external_texture_params_buffer =
@@ -312,6 +315,7 @@ impl Drop for Device {
}
unsafe {
self.raw.destroy_buffer(zero_buffer);
self.raw.destroy_bind_group_layout(empty_bgl);
self.raw
.destroy_buffer(default_external_texture_params_buffer);
self.raw.destroy_fence(fence);
@@ -453,6 +457,15 @@ impl Device {
}
.map_err(DeviceError::from_hal)?;
let empty_bgl = unsafe {
raw_device.create_bind_group_layout(&hal::BindGroupLayoutDescriptor {
label: None,
flags: hal::BindGroupLayoutFlags::empty(),
entries: &[],
})
}
.map_err(DeviceError::from_hal)?;
let default_external_texture_params_buffer = unsafe {
raw_device.create_buffer(&hal::BufferDescriptor {
label: hal_label(
@@ -495,6 +508,7 @@ impl Device {
adapter: adapter.clone(),
queue: OnceCellOrLock::new(),
zero_buffer: ManuallyDrop::new(zero_buffer),
empty_bgl: ManuallyDrop::new(empty_bgl),
default_external_texture_params_buffer: ManuallyDrop::new(
default_external_texture_params_buffer,
),
@@ -2471,8 +2485,12 @@ impl Device {
.bind_group_layouts
.iter()
.enumerate()
.map(|(group_index, bgl)| pipeline::LateSizedBufferGroup {
shader_sizes: bgl
.map(|(group_index, bgl)| {
let Some(bgl) = bgl else {
return pipeline::LateSizedBufferGroup::default();
};
let shader_sizes = bgl
.entries
.values()
.filter_map(|entry| match entry.ty {
@@ -2490,7 +2508,8 @@ impl Device {
}
_ => None,
})
.collect(),
.collect();
pipeline::LateSizedBufferGroup { shader_sizes }
})
.collect()
}
@@ -2518,9 +2537,7 @@ impl Device {
}
}
/// Internal function exposed for use by `player` crate only.
#[doc(hidden)]
pub fn create_bind_group_layout_internal(
fn create_bind_group_layout_internal(
self: &Arc<Self>,
label: &crate::Label,
entry_map: bgl::EntryMap,
@@ -2775,7 +2792,7 @@ impl Device {
.map_err(|e| self.handle_hal_error(e))?;
let bgl = BindGroupLayout {
raw: ManuallyDrop::new(raw),
raw: binding_model::RawBindGroupLayout::Owning(ManuallyDrop::new(raw)),
device: self.clone(),
entries: entry_map,
origin,
@@ -3598,6 +3615,14 @@ impl Device {
pub fn create_pipeline_layout(
self: &Arc<Self>,
desc: &binding_model::ResolvedPipelineLayoutDescriptor,
) -> Result<Arc<binding_model::PipelineLayout>, binding_model::CreatePipelineLayoutError> {
self.create_pipeline_layout_impl(desc, false)
}
fn create_pipeline_layout_impl(
self: &Arc<Self>,
desc: &binding_model::ResolvedPipelineLayoutDescriptor,
ignore_exclusive_pipeline_check: bool,
) -> Result<Arc<binding_model::PipelineLayout>, binding_model::CreatePipelineLayoutError> {
use crate::binding_model::CreatePipelineLayoutError as Error;
@@ -3632,8 +3657,23 @@ impl Device {
let mut count_validator = binding_model::BindingTypeMaxCountValidator::default();
for bgl in desc.bind_group_layouts.iter() {
for (index, bgl) in desc.bind_group_layouts.iter().enumerate() {
let Some(bgl) = bgl else {
continue;
};
bgl.same_device(self)?;
if !ignore_exclusive_pipeline_check {
let exclusive_pipeline = bgl.exclusive_pipeline.get().unwrap();
if !matches!(exclusive_pipeline, binding_model::ExclusivePipeline::None) {
return Err(Error::BglHasExclusivePipeline {
index,
pipeline: alloc::format!("{exclusive_pipeline}"),
});
}
}
count_validator.merge(&bgl.binding_count_validator);
}
@@ -3641,16 +3681,18 @@ impl Device {
.validate(&self.limits)
.map_err(Error::TooManyBindings)?;
let bind_group_layouts = desc
.bind_group_layouts
.iter()
.cloned()
let get_bgl_iter = || {
desc.bind_group_layouts
.iter()
.map(|bgl| bgl.as_ref().filter(|bgl| !bgl.entries.is_empty()))
};
let bind_group_layouts = get_bgl_iter()
.map(|bgl| bgl.cloned())
.collect::<ArrayVec<_, { hal::MAX_BIND_GROUPS }>>();
let raw_bind_group_layouts = desc
.bind_group_layouts
.iter()
.map(|bgl| bgl.raw())
let raw_bind_group_layouts = get_bgl_iter()
.map(|bgl| bgl.map(|bgl| bgl.raw()))
.collect::<ArrayVec<_, { hal::MAX_BIND_GROUPS }>>();
let additional_flags = if self.indirect_validation.is_some() {
@@ -3686,7 +3728,7 @@ impl Device {
Ok(layout)
}
pub(crate) fn derive_pipeline_layout(
fn create_derived_pipeline_layout(
self: &Arc<Self>,
mut derived_group_layouts: Box<ArrayVec<bgl::EntryMap, { hal::MAX_BIND_GROUPS }>>,
) -> Result<Arc<binding_model::PipelineLayout>, pipeline::ImplicitLayoutError> {
@@ -3702,9 +3744,13 @@ impl Device {
let bind_group_layouts = derived_group_layouts
.into_iter()
.map(|mut bgl_entry_map| {
if bgl_entry_map.is_empty() {
return Ok(None);
}
bgl_entry_map.sort();
match unique_bind_group_layouts.entry(bgl_entry_map) {
hashbrown::hash_map::Entry::Occupied(v) => Ok(Arc::clone(v.get())),
hashbrown::hash_map::Entry::Occupied(v) => Ok(Some(Arc::clone(v.get()))),
hashbrown::hash_map::Entry::Vacant(e) => {
match self.create_bind_group_layout_internal(
&None,
@@ -3713,7 +3759,7 @@ impl Device {
) {
Ok(bgl) => {
e.insert(bgl.clone());
Ok(bgl)
Ok(Some(bgl))
}
Err(e) => Err(e),
}
@@ -3728,7 +3774,7 @@ impl Device {
immediate_size: 0, //TODO?
};
let layout = self.create_pipeline_layout(&layout_desc)?;
let layout = self.create_pipeline_layout_impl(&layout_desc, true)?;
Ok(layout)
}
@@ -3756,9 +3802,7 @@ impl Device {
};
let mut binding_layout_source = match pipeline_layout {
Some(ref pipeline_layout) => {
validation::BindingLayoutSource::Provided(pipeline_layout.get_binding_maps())
}
Some(pipeline_layout) => validation::BindingLayoutSource::Provided(pipeline_layout),
None => validation::BindingLayoutSource::new_derived(&self.limits),
};
let mut shader_binding_sizes = FastHashMap::default();
@@ -3786,12 +3830,9 @@ impl Device {
}
let pipeline_layout = match binding_layout_source {
validation::BindingLayoutSource::Provided(_) => {
drop(binding_layout_source);
pipeline_layout.unwrap()
}
validation::BindingLayoutSource::Provided(pipeline_layout) => pipeline_layout,
validation::BindingLayoutSource::Derived(entries) => {
self.derive_pipeline_layout(entries)?
self.create_derived_pipeline_layout(entries)?
}
};
@@ -3852,6 +3893,10 @@ impl Device {
if is_auto_layout {
for bgl in pipeline.layout.bind_group_layouts.iter() {
let Some(bgl) = bgl else {
continue;
};
// `bind_group_layouts` might contain duplicate entries, so we need to ignore the result.
let _ = bgl
.exclusive_pipeline
@@ -4268,9 +4313,7 @@ impl Device {
};
let mut binding_layout_source = match pipeline_layout {
Some(ref pipeline_layout) => {
validation::BindingLayoutSource::Provided(pipeline_layout.get_binding_maps())
}
Some(pipeline_layout) => validation::BindingLayoutSource::Provided(pipeline_layout),
None => validation::BindingLayoutSource::new_derived(&self.limits),
};
@@ -4510,12 +4553,9 @@ impl Device {
}
let pipeline_layout = match binding_layout_source {
validation::BindingLayoutSource::Provided(_) => {
drop(binding_layout_source);
pipeline_layout.unwrap()
}
validation::BindingLayoutSource::Provided(pipeline_layout) => pipeline_layout,
validation::BindingLayoutSource::Derived(entries) => {
self.derive_pipeline_layout(entries)?
self.create_derived_pipeline_layout(entries)?
}
};
@@ -4667,6 +4707,10 @@ impl Device {
if is_auto_layout {
for bgl in pipeline.layout.bind_group_layouts.iter() {
let Some(bgl) = bgl else {
continue;
};
// `bind_group_layouts` might contain duplicate entries, so we need to ignore the result.
let _ = bgl
.exclusive_pipeline
@@ -183,8 +183,8 @@ impl Dispatch {
),
flags: hal::PipelineLayoutFlags::empty(),
bind_group_layouts: &[
dst_bind_group_layout.as_ref(),
src_bind_group_layout.as_ref(),
Some(dst_bind_group_layout.as_ref()),
Some(src_bind_group_layout.as_ref()),
],
immediate_size: 4,
};
+6 -6
View File
@@ -107,9 +107,9 @@ impl Draw {
),
flags: hal::PipelineLayoutFlags::empty(),
bind_group_layouts: &[
metadata_bind_group_layout.as_ref(),
src_bind_group_layout.as_ref(),
dst_bind_group_layout.as_ref(),
Some(metadata_bind_group_layout.as_ref()),
Some(src_bind_group_layout.as_ref()),
Some(dst_bind_group_layout.as_ref()),
],
immediate_size: 8,
};
@@ -422,7 +422,7 @@ impl Draw {
let metadata_bind_group =
resources.get_metadata_bind_group(batch.metadata_resource_index);
unsafe {
encoder.set_bind_group(pipeline_layout, 0, Some(metadata_bind_group), &[]);
encoder.set_bind_group(pipeline_layout, 0, metadata_bind_group, &[]);
}
// Make sure the indirect buffer is still valid.
@@ -439,14 +439,14 @@ impl Draw {
encoder.set_bind_group(
pipeline_layout,
1,
Some(src_bind_group),
src_bind_group,
&[batch.src_dynamic_offset as u32],
);
}
let dst_bind_group = resources.get_dst_bind_group(batch.dst_resource_index);
unsafe {
encoder.set_bind_group(pipeline_layout, 2, Some(dst_bind_group), &[]);
encoder.set_bind_group(pipeline_layout, 2, dst_bind_group, &[]);
}
unsafe {
+3 -11
View File
@@ -28,7 +28,7 @@ use crate::{
/// Information about buffer bindings, which
/// is validated against the shader (and pipeline)
/// at draw time as opposed to initialization time.
#[derive(Debug)]
#[derive(Debug, Default)]
pub(crate) struct LateSizedBufferGroup {
// The order has to match `BindGroup::late_buffer_binding_sizes`.
pub(crate) shader_sizes: Vec<wgt::BufferAddress>,
@@ -312,11 +312,7 @@ impl ComputePipeline {
self: &Arc<Self>,
index: u32,
) -> Result<Arc<BindGroupLayout>, GetBindGroupLayoutError> {
self.layout
.bind_group_layouts
.get(index as usize)
.cloned()
.ok_or(GetBindGroupLayoutError::InvalidGroupIndex(index))
self.layout.get_bind_group_layout(index)
}
}
@@ -854,10 +850,6 @@ impl RenderPipeline {
self: &Arc<Self>,
index: u32,
) -> Result<Arc<BindGroupLayout>, GetBindGroupLayoutError> {
self.layout
.bind_group_layouts
.get(index as usize)
.cloned()
.ok_or(GetBindGroupLayoutError::InvalidGroupIndex(index))
self.layout.get_bind_group_layout(index)
}
}
+2 -2
View File
@@ -195,7 +195,7 @@ impl TimestampNormalizer {
Some("(wgpu internal) Timestamp normalizer pipeline layout"),
device.instance_flags,
),
bind_group_layouts: &[temporary_bind_group_layout.as_ref()],
bind_group_layouts: &[Some(temporary_bind_group_layout.as_ref())],
immediate_size: 8,
flags: hal::PipelineLayoutFlags::empty(),
})
@@ -347,7 +347,7 @@ impl TimestampNormalizer {
timestamp_writes: None,
});
encoder.set_compute_pipeline(&*state.pipeline);
encoder.set_bind_group(&*state.pipeline_layout, 0, Some(bind_group), &[]);
encoder.set_bind_group(&*state.pipeline_layout, 0, bind_group, &[]);
encoder.set_immediates(
&*state.pipeline_layout,
0,
+14 -15
View File
@@ -1,6 +1,7 @@
use alloc::{
boxed::Box,
string::{String, ToString as _},
sync::Arc,
vec::Vec,
};
use core::fmt;
@@ -1010,7 +1011,7 @@ pub fn check_texture_format(
}
}
pub enum BindingLayoutSource<'a> {
pub enum BindingLayoutSource {
/// The binding layout is derived from the pipeline layout.
///
/// This will be filled in by the shader binding validation, as it iterates the shader's interfaces.
@@ -1018,10 +1019,10 @@ pub enum BindingLayoutSource<'a> {
/// The binding layout is provided by the user in BGLs.
///
/// This will be validated against the shader's interfaces.
Provided(ArrayVec<&'a bgl::EntryMap, { hal::MAX_BIND_GROUPS }>),
Provided(Arc<crate::binding_model::PipelineLayout>),
}
impl<'a> BindingLayoutSource<'a> {
impl BindingLayoutSource {
pub fn new_derived(limits: &wgt::Limits) -> Self {
let mut array = ArrayVec::new();
for _ in 0..limits.max_bind_groups {
@@ -1247,7 +1248,7 @@ impl Interface {
/// <https://www.w3.org/TR/webgpu/#abstract-opdef-validating-inter-stage-interfaces>.
pub fn check_stage(
&self,
layouts: &mut BindingLayoutSource<'_>,
layouts: &mut BindingLayoutSource,
shader_binding_sizes: &mut FastHashMap<naga::ResourceBinding, wgt::BufferSize>,
entry_point_name: &str,
shader_stage: ShaderStageForValidation,
@@ -1269,7 +1270,7 @@ impl Interface {
let res = &self.resources[handle];
let result = 'err: {
match layouts {
BindingLayoutSource::Provided(layouts) => {
BindingLayoutSource::Provided(pipeline_layout) => {
// update the required binding size for this buffer
if let ResourceType::Buffer { size } = res.ty {
match shader_binding_sizes.entry(res.bind) {
@@ -1282,11 +1283,9 @@ impl Interface {
}
}
let Some(map) = layouts.get(res.bind.group as usize) else {
break 'err Err(BindingError::Missing);
};
let Some(entry) = map.get(res.bind.binding) else {
let Some(entry) =
pipeline_layout.get_bgl_entry(res.bind.group, res.bind.binding)
else {
break 'err Err(BindingError::Missing);
};
@@ -1340,15 +1339,15 @@ impl Interface {
//
// We only need to do this if the binding layout is provided by the user, as derived
// layouts will inherently be correctly tagged.
if let BindingLayoutSource::Provided(layouts) = layouts {
if let BindingLayoutSource::Provided(pipeline_layout) = layouts {
for &(texture_handle, sampler_handle) in entry_point.sampling_pairs.iter() {
let texture_bind = &self.resources[texture_handle].bind;
let sampler_bind = &self.resources[sampler_handle].bind;
let texture_layout = layouts[texture_bind.group as usize]
.get(texture_bind.binding)
let texture_layout = pipeline_layout
.get_bgl_entry(texture_bind.group, texture_bind.binding)
.unwrap();
let sampler_layout = layouts[sampler_bind.group as usize]
.get(sampler_bind.binding)
let sampler_layout = pipeline_layout
.get_bgl_entry(sampler_bind.group, sampler_bind.binding)
.unwrap();
assert!(texture_layout.visibility.contains(stage_bit));
assert!(sampler_layout.visibility.contains(stage_bit));
+1 -1
View File
@@ -245,7 +245,7 @@ impl<A: hal::Api> Example<A> {
let pipeline_layout_desc = hal::PipelineLayoutDescriptor {
label: None,
flags: hal::PipelineLayoutFlags::empty(),
bind_group_layouts: &[&global_group_layout, &local_group_layout],
bind_group_layouts: &[Some(&global_group_layout), Some(&local_group_layout)],
immediate_size: 0,
};
let pipeline_layout = unsafe {
@@ -390,7 +390,7 @@ impl<A: hal::Api> Example<A> {
let pipeline_layout_desc = hal::PipelineLayoutDescriptor {
label: None,
flags: hal::PipelineLayoutFlags::empty(),
bind_group_layouts: &[&bgl],
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
};
let pipeline_layout = unsafe {
+1 -1
View File
@@ -1127,7 +1127,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
group: &super::BindGroup,
dynamic_offsets: &[wgt::DynamicOffset],
) {
let info = &layout.bind_group_infos[index as usize];
let info = layout.bind_group_infos[index as usize].as_ref().unwrap();
let mut root_index = info.base_root_index as usize;
// Bind CBV/SRC/UAV descriptor tables
+10 -3
View File
@@ -950,6 +950,10 @@ impl crate::Device for super::Device {
let mut total_non_dynamic_entries = 0_usize;
let mut sampler_in_any_bind_group = false;
for bgl in desc.bind_group_layouts {
let Some(bgl) = bgl else {
continue;
};
let mut sampler_in_bind_group = false;
for entry in &bgl.entries {
@@ -980,9 +984,12 @@ impl crate::Device for super::Device {
let mut ranges = Vec::with_capacity(total_non_dynamic_entries);
let mut bind_group_infos =
ArrayVec::<super::BindGroupInfo, { crate::MAX_BIND_GROUPS }>::default();
let mut bind_group_infos = [const { None }; crate::MAX_BIND_GROUPS];
for (index, bgl) in desc.bind_group_layouts.iter().enumerate() {
let Some(bgl) = bgl else {
continue;
};
let mut info = super::BindGroupInfo {
tables: super::TableTypes::empty(),
base_root_index: parameters.len() as u32,
@@ -1247,7 +1254,7 @@ impl crate::Device for super::Device {
total_dynamic_storage_buffers += dynamic_storage_buffers;
}
bind_group_infos.push(info);
bind_group_infos[index] = Some(info);
}
let sampler_heap_target = hlsl::SamplerHeapBindTargets {
+1 -1
View File
@@ -1119,7 +1119,7 @@ pub struct PipelineLayout {
shared: PipelineLayoutShared,
// Storing for each associated bind group, which tables we created
// in the root signature. This is required for binding descriptor sets.
bind_group_infos: ArrayVec<BindGroupInfo, { crate::MAX_BIND_GROUPS }>,
bind_group_infos: [Option<BindGroupInfo>; crate::MAX_BIND_GROUPS],
naga_options: naga::back::hlsl::Options,
}
+2 -8
View File
@@ -62,7 +62,7 @@ pub trait DynCommandEncoder: DynResource + core::fmt::Debug {
&mut self,
layout: &dyn DynPipelineLayout,
index: u32,
group: Option<&dyn DynBindGroup>,
group: &dyn DynBindGroup,
dynamic_offsets: &[wgt::DynamicOffset],
);
@@ -317,15 +317,9 @@ impl<C: CommandEncoder + DynResource> DynCommandEncoder for C {
&mut self,
layout: &dyn DynPipelineLayout,
index: u32,
group: Option<&dyn DynBindGroup>,
group: &dyn DynBindGroup,
dynamic_offsets: &[wgt::DynamicOffset],
) {
if group.is_none() {
// TODO: Handle group None correctly.
return;
}
let group = group.unwrap();
let layout = layout.expect_downcast_ref();
let group = group.expect_downcast_ref();
unsafe { C::set_bind_group(self, layout, index, group, dynamic_offsets) };
+1 -1
View File
@@ -290,7 +290,7 @@ impl<D: Device + DynResource> DynDevice for D {
let bind_group_layouts: Vec<_> = desc
.bind_group_layouts
.iter()
.map(|bgl| bgl.expect_downcast_ref())
.map(|bgl| bgl.map(|bgl| bgl.expect_downcast_ref()))
.collect();
let desc = PipelineLayoutDescriptor {
label: desc.label,
+1 -1
View File
@@ -718,7 +718,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
let mut do_index = 0;
let mut dirty_textures = 0u32;
let mut dirty_samplers = 0u32;
let group_info = &layout.group_infos[index as usize];
let group_info = layout.group_infos[index as usize].as_ref().unwrap();
for (binding_layout, raw_binding) in group_info.entries.iter().zip(group.contents.iter()) {
let slot = group_info.binding_to_slot[binding_layout.binding as usize] as u32;
+12 -6
View File
@@ -321,10 +321,11 @@ impl super::Device {
multiview_mask: Option<NonZeroU32>,
) -> Result<Arc<super::PipelineInner>, crate::PipelineError> {
let mut program_stages = ArrayVec::new();
let mut group_to_binding_to_slot = Vec::with_capacity(layout.group_infos.len());
for group in &*layout.group_infos {
group_to_binding_to_slot.push(group.binding_to_slot.clone());
}
let group_to_binding_to_slot = layout
.group_infos
.iter()
.map(|group| group.as_ref().map(|group| group.binding_to_slot.clone()))
.collect::<Vec<_>>();
for &(naga_stage, stage) in &shaders {
program_stages.push(super::ProgramStage {
naga_stage: naga_stage.to_owned(),
@@ -1198,6 +1199,11 @@ impl crate::Device for super::Device {
let mut binding_map = glsl::BindingMap::default();
for (group_index, bg_layout) in desc.bind_group_layouts.iter().enumerate() {
let Some(bg_layout) = bg_layout else {
group_infos.push(None);
continue;
};
// create a vector with the size enough to hold all the bindings, filled with `!0`
let mut binding_to_slot = vec![
!0;
@@ -1236,10 +1242,10 @@ impl crate::Device for super::Device {
*counter += entry.count.map_or(1, |c| c.get() as u8);
}
group_infos.push(super::BindGroupLayoutInfo {
group_infos.push(Some(super::BindGroupLayoutInfo {
entries: Arc::clone(&bg_layout.entries),
binding_to_slot,
});
}));
}
self.counters.pipeline_layouts.add(1);
+6 -3
View File
@@ -553,15 +553,18 @@ struct BindGroupLayoutInfo {
#[derive(Debug)]
pub struct PipelineLayout {
group_infos: Box<[BindGroupLayoutInfo]>,
group_infos: Box<[Option<BindGroupLayoutInfo>]>,
naga_options: naga::back::glsl::Options,
}
impl crate::DynPipelineLayout for PipelineLayout {}
impl PipelineLayout {
/// # Panics
/// If the pipeline layout does not contain a bind group layout used by
/// the resource binding.
fn get_slot(&self, br: &naga::ResourceBinding) -> u8 {
let group_info = &self.group_infos[br.group as usize];
let group_info = self.group_infos[br.group as usize].as_ref().unwrap();
group_info.binding_to_slot[br.binding as usize]
}
}
@@ -709,7 +712,7 @@ struct ProgramStage {
#[derive(PartialEq, Eq, Hash)]
struct ProgramCacheKey {
stages: ArrayVec<ProgramStage, 3>,
group_to_binding_to_slot: Box<[Box<[u8]>]>,
group_to_binding_to_slot: Box<[Option<Box<[u8]>>]>,
}
type ProgramCache = FastHashMap<ProgramCacheKey, Result<Arc<PipelineInner>, crate::PipelineError>>;
+1 -1
View File
@@ -2094,7 +2094,7 @@ pub struct BindGroupLayoutDescriptor<'a> {
pub struct PipelineLayoutDescriptor<'a, B: DynBindGroupLayout + ?Sized> {
pub label: Label<'a>,
pub flags: PipelineLayoutFlags,
pub bind_group_layouts: &'a [&'a B],
pub bind_group_layouts: &'a [Option<&'a B>],
pub immediate_size: u32,
}
+3 -1
View File
@@ -1025,7 +1025,9 @@ impl crate::CommandEncoder for super::CommandEncoder {
group: &super::BindGroup,
dynamic_offsets: &[wgt::DynamicOffset],
) {
let bg_info = &layout.bind_group_infos[group_index as usize];
let bg_info = layout.bind_group_infos[group_index as usize]
.as_ref()
.unwrap();
let render_encoder = self.state.render.clone();
let compute_encoder = self.state.compute.clone();
if let Some(encoder) = render_encoder {
+7 -3
View File
@@ -728,7 +728,7 @@ impl crate::Device for super::Device {
need_sizes_buffer: false,
resources: Default::default(),
});
let mut bind_group_infos = arrayvec::ArrayVec::new();
let mut bind_group_infos = [const { None }; crate::MAX_BIND_GROUPS];
// First, place the immediates
for info in stage_data.iter_mut() {
@@ -742,7 +742,11 @@ impl crate::Device for super::Device {
}
// Second, place the described resources
for (group_index, &bgl) in desc.bind_group_layouts.iter().enumerate() {
for (group_index, bgl) in desc.bind_group_layouts.iter().enumerate() {
let Some(bgl) = bgl else {
continue;
};
// remember where the resources for this set start at each shader stage
let base_resource_indices = stage_data.map_ref(|info| info.counters.clone());
@@ -827,7 +831,7 @@ impl crate::Device for super::Device {
}
}
bind_group_infos.push(super::BindGroupLayoutInfo {
bind_group_infos[group_index] = Some(super::BindGroupLayoutInfo {
base_resource_indices,
});
}
+1 -2
View File
@@ -33,7 +33,6 @@ use alloc::{
};
use core::{fmt, iter, ops, ptr::NonNull, sync::atomic};
use arrayvec::ArrayVec;
use bitflags::bitflags;
use hashbrown::HashMap;
use naga::FastHashMap;
@@ -734,7 +733,7 @@ struct ImmediateDataInfo {
#[derive(Debug)]
pub struct PipelineLayout {
bind_group_infos: ArrayVec<BindGroupLayoutInfo, { crate::MAX_BIND_GROUPS }>,
bind_group_infos: [Option<BindGroupLayoutInfo>; crate::MAX_BIND_GROUPS],
immediates_infos: MultiStageData<Option<ImmediateDataInfo>>,
total_counters: MultiStageResourceCounters,
total_immediates: u32,
+7
View File
@@ -2514,6 +2514,12 @@ impl super::Adapter {
let drop_guard = crate::DropGuard::from_option(drop_callback);
let empty_descriptor_set_layout = unsafe {
raw_device
.create_descriptor_set_layout(&vk::DescriptorSetLayoutCreateInfo::default(), None)
.map_err(super::map_host_device_oom_err)?
};
let shared = Arc::new(super::DeviceShared {
raw: raw_device,
family_index,
@@ -2544,6 +2550,7 @@ impl super::Adapter {
texture_identity_factory: super::ResourceIdentityFactory::new(),
texture_view_identity_factory: super::ResourceIdentityFactory::new(),
empty_descriptor_set_layout,
});
let relay_semaphores = super::RelaySemaphores::new(&shared)?;
+18 -2
View File
@@ -1420,7 +1420,19 @@ impl crate::Device for super::Device {
let vk_set_layouts = desc
.bind_group_layouts
.iter()
.map(|bgl| bgl.raw)
.map(|bgl| match bgl {
Some(bgl) => bgl.raw,
None => {
// `VUID-VkPipelineLayoutCreateInfo-pSetLayouts-parameter`
// says `VK_NULL_HANDLE` is allowed but
// `VUID-VkPipelineLayoutCreateInfo-graphicsPipelineLibrary-06753`
// says it's not, unless the `graphicsPipelineLibrary`
// feature is enabled.
//
// We use an empty descriptor set layout to work around this.
self.shared.empty_descriptor_set_layout
}
})
.collect::<Vec<_>>();
let vk_immediates_ranges: Option<vk::PushConstantRange> = if desc.immediate_size != 0 {
Some(vk::PushConstantRange {
@@ -1452,7 +1464,11 @@ impl crate::Device for super::Device {
}
let mut binding_map = BTreeMap::new();
for (group, &layout) in desc.bind_group_layouts.iter().enumerate() {
for (group, layout) in desc.bind_group_layouts.iter().enumerate() {
let Some(layout) = layout else {
continue;
};
for &(binding, binding_info) in &layout.binding_map {
binding_map.insert(
naga::ResourceBinding {
+6
View File
@@ -495,6 +495,8 @@ struct DeviceShared {
/// As above, for texture views.
texture_view_identity_factory: ResourceIdentityFactory<vk::ImageView>,
empty_descriptor_set_layout: vk::DescriptorSetLayout,
// The `drop_guard` field must be the last field of this struct so it is dropped last.
// Do not add new fields after it.
drop_guard: Option<crate::DropGuard>,
@@ -505,6 +507,10 @@ impl Drop for DeviceShared {
for &raw in self.render_passes.lock().values() {
unsafe { self.raw.destroy_render_pass(raw, None) };
}
unsafe {
self.raw
.destroy_descriptor_set_layout(self.empty_descriptor_set_layout, None)
};
if self.drop_guard.is_none() {
unsafe { self.raw.destroy_device(None) };
}
+1 -1
View File
@@ -35,7 +35,7 @@ pub struct PipelineLayoutDescriptor<'a> {
pub label: Label<'a>,
/// Bind groups that this pipeline uses. The first entry will provide all the bindings for
/// "set = 0", second entry will provide all the bindings for "set = 1" etc.
pub bind_group_layouts: &'a [&'a BindGroupLayout],
pub bind_group_layouts: &'a [Option<&'a BindGroupLayout>],
/// The number of bytes of immediate data that are allocated for use
/// in the shader. The `var<immediate>`s in the shader attached to
/// this pipeline must be equal or smaller than this size.
+14 -19
View File
@@ -2129,10 +2129,14 @@ impl dispatch::DeviceInterface for WebDevice {
&self,
desc: &crate::PipelineLayoutDescriptor<'_>,
) -> dispatch::DispatchPipelineLayout {
let null = wasm_bindgen::JsValue::NULL;
let temp_layouts = desc
.bind_group_layouts
.iter()
.map(|bgl| &bgl.inner.as_webgpu().inner)
.map(|bgl| match bgl {
Some(bgl) => bgl.inner.as_webgpu().inner.as_ref(),
None => &null,
})
.collect::<js_sys::Array>();
let mapped_desc = webgpu_sys::GpuPipelineLayoutDescriptor::new(&temp_layouts);
if let Some(label) = desc.label {
@@ -3315,18 +3319,15 @@ impl dispatch::ComputePassInterface for WebComputePassEncoder {
bind_group: Option<&dispatch::DispatchBindGroup>,
offsets: &[crate::DynamicOffset],
) {
let Some(bind_group) = bind_group else {
return;
};
let bind_group = &bind_group.as_webgpu().inner;
let bind_group = bind_group.map(|bind_group| &bind_group.as_webgpu().inner);
if offsets.is_empty() {
self.inner.set_bind_group(index, Some(bind_group));
self.inner.set_bind_group(index, bind_group);
} else {
self.inner
.set_bind_group_with_u32_slice_and_f64_and_dynamic_offsets_data_length(
index,
Some(bind_group),
bind_group,
offsets,
0f64,
offsets.len() as u32,
@@ -3402,18 +3403,15 @@ impl dispatch::RenderPassInterface for WebRenderPassEncoder {
bind_group: Option<&dispatch::DispatchBindGroup>,
offsets: &[crate::DynamicOffset],
) {
let Some(bind_group) = bind_group else {
return;
};
let bind_group = &bind_group.as_webgpu().inner;
let bind_group = bind_group.map(|bind_group| &bind_group.as_webgpu().inner);
if offsets.is_empty() {
self.inner.set_bind_group(index, Some(bind_group));
self.inner.set_bind_group(index, bind_group);
} else {
self.inner
.set_bind_group_with_u32_slice_and_f64_and_dynamic_offsets_data_length(
index,
Some(bind_group),
bind_group,
offsets,
0f64,
offsets.len() as u32,
@@ -3696,18 +3694,15 @@ impl dispatch::RenderBundleEncoderInterface for WebRenderBundleEncoder {
bind_group: Option<&dispatch::DispatchBindGroup>,
offsets: &[crate::DynamicOffset],
) {
let Some(bind_group) = bind_group else {
return;
};
let bind_group = &bind_group.as_webgpu().inner;
let bind_group = bind_group.map(|bind_group| &bind_group.as_webgpu().inner);
if offsets.is_empty() {
self.inner.set_bind_group(index, Some(bind_group));
self.inner.set_bind_group(index, bind_group);
} else {
self.inner
.set_bind_group_with_u32_slice_and_f64_and_dynamic_offsets_data_length(
index,
Some(bind_group),
bind_group,
offsets,
0f64,
offsets.len() as u32,
+1 -1
View File
@@ -1283,7 +1283,7 @@ impl dispatch::DeviceInterface for CoreDevice {
let temp_layouts = desc
.bind_group_layouts
.iter()
.map(|bgl| bgl.inner.as_core().id)
.map(|bgl| bgl.map(|bgl| bgl.inner.as_core().id))
.collect::<ArrayVec<_, { wgc::MAX_BIND_GROUPS }>>();
let descriptor = wgc::binding_model::PipelineLayoutDescriptor {
label: desc.label.map(Borrowed),
+1 -1
View File
@@ -93,7 +93,7 @@ impl<'a> TextureBlitterBuilder<'a> {
.device
.create_pipeline_layout(&PipelineLayoutDescriptor {
label: Some("wgpu::util::TextureBlitter::pipeline_layout"),
bind_group_layouts: &[&bind_group_layout],
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});