From c8beade1877251c494036fc3661b04ec6aad63a9 Mon Sep 17 00:00:00 2001 From: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> Date: Fri, 13 Sep 2024 17:30:38 +0200 Subject: [PATCH] remove backend from ID (#6263) --- deno_webgpu/lib.rs | 5 +- player/src/bin/play.rs | 9 +- player/src/lib.rs | 6 +- player/tests/data/bind-group.ron | 26 +- player/tests/data/buffer-copy.ron | 4 +- player/tests/data/clear-buffer-texture.ron | 18 +- .../tests/data/pipeline-statistics-query.ron | 22 +- player/tests/data/quad.ron | 28 +- player/tests/data/zero-init-buffer.ron | 34 +- .../tests/data/zero-init-texture-binding.ron | 50 +-- .../data/zero-init-texture-copytobuffer.ron | 8 +- .../data/zero-init-texture-rendertarget.ron | 14 +- player/tests/test.rs | 14 +- wgpu-core/src/device/global.rs | 82 ++--- wgpu-core/src/device/mod.rs | 8 +- wgpu-core/src/device/queue.rs | 2 +- wgpu-core/src/id.rs | 152 +++------ wgpu-core/src/identity.rs | 22 +- wgpu-core/src/instance.rs | 292 +++++------------- wgpu-core/src/present.rs | 2 +- wgpu-core/src/registry.rs | 10 +- wgpu-core/src/storage.rs | 12 +- wgpu/src/backend/wgpu_core.rs | 6 +- 23 files changed, 282 insertions(+), 544 deletions(-) diff --git a/deno_webgpu/lib.rs b/deno_webgpu/lib.rs index 6f708014f..e31812e25 100644 --- a/deno_webgpu/lib.rs +++ b/deno_webgpu/lib.rs @@ -401,10 +401,7 @@ pub fn op_webgpu_request_adapter( force_fallback_adapter, compatible_surface: None, // windowless }; - let res = instance.request_adapter( - &descriptor, - wgpu_core::instance::AdapterInputs::Mask(backends, |_| None), - ); + let res = instance.request_adapter(&descriptor, backends, None); let adapter = match res { Ok(adapter) => adapter, diff --git a/player/src/bin/play.rs b/player/src/bin/play.rs index eb26ce6ba..558eb194b 100644 --- a/player/src/bin/play.rs +++ b/player/src/bin/play.rs @@ -56,7 +56,7 @@ fn main() { global.instance_create_surface( window.display_handle().unwrap().into(), window.window_handle().unwrap().into(), - Some(wgc::id::Id::zip(0, 1, wgt::Backend::Empty)), + Some(wgc::id::Id::zip(0, 1)), ) } .unwrap(); @@ -74,14 +74,15 @@ fn main() { #[cfg(not(feature = "winit"))] compatible_surface: None, }, - wgc::instance::AdapterInputs::IdSet(&[wgc::id::AdapterId::zip(0, 0, backend)]), + wgt::Backends::from(backend), + Some(wgc::id::AdapterId::zip(0, 1)), ) .expect("Unable to find an adapter for selected backend"); let info = global.adapter_get_info(adapter); log::info!("Picked '{}'", info.name); - let device_id = wgc::id::Id::zip(1, 0, backend); - let queue_id = wgc::id::Id::zip(1, 0, backend); + let device_id = wgc::id::Id::zip(0, 1); + let queue_id = wgc::id::Id::zip(0, 1); let res = global.adapter_request_device( adapter, &desc, diff --git a/player/src/lib.rs b/player/src/lib.rs index 8ea4e775b..241c19096 100644 --- a/player/src/lib.rs +++ b/player/src/lib.rs @@ -352,11 +352,7 @@ impl GlobalPlay for wgc::global::Global { let (encoder, error) = self.device_create_command_encoder( device, &wgt::CommandEncoderDescriptor { label: None }, - Some( - comb_manager - .process(device.backend()) - .into_command_encoder_id(), - ), + Some(comb_manager.process().into_command_encoder_id()), ); if let Some(e) = error { panic!("{e}"); diff --git a/player/tests/data/bind-group.ron b/player/tests/data/bind-group.ron index 87b3a1c72..80a5d18ba 100644 --- a/player/tests/data/bind-group.ron +++ b/player/tests/data/bind-group.ron @@ -2,13 +2,13 @@ features: [], expectations: [], //not crash! actions: [ - CreateBuffer(Id(0, 1, Empty), ( + CreateBuffer(Id(0, 1), ( label: None, size: 16, usage: 64, mapped_at_creation: false, )), - CreateBindGroupLayout(Id(0, 1, Empty), ( + CreateBindGroupLayout(Id(0, 1), ( label: None, entries: [ ( @@ -20,29 +20,29 @@ ), ], )), - CreateBindGroup(Id(0, 1, Empty), ( + CreateBindGroup(Id(0, 1), ( label: None, - layout: Id(0, 1, Empty), + layout: Id(0, 1), entries: [ ( binding: 0, resource: Buffer(( - buffer_id: Id(0, 1, Empty), + buffer_id: Id(0, 1), offset: 0, size: None, )), ) ], )), - CreatePipelineLayout(Id(0, 1, Empty), ( + CreatePipelineLayout(Id(0, 1), ( label: Some("empty"), bind_group_layouts: [ - Id(0, 1, Empty), + Id(0, 1), ], push_constant_ranges: [], )), CreateShaderModule( - id: Id(0, 1, Empty), + id: Id(0, 1), desc: ( label: None, flags: (bits: 3), @@ -50,12 +50,12 @@ data: "empty.wgsl", ), CreateComputePipeline( - id: Id(0, 1, Empty), + id: Id(0, 1), desc: ( label: None, - layout: Some(Id(0, 1, Empty)), + layout: Some(Id(0, 1)), stage: ( - module: Id(0, 1, Empty), + module: Id(0, 1), entry_point: None, constants: {}, zero_initialize_workgroup_memory: true, @@ -70,9 +70,9 @@ SetBindGroup( index: 0, num_dynamic_offsets: 0, - bind_group_id: Some(Id(0, 1, Empty)), + bind_group_id: Some(Id(0, 1)), ), - SetPipeline(Id(0, 1, Empty)), + SetPipeline(Id(0, 1)), ], dynamic_offsets: [], string_data: [], diff --git a/player/tests/data/buffer-copy.ron b/player/tests/data/buffer-copy.ron index 5c66f2c01..0cce3b1f6 100644 --- a/player/tests/data/buffer-copy.ron +++ b/player/tests/data/buffer-copy.ron @@ -10,7 +10,7 @@ ], actions: [ CreateBuffer( - Id(0, 1, Empty), + Id(0, 1), ( label: Some("dummy"), size: 16, @@ -19,7 +19,7 @@ ), ), WriteBuffer( - id: Id(0, 1, Empty), + id: Id(0, 1), data: "data1.bin", range: ( start: 0, diff --git a/player/tests/data/clear-buffer-texture.ron b/player/tests/data/clear-buffer-texture.ron index 7b25fa42c..4b7548d2f 100644 --- a/player/tests/data/clear-buffer-texture.ron +++ b/player/tests/data/clear-buffer-texture.ron @@ -20,7 +20,7 @@ ) ], actions: [ - CreateTexture(Id(0, 1, Empty), ( + CreateTexture(Id(0, 1), ( label: Some("Output Texture"), size: ( width: 64, @@ -36,7 +36,7 @@ // First fill the texture to ensure it wasn't just zero initialized or "happened" to be zero. WriteTexture( to: ( - texture: Id(0, 1, Empty), + texture: Id(0, 1), mip_level: 0, array_layer: 0, ), @@ -52,7 +52,7 @@ ), ), CreateBuffer( - Id(0, 1, Empty), + Id(0, 1), ( label: Some("Output Buffer"), size: 16384, @@ -62,7 +62,7 @@ ), CreateBuffer( - Id(1, 1, Empty), + Id(1, 1), ( label: Some("Buffer to be cleared"), size: 16, @@ -72,7 +72,7 @@ ), // Make sure there is something in the buffer, otherwise it might be just zero init! WriteBuffer( - id: Id(1, 1, Empty), + id: Id(1, 1), data: "data1.bin", range: ( start: 0, @@ -82,7 +82,7 @@ ), Submit(1, [ ClearTexture( - dst: Id(0, 1, Empty), + dst: Id(0, 1), subresource_range: ImageSubresourceRange( aspect: all, baseMipLevel: 0, @@ -93,12 +93,12 @@ ), CopyTextureToBuffer( src: ( - texture: Id(0, 1, Empty), + texture: Id(0, 1), mip_level: 0, array_layer: 0, ), dst: ( - buffer: Id(0, 1, Empty), + buffer: Id(0, 1), layout: ( offset: 0, bytes_per_row: Some(256), @@ -112,7 +112,7 @@ ), // Partial clear to prove ClearBuffer( - dst: Id(1, 1, Empty), + dst: Id(1, 1), offset: 4, size: Some(8), ) diff --git a/player/tests/data/pipeline-statistics-query.ron b/player/tests/data/pipeline-statistics-query.ron index 8a6e4239b..17ef08b1b 100644 --- a/player/tests/data/pipeline-statistics-query.ron +++ b/player/tests/data/pipeline-statistics-query.ron @@ -9,13 +9,13 @@ ), ], actions: [ - CreatePipelineLayout(Id(0, 1, Empty), ( + CreatePipelineLayout(Id(0, 1), ( label: Some("empty"), bind_group_layouts: [], push_constant_ranges: [], )), CreateShaderModule( - id: Id(0, 1, Empty), + id: Id(0, 1), desc: ( label: None, flags: (bits: 3), @@ -23,12 +23,12 @@ data: "empty.wgsl", ), CreateComputePipeline( - id: Id(0, 1, Empty), + id: Id(0, 1), desc: ( label: None, - layout: Some(Id(0, 1, Empty)), + layout: Some(Id(0, 1)), stage: ( - module: Id(0, 1, Empty), + module: Id(0, 1), entry_point: None, constants: {}, zero_initialize_workgroup_memory: true, @@ -37,7 +37,7 @@ ), ), CreateQuerySet( - id: Id(0, 1, Empty), + id: Id(0, 1), desc: ( label: Some("Compute Invocation QuerySet"), count: 2, @@ -45,7 +45,7 @@ ), ), CreateBuffer( - Id(0, 1, Empty), + Id(0, 1), ( label: Some("Compute Invocation Result Buffer"), size: 16, @@ -57,9 +57,9 @@ RunComputePass( base: ( commands: [ - SetPipeline(Id(0, 1, Empty)), + SetPipeline(Id(0, 1)), BeginPipelineStatisticsQuery( - query_set_id: Id(0, 1, Empty), + query_set_id: Id(0, 1), query_index: 0, ), Dispatch((2, 3, 7,)), @@ -71,10 +71,10 @@ ), ), ResolveQuerySet( - query_set_id: Id(0, 1, Empty), + query_set_id: Id(0, 1), start_query: 0, query_count: 1, - destination: Id(0, 1, Empty), + destination: Id(0, 1), destination_offset: 0, ) ]), diff --git a/player/tests/data/quad.ron b/player/tests/data/quad.ron index aad576c42..a954cb597 100644 --- a/player/tests/data/quad.ron +++ b/player/tests/data/quad.ron @@ -10,14 +10,14 @@ ], actions: [ CreateShaderModule( - id: Id(0, 1, Empty), + id: Id(0, 1), desc: ( label: None, flags: (bits: 3), ), data: "quad.wgsl", ), - CreateTexture(Id(0, 1, Empty), ( + CreateTexture(Id(0, 1), ( label: Some("Output Texture"), size: ( width: 64, @@ -31,12 +31,12 @@ view_formats: [], )), CreateTextureView( - id: Id(0, 1, Empty), - parent_id: Id(0, 1, Empty), + id: Id(0, 1), + parent_id: Id(0, 1), desc: (), ), CreateBuffer( - Id(0, 1, Empty), + Id(0, 1), ( label: Some("Output Buffer"), size: 16384, @@ -44,19 +44,19 @@ mapped_at_creation: false, ), ), - CreatePipelineLayout(Id(0, 1, Empty), ( + CreatePipelineLayout(Id(0, 1), ( label: None, bind_group_layouts: [], push_constant_ranges: [], )), CreateRenderPipeline( - id: Id(0, 1, Empty), + id: Id(0, 1), desc: ( label: None, - layout: Some(Id(0, 1, Empty)), + layout: Some(Id(0, 1)), vertex: ( stage: ( - module: Id(0, 1, Empty), + module: Id(0, 1), entry_point: None, constants: {}, zero_initialize_workgroup_memory: true, @@ -66,7 +66,7 @@ ), fragment: Some(( stage: ( - module: Id(0, 1, Empty), + module: Id(0, 1), entry_point: None, constants: {}, zero_initialize_workgroup_memory: true, @@ -84,7 +84,7 @@ RunRenderPass( base: ( commands: [ - SetPipeline(Id(0, 1, Empty)), + SetPipeline(Id(0, 1)), Draw( vertex_count: 3, instance_count: 1, @@ -98,7 +98,7 @@ ), target_colors: [ Some(( - view: Id(0, 1, Empty), + view: Id(0, 1), resolve_target: None, channel: ( load_op: clear, @@ -117,12 +117,12 @@ ), CopyTextureToBuffer( src: ( - texture: Id(0, 1, Empty), + texture: Id(0, 1), mip_level: 0, array_layer: 0, ), dst: ( - buffer: Id(0, 1, Empty), + buffer: Id(0, 1), layout: ( offset: 0, bytes_per_row: Some(256), diff --git a/player/tests/data/zero-init-buffer.ron b/player/tests/data/zero-init-buffer.ron index 2b3f4a890..c4cf25f65 100644 --- a/player/tests/data/zero-init-buffer.ron +++ b/player/tests/data/zero-init-buffer.ron @@ -39,7 +39,7 @@ ], actions: [ CreateBuffer( - Id(0, 1, Empty), + Id(0, 1), ( label: Some("mapped_at_creation: false, with MAP_WRITE"), size: 16, @@ -48,7 +48,7 @@ ), ), CreateBuffer( - Id(1, 1, Empty), + Id(1, 1), ( label: Some("mapped_at_creation: false, without MAP_WRITE"), size: 16, @@ -57,7 +57,7 @@ ), ), CreateBuffer( - Id(2, 1, Empty), + Id(2, 1), ( label: Some("partially written"), size: 24, @@ -66,7 +66,7 @@ ), ), WriteBuffer( - id: Id(2, 1, Empty), + id: Id(2, 1), data: "data1.bin", range: ( start: 4, @@ -75,20 +75,20 @@ queued: true, ), CreateShaderModule( - id: Id(0, 1, Empty), + id: Id(0, 1), desc: ( label: None, flags: (bits: 3), ), data: "zero-init-buffer-for-binding.wgsl", ), - CreateBuffer(Id(3, 1, Empty), ( + CreateBuffer(Id(3, 1), ( label: Some("used in binding"), size: 16, usage: 129, // STORAGE + MAP_READ mapped_at_creation: false, )), - CreateBindGroupLayout(Id(0, 1, Empty), ( + CreateBindGroupLayout(Id(0, 1), ( label: None, entries: [ ( @@ -105,34 +105,34 @@ ), ], )), - CreateBindGroup(Id(0, 1, Empty), ( + CreateBindGroup(Id(0, 1), ( label: None, - layout: Id(0, 1, Empty), + layout: Id(0, 1), entries: [ ( binding: 0, resource: Buffer(( - buffer_id: Id(3, 1, Empty), + buffer_id: Id(3, 1), offset: 0, size: Some(16), )), ), ], )), - CreatePipelineLayout(Id(0, 1, Empty), ( + CreatePipelineLayout(Id(0, 1), ( label: None, bind_group_layouts: [ - Id(0, 1, Empty), + Id(0, 1), ], push_constant_ranges: [], )), CreateComputePipeline( - id: Id(0, 1, Empty), + id: Id(0, 1), desc: ( label: None, - layout: Some(Id(0, 1, Empty)), + layout: Some(Id(0, 1)), stage: ( - module: Id(0, 1, Empty), + module: Id(0, 1), entry_point: None, constants: {}, zero_initialize_workgroup_memory: true, @@ -145,11 +145,11 @@ base: ( label: None, commands: [ - SetPipeline(Id(0, 1, Empty)), + SetPipeline(Id(0, 1)), SetBindGroup( index: 0, num_dynamic_offsets: 0, - bind_group_id: Some(Id(0, 1, Empty)), + bind_group_id: Some(Id(0, 1)), ), Dispatch((4, 1, 1)), ], diff --git a/player/tests/data/zero-init-texture-binding.ron b/player/tests/data/zero-init-texture-binding.ron index e828b6c13..48415f43c 100644 --- a/player/tests/data/zero-init-texture-binding.ron +++ b/player/tests/data/zero-init-texture-binding.ron @@ -17,7 +17,7 @@ // MISSING: Partial views ], actions: [ - CreateTexture(Id(0, 1, Empty), ( + CreateTexture(Id(0, 1), ( label: Some("Sampled Texture"), size: ( width: 64, @@ -31,12 +31,12 @@ view_formats: [], )), CreateTextureView( - id: Id(0, 1, Empty), - parent_id: Id(0, 1, Empty), + id: Id(0, 1), + parent_id: Id(0, 1), desc: (), ), CreateBuffer( - Id(0, 1, Empty), + Id(0, 1), ( label: Some("Sampled Texture Buffer"), size: 16384, @@ -44,7 +44,7 @@ mapped_at_creation: false, ), ), - CreateTexture(Id(1, 1, Empty), ( + CreateTexture(Id(1, 1), ( label: Some("Storage Texture"), size: ( width: 64, @@ -58,12 +58,12 @@ view_formats: [], )), CreateTextureView( - id: Id(1, 1, Empty), - parent_id: Id(1, 1, Empty), + id: Id(1, 1), + parent_id: Id(1, 1), desc: (), ), CreateBuffer( - Id(1, 1, Empty), + Id(1, 1), ( label: Some("Storage Texture Buffer"), size: 16384, @@ -73,7 +73,7 @@ ), - CreateBindGroupLayout(Id(0, 1, Empty), ( + CreateBindGroupLayout(Id(0, 1), ( label: None, entries: [ ( @@ -98,29 +98,29 @@ ), ], )), - CreateBindGroup(Id(0, 1, Empty), ( + CreateBindGroup(Id(0, 1), ( label: None, - layout: Id(0, 1, Empty), + layout: Id(0, 1), entries: [ ( binding: 0, - resource: TextureView(Id(0, 1, Empty)), + resource: TextureView(Id(0, 1)), ), ( binding: 1, - resource: TextureView(Id(1, 1, Empty)), + resource: TextureView(Id(1, 1)), ), ], )), - CreatePipelineLayout(Id(0, 1, Empty), ( + CreatePipelineLayout(Id(0, 1), ( label: None, bind_group_layouts: [ - Id(0, 1, Empty), + Id(0, 1), ], push_constant_ranges: [], )), CreateShaderModule( - id: Id(0, 1, Empty), + id: Id(0, 1), desc: ( label: None, flags: (bits: 3), @@ -128,12 +128,12 @@ data: "zero-init-texture-binding.wgsl", ), CreateComputePipeline( - id: Id(0, 1, Empty), + id: Id(0, 1), desc: ( label: None, - layout: Some(Id(0, 1, Empty)), + layout: Some(Id(0, 1)), stage: ( - module: Id(0, 1, Empty), + module: Id(0, 1), entry_point: None, constants: {}, zero_initialize_workgroup_memory: true, @@ -146,11 +146,11 @@ RunComputePass( base: ( commands: [ - SetPipeline(Id(0, 1, Empty)), + SetPipeline(Id(0, 1)), SetBindGroup( index: 0, num_dynamic_offsets: 0, - bind_group_id: Some(Id(0, 1, Empty)), + bind_group_id: Some(Id(0, 1)), ), Dispatch((4, 1, 1)), ], @@ -161,12 +161,12 @@ ), CopyTextureToBuffer( src: ( - texture: Id(0, 1, Empty), + texture: Id(0, 1), mip_level: 0, array_layer: 0, ), dst: ( - buffer: Id(0, 1, Empty), + buffer: Id(0, 1), layout: ( offset: 0, bytes_per_row: Some(256), @@ -180,12 +180,12 @@ ), CopyTextureToBuffer( src: ( - texture: Id(1, 1, Empty), + texture: Id(1, 1), mip_level: 0, array_layer: 0, ), dst: ( - buffer: Id(1, 1, Empty), + buffer: Id(1, 1), layout: ( offset: 0, bytes_per_row: Some(256), diff --git a/player/tests/data/zero-init-texture-copytobuffer.ron b/player/tests/data/zero-init-texture-copytobuffer.ron index 599ddbd67..eae95aaae 100644 --- a/player/tests/data/zero-init-texture-copytobuffer.ron +++ b/player/tests/data/zero-init-texture-copytobuffer.ron @@ -10,7 +10,7 @@ // MISSING: Partial copies ], actions: [ - CreateTexture(Id(0, 1, Empty), ( + CreateTexture(Id(0, 1), ( label: Some("Copy To Buffer Texture"), size: ( width: 64, @@ -24,7 +24,7 @@ view_formats: [], )), CreateBuffer( - Id(0, 1, Empty), + Id(0, 1), ( label: Some("Copy to Buffer Buffer"), size: 16384, @@ -35,12 +35,12 @@ Submit(1, [ CopyTextureToBuffer( src: ( - texture: Id(0, 1, Empty), + texture: Id(0, 1), mip_level: 0, array_layer: 0, ), dst: ( - buffer: Id(0, 1, Empty), + buffer: Id(0, 1), layout: ( offset: 0, bytes_per_row: Some(256), diff --git a/player/tests/data/zero-init-texture-rendertarget.ron b/player/tests/data/zero-init-texture-rendertarget.ron index ec844fe07..adbb86962 100644 --- a/player/tests/data/zero-init-texture-rendertarget.ron +++ b/player/tests/data/zero-init-texture-rendertarget.ron @@ -10,7 +10,7 @@ // MISSING: Partial view. ], actions: [ - CreateTexture(Id(0, 1, Empty), ( + CreateTexture(Id(0, 1), ( label: Some("Render Target Texture"), size: ( width: 64, @@ -24,12 +24,12 @@ view_formats: [], )), CreateTextureView( - id: Id(0, 1, Empty), - parent_id: Id(0, 1, Empty), + id: Id(0, 1), + parent_id: Id(0, 1), desc: (), ), CreateBuffer( - Id(0, 1, Empty), + Id(0, 1), ( label: Some("Render Target Buffer"), size: 16384, @@ -48,7 +48,7 @@ ), target_colors: [ Some(( - view: Id(0, 1, Empty), + view: Id(0, 1), resolve_target: None, channel: ( load_op: load, @@ -64,12 +64,12 @@ ), CopyTextureToBuffer( src: ( - texture: Id(0, 1, Empty), + texture: Id(0, 1), mip_level: 0, array_layer: 0, ), dst: ( - buffer: Id(0, 1, Empty), + buffer: Id(0, 1), layout: ( offset: 0, bytes_per_row: Some(256), diff --git a/player/tests/test.rs b/player/tests/test.rs index 3b26a202d..ec96f5446 100644 --- a/player/tests/test.rs +++ b/player/tests/test.rs @@ -105,9 +105,8 @@ impl Test<'_> { adapter: wgc::id::AdapterId, test_num: u32, ) { - let backend = adapter.backend(); - let device_id = wgc::id::Id::zip(test_num, 0, backend); - let queue_id = wgc::id::Id::zip(test_num, 0, backend); + let device_id = wgc::id::Id::zip(test_num, 1); + let queue_id = wgc::id::Id::zip(test_num, 1); let res = global.adapter_request_device( adapter, &wgt::DeviceDescriptor { @@ -137,7 +136,7 @@ impl Test<'_> { } println!("\t\t\tMapping..."); for expect in &self.expectations { - let buffer = wgc::id::Id::zip(expect.buffer.index, expect.buffer.epoch, backend); + let buffer = wgc::id::Id::zip(expect.buffer.index, expect.buffer.epoch); global .buffer_map_async( buffer, @@ -160,7 +159,7 @@ impl Test<'_> { for expect in self.expectations { println!("\t\t\tChecking {}", expect.name); - let buffer = wgc::id::Id::zip(expect.buffer.index, expect.buffer.epoch, backend); + let buffer = wgc::id::Id::zip(expect.buffer.index, expect.buffer.epoch); let (ptr, size) = global .buffer_get_mapped_range( buffer, @@ -237,7 +236,8 @@ impl Corpus { force_fallback_adapter: false, compatible_surface: None, }, - wgc::instance::AdapterInputs::IdSet(&[wgc::id::Id::zip(0, 0, backend)]), + wgt::Backends::from(backend), + Some(wgc::id::Id::zip(0, 1)), ) { Ok(adapter) => adapter, Err(_) => continue, @@ -247,7 +247,7 @@ impl Corpus { let supported_features = global.adapter_features(adapter); let downlevel_caps = global.adapter_downlevel_capabilities(adapter); - let test = Test::load(dir.join(test_path), adapter.backend()); + let test = Test::load(dir.join(test_path), backend); if !supported_features.contains(test.features) { println!( "\t\tSkipped due to missing features {:?}", diff --git a/wgpu-core/src/device/global.rs b/wgpu-core/src/device/global.rs index 4b7143e55..10b82a73a 100644 --- a/wgpu-core/src/device/global.rs +++ b/wgpu-core/src/device/global.rs @@ -104,7 +104,7 @@ impl Global { profiling::scope!("Device::create_buffer"); let hub = &self.hub; - let fid = hub.buffers.prepare(device_id.backend(), id_in); + let fid = hub.buffers.prepare(id_in); let error = 'error: { let device = self.hub.devices.get(device_id); @@ -175,21 +175,19 @@ impl Global { /// [`wgpu_types::BufferUsages`]: wgt::BufferUsages pub fn create_buffer_error( &self, - backend: wgt::Backend, id_in: Option, desc: &resource::BufferDescriptor, ) { - let fid = self.hub.buffers.prepare(backend, id_in); + let fid = self.hub.buffers.prepare(id_in); fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string()))); } pub fn create_render_bundle_error( &self, - backend: wgt::Backend, id_in: Option, desc: &command::RenderBundleDescriptor, ) { - let fid = self.hub.render_bundles.prepare(backend, id_in); + let fid = self.hub.render_bundles.prepare(id_in); fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string()))); } @@ -198,11 +196,10 @@ impl Global { /// See `create_buffer_error` for more context and explanation. pub fn create_texture_error( &self, - backend: wgt::Backend, id_in: Option, desc: &resource::TextureDescriptor, ) { - let fid = self.hub.textures.prepare(backend, id_in); + let fid = self.hub.textures.prepare(id_in); fid.assign(Fallible::Invalid(Arc::new(desc.label.to_string()))); } @@ -311,7 +308,7 @@ impl Global { let hub = &self.hub; - let fid = hub.textures.prepare(device_id.backend(), id_in); + let fid = hub.textures.prepare(id_in); let error = 'error: { let device = self.hub.devices.get(device_id); @@ -354,7 +351,7 @@ impl Global { let hub = &self.hub; - let fid = hub.textures.prepare(device_id.backend(), id_in); + let fid = hub.textures.prepare(id_in); let error = 'error: { let device = self.hub.devices.get(device_id); @@ -398,7 +395,7 @@ impl Global { profiling::scope!("Device::create_buffer"); let hub = &self.hub; - let fid = hub.buffers.prepare(A::VARIANT, id_in); + let fid = hub.buffers.prepare(id_in); let device = self.hub.devices.get(device_id); @@ -458,7 +455,7 @@ impl Global { let hub = &self.hub; - let fid = hub.texture_views.prepare(texture_id.backend(), id_in); + let fid = hub.texture_views.prepare(id_in); let error = 'error: { let texture = match hub.textures.get(texture_id).get() { @@ -522,7 +519,7 @@ impl Global { profiling::scope!("Device::create_sampler"); let hub = &self.hub; - let fid = hub.samplers.prepare(device_id.backend(), id_in); + let fid = hub.samplers.prepare(id_in); let error = 'error: { let device = self.hub.devices.get(device_id); @@ -575,7 +572,7 @@ impl Global { profiling::scope!("Device::create_bind_group_layout"); let hub = &self.hub; - let fid = hub.bind_group_layouts.prepare(device_id.backend(), id_in); + let fid = hub.bind_group_layouts.prepare(id_in); let error = 'error: { let device = self.hub.devices.get(device_id); @@ -647,7 +644,7 @@ impl Global { profiling::scope!("Device::create_pipeline_layout"); let hub = &self.hub; - let fid = hub.pipeline_layouts.prepare(device_id.backend(), id_in); + let fid = hub.pipeline_layouts.prepare(id_in); let error = 'error: { let device = self.hub.devices.get(device_id); @@ -715,7 +712,7 @@ impl Global { profiling::scope!("Device::create_bind_group"); let hub = &self.hub; - let fid = hub.bind_groups.prepare(device_id.backend(), id_in); + let fid = hub.bind_groups.prepare(id_in); let error = 'error: { let device = self.hub.devices.get(device_id); @@ -877,7 +874,7 @@ impl Global { profiling::scope!("Device::create_shader_module"); let hub = &self.hub; - let fid = hub.shader_modules.prepare(device_id.backend(), id_in); + let fid = hub.shader_modules.prepare(id_in); let error = 'error: { let device = self.hub.devices.get(device_id); @@ -949,7 +946,7 @@ impl Global { profiling::scope!("Device::create_shader_module"); let hub = &self.hub; - let fid = hub.shader_modules.prepare(device_id.backend(), id_in); + let fid = hub.shader_modules.prepare(id_in); let error = 'error: { let device = self.hub.devices.get(device_id); @@ -1006,10 +1003,9 @@ impl Global { profiling::scope!("Device::create_command_encoder"); let hub = &self.hub; - let fid = hub.command_buffers.prepare( - device_id.backend(), - id_in.map(|id| id.into_command_buffer_id()), - ); + let fid = hub + .command_buffers + .prepare(id_in.map(|id| id.into_command_buffer_id())); let device = self.hub.devices.get(device_id); @@ -1072,9 +1068,7 @@ impl Global { let hub = &self.hub; - let fid = hub - .render_bundles - .prepare(bundle_encoder.parent().backend(), id_in); + let fid = hub.render_bundles.prepare(id_in); let error = 'error: { let device = self.hub.devices.get(bundle_encoder.parent()); @@ -1133,7 +1127,7 @@ impl Global { profiling::scope!("Device::create_query_set"); let hub = &self.hub; - let fid = hub.query_sets.prepare(device_id.backend(), id_in); + let fid = hub.query_sets.prepare(id_in); let error = 'error: { let device = self.hub.devices.get(device_id); @@ -1194,7 +1188,7 @@ impl Global { let missing_implicit_pipeline_ids = desc.layout.is_none() && id_in.is_some() && implicit_pipeline_ids.is_none(); - let fid = hub.render_pipelines.prepare(device_id.backend(), id_in); + let fid = hub.render_pipelines.prepare(id_in); let implicit_context = implicit_pipeline_ids.map(|ipi| ipi.prepare(hub)); let error = 'error: { @@ -1378,7 +1372,7 @@ impl Global { ) { let hub = &self.hub; - let fid = hub.bind_group_layouts.prepare(pipeline_id.backend(), id_in); + let fid = hub.bind_group_layouts.prepare(id_in); let error = 'error: { let pipeline = match hub.render_pipelines.get(pipeline_id).get() { @@ -1431,7 +1425,7 @@ impl Global { let missing_implicit_pipeline_ids = desc.layout.is_none() && id_in.is_some() && implicit_pipeline_ids.is_none(); - let fid = hub.compute_pipelines.prepare(device_id.backend(), id_in); + let fid = hub.compute_pipelines.prepare(id_in); let implicit_context = implicit_pipeline_ids.map(|ipi| ipi.prepare(hub)); let error = 'error: { @@ -1562,7 +1556,7 @@ impl Global { ) { let hub = &self.hub; - let fid = hub.bind_group_layouts.prepare(pipeline_id.backend(), id_in); + let fid = hub.bind_group_layouts.prepare(id_in); let error = 'error: { let pipeline = match hub.compute_pipelines.get(pipeline_id).get() { @@ -1616,7 +1610,7 @@ impl Global { let hub = &self.hub; - let fid = hub.pipeline_caches.prepare(device_id.backend(), id_in); + let fid = hub.pipeline_caches.prepare(id_in); let error: pipeline::CreatePipelineCacheError = 'error: { let device = self.hub.devices.get(device_id); @@ -1881,7 +1875,7 @@ impl Global { // // https://github.com/gfx-rs/wgpu/issues/4105 - let surface_raw = surface.raw(device_id.backend()).unwrap(); + let surface_raw = surface.raw(device.backend()).unwrap(); match unsafe { surface_raw.configure(device.raw(), &hal_config) } { Ok(()) => (), Err(error) => { @@ -1963,7 +1957,6 @@ impl Global { /// submissions still in flight. fn poll_all_devices_of_api( &self, - backend: wgt::Backend, force_wait: bool, closures: &mut UserClosures, ) -> Result { @@ -1974,7 +1967,7 @@ impl Global { { let device_guard = hub.devices.read(); - for (_id, device) in device_guard.iter(backend) { + for (_id, device) in device_guard.iter() { let maintain = if force_wait { wgt::Maintain::Wait } else { @@ -2004,28 +1997,7 @@ impl Global { pub fn poll_all_devices(&self, force_wait: bool) -> Result { api_log!("poll_all_devices"); let mut closures = UserClosures::default(); - let mut all_queue_empty = true; - - #[cfg(vulkan)] - { - all_queue_empty &= - self.poll_all_devices_of_api(wgt::Backend::Vulkan, force_wait, &mut closures)?; - } - #[cfg(metal)] - { - all_queue_empty &= - self.poll_all_devices_of_api(wgt::Backend::Metal, force_wait, &mut closures)?; - } - #[cfg(dx12)] - { - all_queue_empty &= - self.poll_all_devices_of_api(wgt::Backend::Dx12, force_wait, &mut closures)?; - } - #[cfg(gles)] - { - all_queue_empty &= - self.poll_all_devices_of_api(wgt::Backend::Gl, force_wait, &mut closures)?; - } + let all_queue_empty = self.poll_all_devices_of_api(force_wait, &mut closures)?; closures.fire(); diff --git a/wgpu-core/src/device/mod.rs b/wgpu-core/src/device/mod.rs index 97ce639fe..959f3cada 100644 --- a/wgpu-core/src/device/mod.rs +++ b/wgpu-core/src/device/mod.rs @@ -457,16 +457,12 @@ pub struct ImplicitPipelineIds<'a> { impl ImplicitPipelineIds<'_> { fn prepare(self, hub: &Hub) -> ImplicitPipelineContext { - let backend = self.root_id.backend(); ImplicitPipelineContext { - root_id: hub - .pipeline_layouts - .prepare(backend, Some(self.root_id)) - .id(), + root_id: hub.pipeline_layouts.prepare(Some(self.root_id)).id(), group_ids: self .group_ids .iter() - .map(|id_in| hub.bind_group_layouts.prepare(backend, Some(*id_in)).id()) + .map(|id_in| hub.bind_group_layouts.prepare(Some(*id_in)).id()) .collect(), } } diff --git a/wgpu-core/src/device/queue.rs b/wgpu-core/src/device/queue.rs index 1710c0591..f576b2412 100644 --- a/wgpu-core/src/device/queue.rs +++ b/wgpu-core/src/device/queue.rs @@ -444,7 +444,7 @@ impl Global { let staging_buffer = StagingBuffer::new(device, buffer_size)?; let ptr = unsafe { staging_buffer.ptr() }; - let fid = hub.staging_buffers.prepare(queue_id.backend(), id_in); + let fid = hub.staging_buffers.prepare(id_in); let id = fid.assign(staging_buffer); resource_log!("Queue::create_staging_buffer {id:?}"); diff --git a/wgpu-core/src/id.rs b/wgpu-core/src/id.rs index 19baa2e6f..76ea8e333 100644 --- a/wgpu-core/src/id.rs +++ b/wgpu-core/src/id.rs @@ -4,18 +4,25 @@ use std::{ fmt::{self, Debug}, hash::Hash, marker::PhantomData, + num::NonZeroU64, }; -use wgt::{Backend, WasmNotSendSync}; +use wgt::WasmNotSendSync; -type IdType = u64; -type ZippedIndex = Index; -type NonZeroId = std::num::NonZeroU64; - -const INDEX_BITS: usize = ZippedIndex::BITS as usize; -const EPOCH_BITS: usize = INDEX_BITS - BACKEND_BITS; -const BACKEND_BITS: usize = 3; -const BACKEND_SHIFT: usize = INDEX_BITS * 2 - BACKEND_BITS; -pub const EPOCH_MASK: u32 = (1 << (EPOCH_BITS)) - 1; +const _: () = { + if std::mem::size_of::() != 4 { + panic!() + } +}; +const _: () = { + if std::mem::size_of::() != 4 { + panic!() + } +}; +const _: () = { + if std::mem::size_of::() != 8 { + panic!() + } +}; /// The raw underlying representation of an identifier. #[repr(transparent)] @@ -30,50 +37,18 @@ pub const EPOCH_MASK: u32 = (1 << (EPOCH_BITS)) - 1; serde(from = "SerialId") )] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct RawId(NonZeroId); +pub struct RawId(NonZeroU64); impl RawId { - #[doc(hidden)] - #[inline] - pub fn from_non_zero(non_zero: NonZeroId) -> Self { - Self(non_zero) - } - - #[doc(hidden)] - #[inline] - pub fn into_non_zero(self) -> NonZeroId { - self.0 - } - /// Zip together an identifier and return its raw underlying representation. - pub fn zip(index: Index, epoch: Epoch, backend: Backend) -> RawId { - assert_eq!(0, epoch >> EPOCH_BITS); - assert_eq!(0, (index as IdType) >> INDEX_BITS); - let v = index as IdType - | ((epoch as IdType) << INDEX_BITS) - | ((backend as IdType) << BACKEND_SHIFT); - Self(NonZeroId::new(v).unwrap()) + pub fn zip(index: Index, epoch: Epoch) -> RawId { + let v = (index as u64) | ((epoch as u64) << 32); + Self(NonZeroU64::new(v).unwrap()) } /// Unzip a raw identifier into its components. - #[allow(trivial_numeric_casts)] - pub fn unzip(self) -> (Index, Epoch, Backend) { - ( - (self.0.get() as ZippedIndex) as Index, - (((self.0.get() >> INDEX_BITS) as ZippedIndex) & (EPOCH_MASK as ZippedIndex)) as Index, - self.backend(), - ) - } - - pub fn backend(self) -> Backend { - match self.0.get() >> (BACKEND_SHIFT) as u8 { - 0 => Backend::Empty, - 1 => Backend::Vulkan, - 2 => Backend::Metal, - 3 => Backend::Dx12, - 4 => Backend::Gl, - _ => unreachable!(), - } + pub fn unzip(self) -> (Index, Epoch) { + (self.0.get() as Index, (self.0.get() >> 32) as Epoch) } } @@ -116,20 +91,20 @@ pub struct Id(RawId, PhantomData); #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] enum SerialId { // The only variant forces RON to not ignore "Id" - Id(Index, Epoch, Backend), + Id(Index, Epoch), } impl From for SerialId { fn from(id: RawId) -> Self { - let (index, epoch, backend) = id.unzip(); - Self::Id(index, epoch, backend) + let (index, epoch) = id.unzip(); + Self::Id(index, epoch) } } impl From for RawId { fn from(id: SerialId) -> Self { match id { - SerialId::Id(index, epoch, backend) => RawId::zip(index, epoch, backend), + SerialId::Id(index, epoch) => RawId::zip(index, epoch), } } } @@ -150,29 +125,13 @@ where self.0 } - #[allow(dead_code)] - pub(crate) fn dummy(index: u32) -> Self { - Id::zip(index, 1, Backend::Empty) - } - - #[allow(dead_code)] - pub(crate) fn is_valid(&self) -> bool { - self.backend() != Backend::Empty - } - - /// Get the backend this identifier corresponds to. #[inline] - pub fn backend(self) -> Backend { - self.0.backend() + pub fn zip(index: Index, epoch: Epoch) -> Self { + Id(RawId::zip(index, epoch), PhantomData) } #[inline] - pub fn zip(index: Index, epoch: Epoch, backend: Backend) -> Self { - Id(RawId::zip(index, epoch, backend), PhantomData) - } - - #[inline] - pub fn unzip(self) -> (Index, Epoch, Backend) { + pub fn unzip(self) -> (Index, Epoch) { self.0.unzip() } } @@ -194,16 +153,8 @@ where T: Marker, { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let (index, epoch, backend) = self.unzip(); - let backend = match backend { - Backend::Empty => "_", - Backend::Vulkan => "vk", - Backend::Metal => "mtl", - Backend::Dx12 => "d3d12", - Backend::Gl => "gl", - Backend::BrowserWebGpu => "webgpu", - }; - write!(formatter, "Id({index},{epoch},{backend})")?; + let (index, epoch) = self.unzip(); + write!(formatter, "Id({index},{epoch})")?; Ok(()) } } @@ -326,43 +277,16 @@ impl CommandBufferId { } } -#[test] -fn test_id_backend() { - for &b in &[ - Backend::Empty, - Backend::Vulkan, - Backend::Metal, - Backend::Dx12, - Backend::Gl, - ] { - let id = Id::<()>::zip(1, 0, b); - let (_id, _epoch, backend) = id.unzip(); - assert_eq!(id.backend(), b); - assert_eq!(backend, b); - } -} - #[test] fn test_id() { - let last_index = ((1u64 << INDEX_BITS) - 1) as Index; - let indexes = [1, last_index / 2 - 1, last_index / 2 + 1, last_index]; - let epochs = [1, EPOCH_MASK / 2 - 1, EPOCH_MASK / 2 + 1, EPOCH_MASK]; - let backends = [ - Backend::Empty, - Backend::Vulkan, - Backend::Metal, - Backend::Dx12, - Backend::Gl, - ]; + let indexes = [0, Index::MAX / 2 - 1, Index::MAX / 2 + 1, Index::MAX]; + let epochs = [1, Epoch::MAX / 2 - 1, Epoch::MAX / 2 + 1, Epoch::MAX]; for &i in &indexes { for &e in &epochs { - for &b in &backends { - let id = Id::<()>::zip(i, e, b); - let (index, epoch, backend) = id.unzip(); - assert_eq!(index, i); - assert_eq!(epoch, e); - assert_eq!(backend, b); - } + let id = Id::<()>::zip(i, e); + let (index, epoch) = id.unzip(); + assert_eq!(index, i); + assert_eq!(epoch, e); } } } diff --git a/wgpu-core/src/identity.rs b/wgpu-core/src/identity.rs index c89731f7a..0493b9d2c 100644 --- a/wgpu-core/src/identity.rs +++ b/wgpu-core/src/identity.rs @@ -1,5 +1,3 @@ -use wgt::Backend; - use crate::{ id::{Id, Marker}, lock::{rank, Mutex}, @@ -52,7 +50,7 @@ impl IdentityValues { /// /// The backend is incorporated into the id, so that ids allocated with /// different `backend` values are always distinct. - pub fn alloc(&mut self, backend: Backend) -> Id { + pub fn alloc(&mut self) -> Id { assert!( self.id_source != IdSource::External, "Mix of internally allocated and externally provided IDs" @@ -61,12 +59,12 @@ impl IdentityValues { self.count += 1; match self.free.pop() { - Some((index, epoch)) => Id::zip(index, epoch + 1, backend), + Some((index, epoch)) => Id::zip(index, epoch + 1), None => { let index = self.next_index; self.next_index += 1; let epoch = 1; - Id::zip(index, epoch, backend) + Id::zip(index, epoch) } } } @@ -85,7 +83,7 @@ impl IdentityValues { /// Free `id`. It will never be returned from `alloc` again. pub fn release(&mut self, id: Id) { if let IdSource::Allocated = self.id_source { - let (index, epoch, _backend) = id.unzip(); + let (index, epoch) = id.unzip(); self.free.push((index, epoch)); } self.count -= 1; @@ -103,8 +101,8 @@ pub struct IdentityManager { } impl IdentityManager { - pub fn process(&self, backend: Backend) -> Id { - self.values.lock().alloc(backend) + pub fn process(&self) -> Id { + self.values.lock().alloc() } pub fn mark_as_used(&self, id: Id) -> Id { self.values.lock().mark_as_used(id) @@ -135,10 +133,10 @@ impl IdentityManager { fn test_epoch_end_of_life() { use crate::id; let man = IdentityManager::::new(); - let id1 = man.process(Backend::Empty); - assert_eq!(id1.unzip(), (0, 1, Backend::Empty)); + let id1 = man.process(); + assert_eq!(id1.unzip(), (0, 1)); man.free(id1); - let id2 = man.process(Backend::Empty); + let id2 = man.process(); // confirm that the epoch 1 is no longer re-used - assert_eq!(id2.unzip(), (0, 2, Backend::Empty)); + assert_eq!(id2.unzip(), (0, 2)); } diff --git a/wgpu-core/src/instance.rs b/wgpu-core/src/instance.rs index 014fbc7bc..581c5ce0d 100644 --- a/wgpu-core/src/instance.rs +++ b/wgpu-core/src/instance.rs @@ -1,13 +1,12 @@ use std::sync::Arc; use std::{borrow::Cow, collections::HashMap}; -use crate::hub::Hub; use crate::{ api_log, device::{queue::Queue, resource::Device, DeviceDescriptor, DeviceError}, global::Global, hal_api::HalApi, - id::{markers, AdapterId, DeviceId, Id, Marker, QueueId, SurfaceId}, + id::{markers, AdapterId, DeviceId, QueueId, SurfaceId}, lock::{rank, Mutex}, present::Presentation, resource::ResourceType, @@ -368,26 +367,6 @@ pub enum RequestDeviceError { UnsupportedFeature(wgt::Features), } -pub enum AdapterInputs<'a, M: Marker> { - IdSet(&'a [Id]), - Mask(Backends, fn(Backend) -> Option>), -} - -impl AdapterInputs<'_, M> { - fn find(&self, b: Backend) -> Option>> { - match *self { - Self::IdSet(ids) => Some(Some(ids.iter().find(|id| id.backend() == b).copied()?)), - Self::Mask(bits, ref fun) => { - if bits.contains(b.into()) { - Some(fun(b)) - } else { - None - } - } - } - } -} - #[derive(Clone, Debug, Error)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[non_exhaustive] @@ -467,7 +446,7 @@ impl Global { let id = self .surfaces - .prepare(Backend::Empty, id_in) // No specific backend for Surface, since it's not specific. + .prepare(id_in) // No specific backend for Surface, since it's not specific. .assign(Arc::new(surface)); Ok(id) } @@ -511,10 +490,7 @@ impl Global { surface_per_backend: std::iter::once((Backend::Metal, raw_surface)).collect(), }; - let id = self - .surfaces - .prepare(Backend::Metal, id_in) - .assign(Arc::new(surface)); + let id = self.surfaces.prepare(id_in).assign(Arc::new(surface)); Ok(id) } @@ -536,10 +512,7 @@ impl Global { surface_per_backend: std::iter::once((Backend::Dx12, surface)).collect(), }; - let id = self - .surfaces - .prepare(Backend::Dx12, id_in) - .assign(Arc::new(surface)); + let id = self.surfaces.prepare(id_in).assign(Arc::new(surface)); Ok(id) } @@ -607,178 +580,81 @@ impl Global { drop(surface) } - pub fn enumerate_adapters(&self, inputs: AdapterInputs) -> Vec { + pub fn enumerate_adapters(&self, backends: Backends) -> Vec { profiling::scope!("Instance::enumerate_adapters"); api_log!("Instance::enumerate_adapters"); - fn enumerate( - hub: &Hub, - backend: Backend, - instance: &dyn hal::DynInstance, - inputs: &AdapterInputs, - list: &mut Vec, - ) { - let Some(id_backend) = inputs.find(backend) else { - return; - }; - + let mut adapters = Vec::new(); + for (_, instance) in self + .instance + .instance_per_backend + .iter() + .filter(|(backend, _)| backends.contains(Backends::from(*backend))) + { profiling::scope!("enumerating", &*format!("{:?}", backend)); let hal_adapters = unsafe { instance.enumerate_adapters(None) }; for raw in hal_adapters { let adapter = Adapter::new(raw); log::info!("Adapter {:?}", adapter.raw.info); - let id = hub - .adapters - .prepare(backend, id_backend) - .assign(Arc::new(adapter)); - list.push(id); + let id = self.hub.adapters.prepare(None).assign(Arc::new(adapter)); + adapters.push(id); } } - - let mut adapters = Vec::new(); - for (backend, instance) in &self.instance.instance_per_backend { - enumerate( - &self.hub, - *backend, - instance.as_ref(), - &inputs, - &mut adapters, - ); - } adapters } - fn select( - &self, - backend: Backend, - selected: &mut usize, - new_id: Option, - mut list: Vec, - ) -> Option { - match selected.checked_sub(list.len()) { - Some(left) => { - *selected = left; - None - } - None => { - let adapter = Adapter::new(list.swap_remove(*selected)); - log::info!("Adapter {:?}", adapter.raw.info); - let id = self - .hub - .adapters - .prepare(backend, new_id) - .assign(Arc::new(adapter)); - Some(id) - } - } - } - pub fn request_adapter( &self, desc: &RequestAdapterOptions, - inputs: AdapterInputs, + backends: Backends, + id_in: Option, ) -> Result { profiling::scope!("Instance::request_adapter"); api_log!("Instance::request_adapter"); - fn gather( - backend: Backend, - instance: &Instance, - inputs: &AdapterInputs, - compatible_surface: Option<&Surface>, - force_software: bool, - device_types: &mut Vec, - ) -> (Option>, Vec) { - let id = inputs.find(backend); - match (id, instance.raw(backend)) { - (Some(id), Some(inst)) => { - let compatible_hal_surface = - compatible_surface.and_then(|surface| surface.raw(backend)); - let mut adapters = unsafe { inst.enumerate_adapters(compatible_hal_surface) }; - if force_software { - adapters.retain(|exposed| exposed.info.device_type == wgt::DeviceType::Cpu); - } - if let Some(surface) = compatible_surface { - adapters - .retain(|exposed| surface.get_capabilities_with_raw(exposed).is_ok()); - } - device_types.extend(adapters.iter().map(|ad| ad.info.device_type)); - (id, adapters) - } - _ => (None, Vec::new()), - } - } - let compatible_surface = desc.compatible_surface.map(|id| self.surfaces.get(id)); let compatible_surface = compatible_surface.as_ref().map(|surface| surface.as_ref()); - let mut device_types = Vec::new(); + let mut adapters = Vec::new(); - #[cfg(vulkan)] - let (id_vulkan, adapters_vk) = gather( - Backend::Vulkan, - &self.instance, - &inputs, - compatible_surface, - desc.force_fallback_adapter, - &mut device_types, - ); - #[cfg(metal)] - let (id_metal, adapters_metal) = gather( - Backend::Metal, - &self.instance, - &inputs, - compatible_surface, - desc.force_fallback_adapter, - &mut device_types, - ); - #[cfg(dx12)] - let (id_dx12, adapters_dx12) = gather( - Backend::Dx12, - &self.instance, - &inputs, - compatible_surface, - desc.force_fallback_adapter, - &mut device_types, - ); - #[cfg(gles)] - let (id_gl, adapters_gl) = gather( - Backend::Gl, - &self.instance, - &inputs, - compatible_surface, - desc.force_fallback_adapter, - &mut device_types, - ); - - if device_types.is_empty() { - return Err(RequestAdapterError::NotFound); - } - - let (mut integrated, mut discrete, mut virt, mut cpu, mut other) = - (None, None, None, None, None); - - for (i, ty) in device_types.into_iter().enumerate() { - match ty { - wgt::DeviceType::IntegratedGpu => { - integrated = integrated.or(Some(i)); - } - wgt::DeviceType::DiscreteGpu => { - discrete = discrete.or(Some(i)); - } - wgt::DeviceType::VirtualGpu => { - virt = virt.or(Some(i)); - } - wgt::DeviceType::Cpu => { - cpu = cpu.or(Some(i)); - } - wgt::DeviceType::Other => { - other = other.or(Some(i)); - } + for (backend, instance) in self + .instance + .instance_per_backend + .iter() + .filter(|(backend, _)| backends.contains(Backends::from(*backend))) + { + let compatible_hal_surface = + compatible_surface.and_then(|surface| surface.raw(*backend)); + let mut backend_adapters = + unsafe { instance.enumerate_adapters(compatible_hal_surface) }; + if desc.force_fallback_adapter { + backend_adapters.retain(|exposed| exposed.info.device_type == wgt::DeviceType::Cpu); } + if let Some(surface) = compatible_surface { + backend_adapters + .retain(|exposed| surface.get_capabilities_with_raw(exposed).is_ok()); + } + adapters.extend(backend_adapters); } - let preferred_gpu = match desc.power_preference { + match desc.power_preference { + PowerPreference::LowPower => { + sort(&mut adapters, true); + } + PowerPreference::HighPerformance => { + sort(&mut adapters, false); + } + PowerPreference::None => {} + }; + + fn sort(adapters: &mut [hal::DynExposedAdapter], prefer_integrated_gpu: bool) { + adapters.sort_by(|a, b| { + get_order(a.info.device_type, prefer_integrated_gpu) + .cmp(&get_order(b.info.device_type, prefer_integrated_gpu)) + }); + } + + fn get_order(device_type: wgt::DeviceType, prefer_integrated_gpu: bool) -> u8 { // Since devices of type "Other" might really be "Unknown" and come // from APIs like OpenGL that don't specify device type, Prefer more // Specific types over Other. @@ -786,42 +662,28 @@ impl Global { // This means that backends which do provide accurate device types // will be preferred if their device type indicates an actual // hardware GPU (integrated or discrete). - PowerPreference::LowPower => integrated.or(discrete).or(other).or(virt).or(cpu), - PowerPreference::HighPerformance => discrete.or(integrated).or(other).or(virt).or(cpu), - PowerPreference::None => { - let option_min = |a: Option, b: Option| { - if let (Some(a), Some(b)) = (a, b) { - Some(a.min(b)) - } else { - a.or(b) - } - }; - // Pick the lowest id of these types - option_min(option_min(discrete, integrated), other) + match device_type { + wgt::DeviceType::DiscreteGpu if prefer_integrated_gpu => 2, + wgt::DeviceType::IntegratedGpu if prefer_integrated_gpu => 1, + wgt::DeviceType::DiscreteGpu => 1, + wgt::DeviceType::IntegratedGpu => 2, + wgt::DeviceType::Other => 3, + wgt::DeviceType::VirtualGpu => 4, + wgt::DeviceType::Cpu => 5, } - }; + } - let mut selected = preferred_gpu.unwrap_or(0); - #[cfg(vulkan)] - if let Some(id) = self.select(Backend::Vulkan, &mut selected, id_vulkan, adapters_vk) { - return Ok(id); + if let Some(adapter) = adapters.into_iter().next() { + log::info!("Adapter {:?}", adapter.info); + let id = self + .hub + .adapters + .prepare(id_in) + .assign(Arc::new(Adapter::new(adapter))); + Ok(id) + } else { + Err(RequestAdapterError::NotFound) } - #[cfg(metal)] - if let Some(id) = self.select(Backend::Metal, &mut selected, id_metal, adapters_metal) { - return Ok(id); - } - #[cfg(dx12)] - if let Some(id) = self.select(Backend::Dx12, &mut selected, id_dx12, adapters_dx12) { - return Ok(id); - } - #[cfg(gles)] - if let Some(id) = self.select(Backend::Gl, &mut selected, id_gl, adapters_gl) { - return Ok(id); - } - let _ = selected; - - log::warn!("Some adapters are present, but enumerating them failed!"); - Err(RequestAdapterError::NotFound) } /// # Safety @@ -834,7 +696,7 @@ impl Global { ) -> AdapterId { profiling::scope!("Instance::create_adapter_from_hal"); - let fid = self.hub.adapters.prepare(hal_adapter.backend(), input); + let fid = self.hub.adapters.prepare(input); let id = fid.assign(Arc::new(Adapter::new(hal_adapter))); resource_log!("Created Adapter {:?}", id); @@ -901,9 +763,8 @@ impl Global { profiling::scope!("Adapter::request_device"); api_log!("Adapter::request_device"); - let backend = adapter_id.backend(); - let device_fid = self.hub.devices.prepare(backend, device_id_in); - let queue_fid = self.hub.queues.prepare(backend, queue_id_in); + let device_fid = self.hub.devices.prepare(device_id_in); + let queue_fid = self.hub.queues.prepare(queue_id_in); let adapter = self.hub.adapters.get(adapter_id); let (device, queue) = @@ -933,9 +794,8 @@ impl Global { ) -> Result<(DeviceId, QueueId), RequestDeviceError> { profiling::scope!("Global::create_device_from_hal"); - let backend = adapter_id.backend(); - let devices_fid = self.hub.devices.prepare(backend, device_id_in); - let queues_fid = self.hub.queues.prepare(backend, queue_id_in); + let devices_fid = self.hub.devices.prepare(device_id_in); + let queues_fid = self.hub.queues.prepare(queue_id_in); let adapter = self.hub.adapters.get(adapter_id); let (device, queue) = adapter.create_device_and_queue_from_hal( diff --git a/wgpu-core/src/present.rs b/wgpu-core/src/present.rs index 93297bf3f..c9d0124bf 100644 --- a/wgpu-core/src/present.rs +++ b/wgpu-core/src/present.rs @@ -131,7 +131,7 @@ impl Global { return Err(SurfaceError::NotConfigured); }; - let fid = hub.textures.prepare(device.backend(), texture_id_in); + let fid = hub.textures.prepare(texture_id_in); #[cfg(feature = "trace")] if let Some(ref mut trace) = *device.trace.lock() { diff --git a/wgpu-core/src/registry.rs b/wgpu-core/src/registry.rs index 6524a4df9..b3349235e 100644 --- a/wgpu-core/src/registry.rs +++ b/wgpu-core/src/registry.rs @@ -70,18 +70,14 @@ impl FutureId<'_, T> { } impl Registry { - pub(crate) fn prepare( - &self, - backend: wgt::Backend, - id_in: Option>, - ) -> FutureId { + pub(crate) fn prepare(&self, id_in: Option>) -> FutureId { FutureId { id: match id_in { Some(id_in) => { self.identity.mark_as_used(id_in); id_in } - None => self.identity.process(backend), + None => self.identity.process(), }, data: &self.storage, } @@ -154,7 +150,7 @@ mod tests { s.spawn(|| { for _ in 0..1000 { let value = Arc::new(TestData); - let new_id = registry.prepare(wgt::Backend::Empty, None); + let new_id = registry.prepare(None); let id = new_id.assign(value); registry.remove(id); } diff --git a/wgpu-core/src/storage.rs b/wgpu-core/src/storage.rs index 5a57782bf..593074875 100644 --- a/wgpu-core/src/storage.rs +++ b/wgpu-core/src/storage.rs @@ -1,7 +1,5 @@ use std::sync::Arc; -use wgt::Backend; - use crate::id::{Id, Marker}; use crate::resource::ResourceType; use crate::{Epoch, Index}; @@ -75,7 +73,7 @@ where T: StorageItem, { pub(crate) fn insert(&mut self, id: Id, value: T) { - let (index, epoch, _) = id.unzip(); + let (index, epoch) = id.unzip(); let index = index as usize; if index >= self.map.len() { self.map.resize_with(index + 1, || Element::Vacant); @@ -94,7 +92,7 @@ where } pub(crate) fn remove(&mut self, id: Id) -> T { - let (index, epoch, _) = id.unzip(); + let (index, epoch) = id.unzip(); match std::mem::replace(&mut self.map[index as usize], Element::Vacant) { Element::Occupied(value, storage_epoch) => { assert_eq!(epoch, storage_epoch); @@ -104,13 +102,13 @@ where } } - pub(crate) fn iter(&self, backend: Backend) -> impl Iterator, &T)> { + pub(crate) fn iter(&self) -> impl Iterator, &T)> { self.map .iter() .enumerate() .filter_map(move |(index, x)| match *x { Element::Occupied(ref value, storage_epoch) => { - Some((Id::zip(index as Index, storage_epoch, backend), value)) + Some((Id::zip(index as Index, storage_epoch), value)) } _ => None, }) @@ -128,7 +126,7 @@ where /// Get an owned reference to an item. /// Panics if there is an epoch mismatch, the entry is empty or in error. pub(crate) fn get(&self, id: Id) -> T { - let (index, epoch, _) = id.unzip(); + let (index, epoch) = id.unzip(); let (result, storage_epoch) = match self.map.get(index as usize) { Some(&Element::Occupied(ref v, epoch)) => (v.clone(), epoch), None | Some(&Element::Vacant) => panic!("{}[{:?}] does not exist", self.kind, id), diff --git a/wgpu/src/backend/wgpu_core.rs b/wgpu/src/backend/wgpu_core.rs index c5ba18cf6..37850c770 100644 --- a/wgpu/src/backend/wgpu_core.rs +++ b/wgpu/src/backend/wgpu_core.rs @@ -61,8 +61,7 @@ impl ContextWgpuCore { #[cfg(native)] pub fn enumerate_adapters(&self, backends: wgt::Backends) -> Vec { - self.0 - .enumerate_adapters(wgc::instance::AdapterInputs::Mask(backends, |_| None)) + self.0.enumerate_adapters(backends) } pub unsafe fn create_adapter_from_hal( @@ -589,7 +588,8 @@ impl crate::Context for ContextWgpuCore { surface.id }), }, - wgc::instance::AdapterInputs::Mask(wgt::Backends::all(), |_| None), + wgt::Backends::all(), + None, ); ready(id.ok()) }