diff --git a/Cargo.lock b/Cargo.lock index 5995767d0..0f3daee6a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -20,12 +20,6 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234" -[[package]] -name = "ahash" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6789e291be47ace86a60303502173d84af8327e3627ecf334356ee0f87a164c" - [[package]] name = "aho-corasick" version = "0.7.15" @@ -66,15 +60,6 @@ dependencies = [ "serde", ] -[[package]] -name = "ash" -version = "0.32.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ea56be8250318e64923c7e65b82a35b5c29dfb6dc1c7d1c0b288c4b1bbb084" -dependencies = [ - "libloading 0.7.0", -] - [[package]] name = "async-executor" version = "1.4.1" @@ -198,9 +183,6 @@ name = "cc" version = "1.0.62" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1770ced377336a88a67c473594ccc14eca6f4559217c34f64aac8f83d641b40" -dependencies = [ - "jobserver", -] [[package]] name = "cfg-if" @@ -456,17 +438,6 @@ dependencies = [ "lazy_static", ] -[[package]] -name = "d3d12" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "091ed1b25fe47c7ff129fc440c23650b6114f36aa00bc7212cc8041879294428" -dependencies = [ - "bitflags", - "libloading 0.7.0", - "winapi 0.3.9", -] - [[package]] name = "darling" version = "0.10.2" @@ -546,7 +517,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b11f15d1e3268f140f68d390637d5e76d849782d971ae7063e0da69fe9709a76" dependencies = [ - "libloading 0.6.5", + "libloading", ] [[package]] @@ -704,150 +675,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "gfx-auxil" -version = "0.9.0" -source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521" -dependencies = [ - "fxhash", - "gfx-hal", - "spirv_cross", -] - -[[package]] -name = "gfx-backend-dx11" -version = "0.8.0" -source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521" -dependencies = [ - "arrayvec", - "bitflags", - "gfx-auxil", - "gfx-hal", - "libloading 0.7.0", - "log", - "parking_lot", - "range-alloc", - "raw-window-handle", - "smallvec", - "spirv_cross", - "thunderdome", - "winapi 0.3.9", - "wio", -] - -[[package]] -name = "gfx-backend-dx12" -version = "0.8.0" -source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521" -dependencies = [ - "arrayvec", - "bit-set", - "bitflags", - "d3d12", - "gfx-auxil", - "gfx-hal", - "log", - "parking_lot", - "range-alloc", - "raw-window-handle", - "smallvec", - "spirv_cross", - "thunderdome", - "winapi 0.3.9", -] - -[[package]] -name = "gfx-backend-empty" -version = "0.8.0" -source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521" -dependencies = [ - "gfx-hal", - "log", - "raw-window-handle", -] - -[[package]] -name = "gfx-backend-gl" -version = "0.8.1" -source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521" -dependencies = [ - "arrayvec", - "bitflags", - "fxhash", - "gfx-auxil", - "gfx-hal", - "glow", - "js-sys", - "khronos-egl", - "libloading 0.7.0", - "log", - "naga", - "parking_lot", - "raw-window-handle", - "spirv_cross", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "gfx-backend-metal" -version = "0.8.1" -source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521" -dependencies = [ - "arrayvec", - "bitflags", - "block", - "cocoa-foundation", - "copyless", - "foreign-types", - "fxhash", - "gfx-auxil", - "gfx-hal", - "log", - "metal", - "naga", - "objc", - "parking_lot", - "profiling", - "range-alloc", - "raw-window-handle", - "spirv_cross", - "storage-map", -] - -[[package]] -name = "gfx-backend-vulkan" -version = "0.8.0" -source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521" -dependencies = [ - "arrayvec", - "ash", - "byteorder", - "core-graphics-types", - "gfx-hal", - "inplace_it", - "libloading 0.7.0", - "log", - "naga", - "objc", - "parking_lot", - "raw-window-handle", - "renderdoc-sys", - "smallvec", - "winapi 0.3.9", -] - -[[package]] -name = "gfx-hal" -version = "0.8.0" -source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521" -dependencies = [ - "bitflags", - "naga", - "raw-window-handle", - "thiserror", -] - [[package]] name = "gif" version = "0.11.2" @@ -858,65 +685,11 @@ dependencies = [ "weezl", ] -[[package]] -name = "glow" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b80b98efaa8a34fce11d60dd2ce2760d5d83c373cbcc73bb87c2a3a84a54108" -dependencies = [ - "js-sys", - "slotmap", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "gpu-alloc" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8159cab119e2c6947476a8b941d478c8de4a1ce050d92c55903f8d0192ccacda" -dependencies = [ - "bitflags", - "gpu-alloc-types", -] - -[[package]] -name = "gpu-alloc-types" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54804d0d6bc9d7f26db4eaec1ad10def69b599315f487d32c334a80d1efe67a5" -dependencies = [ - "bitflags", -] - -[[package]] -name = "gpu-descriptor" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8a70f1e87a3840ed6a3e99e02c2b861e4dbdf26f0d07e38f42ea5aff46cfce2" -dependencies = [ - "bitflags", - "gpu-descriptor-types", - "hashbrown", -] - -[[package]] -name = "gpu-descriptor-types" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "363e3677e55ad168fef68cf9de3a4a310b53124c5e784c53a1d70e92d23f2126" -dependencies = [ - "bitflags", -] - [[package]] name = "hashbrown" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04" -dependencies = [ - "ahash", -] [[package]] name = "hermit-abi" @@ -968,12 +741,6 @@ dependencies = [ "hashbrown", ] -[[package]] -name = "inplace_it" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90953f308a79fe6d62a4643e51f848fbfddcd05975a38e69fdf4ab86a7baf7ca" - [[package]] name = "instant" version = "0.1.8" @@ -1001,15 +768,6 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" -[[package]] -name = "jobserver" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c71313ebb9439f74b00d9d2dcec36440beaf57a6aa0623068441dd7cd81a7f2" -dependencies = [ - "libc", -] - [[package]] name = "jpeg-decoder" version = "0.1.22" @@ -1038,16 +796,6 @@ dependencies = [ "winapi-build", ] -[[package]] -name = "khronos-egl" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c2352bd1d0bceb871cb9d40f24360c8133c11d7486b68b5381c1dd1a32015e3" -dependencies = [ - "libc", - "libloading 0.7.0", -] - [[package]] name = "lazy_static" version = "1.4.0" @@ -1076,16 +824,6 @@ dependencies = [ "winapi 0.3.9", ] -[[package]] -name = "libloading" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f84d96438c15fcd6c3f244c8fce01d1e2b9c6b5623e9c711dc9286d8fc92d6a" -dependencies = [ - "cfg-if 1.0.0", - "winapi 0.3.9", -] - [[package]] name = "lock_api" version = "0.4.1" @@ -1154,20 +892,6 @@ dependencies = [ "autocfg", ] -[[package]] -name = "metal" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c12e48c737ee9a55e8bb2352bcde588f79ae308d3529ee888f7cc0f469b5777" -dependencies = [ - "bitflags", - "block", - "cocoa-foundation", - "foreign-types", - "log", - "objc", -] - [[package]] name = "miniz_oxide" version = "0.3.7" @@ -1431,16 +1155,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" dependencies = [ "malloc_buf", - "objc_exception", -] - -[[package]] -name = "objc_exception" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad970fb455818ad6cba4c122ad012fae53ae8b4795f86378bce65e4f6bab2ca4" -dependencies = [ - "cc", ] [[package]] @@ -1639,11 +1353,6 @@ dependencies = [ "rand_core", ] -[[package]] -name = "range-alloc" -version = "0.1.2" -source = "git+https://github.com/gfx-rs/gfx?rev=27a1dae3796d33d23812f2bb8c7e3b5aea18b521#27a1dae3796d33d23812f2bb8c7e3b5aea18b521" - [[package]] name = "raw-window-handle" version = "0.3.3" @@ -1702,12 +1411,6 @@ version = "0.6.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b181ba2dcf07aaccad5448e8ead58db5b742cf85dfe035e2227f137a539a189" -[[package]] -name = "renderdoc-sys" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1382d1f0a252c4bf97dc20d979a2fdd05b024acd7c2ed0f7595d7817666a157" - [[package]] name = "ron" version = "0.6.2" @@ -1815,12 +1518,6 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" -[[package]] -name = "slotmap" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c46a3482db8f247956e464d783693ece164ca056e6e67563ee5505bdb86452cd" - [[package]] name = "smallvec" version = "1.4.2" @@ -1846,17 +1543,6 @@ dependencies = [ "wayland-protocols", ] -[[package]] -name = "spirv_cross" -version = "0.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06db6bd7b6518f761593783e2896eefe55e90455efc5f44511078ce0426ed418" -dependencies = [ - "cc", - "js-sys", - "wasm-bindgen", -] - [[package]] name = "spirv_headers" version = "1.5.0" @@ -1867,15 +1553,6 @@ dependencies = [ "num-traits 0.2.14", ] -[[package]] -name = "storage-map" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "418bb14643aa55a7841d5303f72cf512cfb323b8cc221d51580500a1ca75206c" -dependencies = [ - "lock_api", -] - [[package]] name = "strsim" version = "0.9.3" @@ -1931,12 +1608,6 @@ dependencies = [ "lazy_static", ] -[[package]] -name = "thunderdome" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87b4947742c93ece24a0032141d9caa3d853752e694a57e35029dd2bd08673e0" - [[package]] name = "tiff" version = "0.6.1" @@ -2200,15 +1871,6 @@ dependencies = [ "cfg_aliases", "copyless", "fxhash", - "gfx-backend-dx11", - "gfx-backend-dx12", - "gfx-backend-empty", - "gfx-backend-gl", - "gfx-backend-metal", - "gfx-backend-vulkan", - "gfx-hal", - "gpu-alloc", - "gpu-descriptor", "log", "loom", "naga", @@ -2219,6 +1881,15 @@ dependencies = [ "serde", "smallvec", "thiserror", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-hal" +version = "0.1.0" +dependencies = [ + "bitflags", "wgpu-types", ] @@ -2306,15 +1977,6 @@ dependencies = [ "x11-dl", ] -[[package]] -name = "wio" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d129932f4644ac2396cb456385cbf9e63b5b30c6e8dc4820bdca4eb082037a5" -dependencies = [ - "winapi 0.3.9", -] - [[package]] name = "ws2_32-sys" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index 5ce16a92f..fa966a3a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,7 @@ members = [ "player", "wgpu", "wgpu-core", + "wgpu-hal", "wgpu-types", ] default-members = ["wgpu"] diff --git a/player/Cargo.toml b/player/Cargo.toml index 70b39a492..40c8c673b 100644 --- a/player/Cargo.toml +++ b/player/Cargo.toml @@ -13,7 +13,6 @@ license = "MPL-2.0" publish = false [features] -cross = ["wgc/cross"] [dependencies] env_logger = "0.8" diff --git a/player/src/lib.rs b/player/src/lib.rs index 91adf5e91..61b9219da 100644 --- a/player/src/lib.rs +++ b/player/src/lib.rs @@ -39,12 +39,12 @@ impl wgc::hub::IdentityHandlerFactory impl wgc::hub::GlobalIdentityHandlerFactory for IdentityPassThroughFactory {} pub trait GlobalPlay { - fn encode_commands( + fn encode_commands( &self, encoder: wgc::id::CommandEncoderId, commands: Vec, ) -> wgc::id::CommandBufferId; - fn process( + fn process( &self, device: wgc::id::DeviceId, action: trace::Action, @@ -54,7 +54,7 @@ pub trait GlobalPlay { } impl GlobalPlay for wgc::hub::Global { - fn encode_commands( + fn encode_commands( &self, encoder: wgc::id::CommandEncoderId, commands: Vec, @@ -68,33 +68,33 @@ impl GlobalPlay for wgc::hub::Global { dst_offset, size, } => self - .command_encoder_copy_buffer_to_buffer::( + .command_encoder_copy_buffer_to_buffer::( encoder, src, src_offset, dst, dst_offset, size, ) .unwrap(), trace::Command::CopyBufferToTexture { src, dst, size } => self - .command_encoder_copy_buffer_to_texture::(encoder, &src, &dst, &size) + .command_encoder_copy_buffer_to_texture::(encoder, &src, &dst, &size) .unwrap(), trace::Command::CopyTextureToBuffer { src, dst, size } => self - .command_encoder_copy_texture_to_buffer::(encoder, &src, &dst, &size) + .command_encoder_copy_texture_to_buffer::(encoder, &src, &dst, &size) .unwrap(), trace::Command::CopyTextureToTexture { src, dst, size } => self - .command_encoder_copy_texture_to_texture::(encoder, &src, &dst, &size) + .command_encoder_copy_texture_to_texture::(encoder, &src, &dst, &size) .unwrap(), trace::Command::ClearBuffer { dst, offset, size } => self - .command_encoder_clear_buffer::(encoder, dst, offset, size) + .command_encoder_clear_buffer::(encoder, dst, offset, size) .unwrap(), trace::Command::ClearImage { dst, subresource_range, } => self - .command_encoder_clear_image::(encoder, dst, &subresource_range) + .command_encoder_clear_image::(encoder, dst, &subresource_range) .unwrap(), trace::Command::WriteTimestamp { query_set_id, query_index, } => self - .command_encoder_write_timestamp::(encoder, query_set_id, query_index) + .command_encoder_write_timestamp::(encoder, query_set_id, query_index) .unwrap(), trace::Command::ResolveQuerySet { query_set_id, @@ -103,7 +103,7 @@ impl GlobalPlay for wgc::hub::Global { destination, destination_offset, } => self - .command_encoder_resolve_query_set::( + .command_encoder_resolve_query_set::( encoder, query_set_id, start_query, @@ -113,7 +113,7 @@ impl GlobalPlay for wgc::hub::Global { ) .unwrap(), trace::Command::RunComputePass { base } => { - self.command_encoder_run_compute_pass_impl::(encoder, base.as_ref()) + self.command_encoder_run_compute_pass_impl::(encoder, base.as_ref()) .unwrap(); } trace::Command::RunRenderPass { @@ -121,7 +121,7 @@ impl GlobalPlay for wgc::hub::Global { target_colors, target_depth_stencil, } => { - self.command_encoder_run_render_pass_impl::( + self.command_encoder_run_render_pass_impl::( encoder, base.as_ref(), &target_colors, @@ -132,14 +132,14 @@ impl GlobalPlay for wgc::hub::Global { } } let (cmd_buf, error) = self - .command_encoder_finish::(encoder, &wgt::CommandBufferDescriptor { label: None }); + .command_encoder_finish::(encoder, &wgt::CommandBufferDescriptor { label: None }); if let Some(e) = error { panic!("{:?}", e); } cmd_buf } - fn process( + fn process( &self, device: wgc::id::DeviceId, action: trace::Action, @@ -155,90 +155,90 @@ impl GlobalPlay for wgc::hub::Global { panic!("Unexpected SwapChain action: winit feature is not enabled") } A::CreateBuffer(id, desc) => { - self.device_maintain_ids::(device).unwrap(); - let (_, error) = self.device_create_buffer::(device, &desc, id); + self.device_maintain_ids::(device).unwrap(); + let (_, error) = self.device_create_buffer::(device, &desc, id); if let Some(e) = error { panic!("{:?}", e); } } A::FreeBuffer(id) => { - self.buffer_destroy::(id).unwrap(); + self.buffer_destroy::(id).unwrap(); } A::DestroyBuffer(id) => { - self.buffer_drop::(id, true); + self.buffer_drop::(id, true); } A::CreateTexture(id, desc) => { - self.device_maintain_ids::(device).unwrap(); - let (_, error) = self.device_create_texture::(device, &desc, id); + self.device_maintain_ids::(device).unwrap(); + let (_, error) = self.device_create_texture::(device, &desc, id); if let Some(e) = error { panic!("{:?}", e); } } A::FreeTexture(id) => { - self.texture_destroy::(id).unwrap(); + self.texture_destroy::(id).unwrap(); } A::DestroyTexture(id) => { - self.texture_drop::(id, true); + self.texture_drop::(id, true); } A::CreateTextureView { id, parent_id, desc, } => { - self.device_maintain_ids::(device).unwrap(); - let (_, error) = self.texture_create_view::(parent_id, &desc, id); + self.device_maintain_ids::(device).unwrap(); + let (_, error) = self.texture_create_view::(parent_id, &desc, id); if let Some(e) = error { panic!("{:?}", e); } } A::DestroyTextureView(id) => { - self.texture_view_drop::(id, true).unwrap(); + self.texture_view_drop::(id, true).unwrap(); } A::CreateSampler(id, desc) => { - self.device_maintain_ids::(device).unwrap(); - let (_, error) = self.device_create_sampler::(device, &desc, id); + self.device_maintain_ids::(device).unwrap(); + let (_, error) = self.device_create_sampler::(device, &desc, id); if let Some(e) = error { panic!("{:?}", e); } } A::DestroySampler(id) => { - self.sampler_drop::(id); + self.sampler_drop::(id); } A::GetSwapChainTexture { id, parent_id } => { - self.device_maintain_ids::(device).unwrap(); - self.swap_chain_get_current_texture_view::(parent_id, id) + self.device_maintain_ids::(device).unwrap(); + self.swap_chain_get_current_texture_view::(parent_id, id) .unwrap() .view_id .unwrap(); } A::CreateBindGroupLayout(id, desc) => { - let (_, error) = self.device_create_bind_group_layout::(device, &desc, id); + let (_, error) = self.device_create_bind_group_layout::(device, &desc, id); if let Some(e) = error { panic!("{:?}", e); } } A::DestroyBindGroupLayout(id) => { - self.bind_group_layout_drop::(id); + self.bind_group_layout_drop::(id); } A::CreatePipelineLayout(id, desc) => { - self.device_maintain_ids::(device).unwrap(); - let (_, error) = self.device_create_pipeline_layout::(device, &desc, id); + self.device_maintain_ids::(device).unwrap(); + let (_, error) = self.device_create_pipeline_layout::(device, &desc, id); if let Some(e) = error { panic!("{:?}", e); } } A::DestroyPipelineLayout(id) => { - self.pipeline_layout_drop::(id); + self.pipeline_layout_drop::(id); } A::CreateBindGroup(id, desc) => { - self.device_maintain_ids::(device).unwrap(); - let (_, error) = self.device_create_bind_group::(device, &desc, id); + self.device_maintain_ids::(device).unwrap(); + let (_, error) = self.device_create_bind_group::(device, &desc, id); if let Some(e) = error { panic!("{:?}", e); } } A::DestroyBindGroup(id) => { - self.bind_group_drop::(id); + self.bind_group_drop::(id); } A::CreateShaderModule { id, desc, data } => { let source = if data.ends_with(".wgsl") { @@ -253,20 +253,20 @@ impl GlobalPlay for wgc::hub::Global { .collect::>(); wgc::pipeline::ShaderModuleSource::SpirV(Cow::Owned(spv)) }; - let (_, error) = self.device_create_shader_module::(device, &desc, source, id); + let (_, error) = self.device_create_shader_module::(device, &desc, source, id); if let Some(e) = error { panic!("{:?}", e); } } A::DestroyShaderModule(id) => { - self.shader_module_drop::(id); + self.shader_module_drop::(id); } A::CreateComputePipeline { id, desc, implicit_context, } => { - self.device_maintain_ids::(device).unwrap(); + self.device_maintain_ids::(device).unwrap(); let implicit_ids = implicit_context .as_ref() @@ -275,20 +275,20 @@ impl GlobalPlay for wgc::hub::Global { group_ids: &ic.group_ids, }); let (_, error) = - self.device_create_compute_pipeline::(device, &desc, id, implicit_ids); + self.device_create_compute_pipeline::(device, &desc, id, implicit_ids); if let Some(e) = error { panic!("{:?}", e); } } A::DestroyComputePipeline(id) => { - self.compute_pipeline_drop::(id); + self.compute_pipeline_drop::(id); } A::CreateRenderPipeline { id, desc, implicit_context, } => { - self.device_maintain_ids::(device).unwrap(); + self.device_maintain_ids::(device).unwrap(); let implicit_ids = implicit_context .as_ref() @@ -297,18 +297,18 @@ impl GlobalPlay for wgc::hub::Global { group_ids: &ic.group_ids, }); let (_, error) = - self.device_create_render_pipeline::(device, &desc, id, implicit_ids); + self.device_create_render_pipeline::(device, &desc, id, implicit_ids); if let Some(e) = error { panic!("{:?}", e); } } A::DestroyRenderPipeline(id) => { - self.render_pipeline_drop::(id); + self.render_pipeline_drop::(id); } A::CreateRenderBundle { id, desc, base } => { let bundle = wgc::command::RenderBundleEncoder::new(&desc, device, Some(base)).unwrap(); - let (_, error) = self.render_bundle_encoder_finish::( + let (_, error) = self.render_bundle_encoder_finish::( bundle, &wgt::RenderBundleDescriptor { label: desc.label }, id, @@ -318,17 +318,17 @@ impl GlobalPlay for wgc::hub::Global { } } A::DestroyRenderBundle(id) => { - self.render_bundle_drop::(id); + self.render_bundle_drop::(id); } A::CreateQuerySet { id, desc } => { - self.device_maintain_ids::(device).unwrap(); - let (_, error) = self.device_create_query_set::(device, &desc, id); + self.device_maintain_ids::(device).unwrap(); + let (_, error) = self.device_create_query_set::(device, &desc, id); if let Some(e) = error { panic!("{:?}", e); } } A::DestroyQuerySet(id) => { - self.query_set_drop::(id); + self.query_set_drop::(id); } A::WriteBuffer { id, @@ -339,11 +339,11 @@ impl GlobalPlay for wgc::hub::Global { let bin = std::fs::read(dir.join(data)).unwrap(); let size = (range.end - range.start) as usize; if queued { - self.queue_write_buffer::(device, id, range.start, &bin) + self.queue_write_buffer::(device, id, range.start, &bin) .unwrap(); } else { - self.device_wait_for_buffer::(device, id).unwrap(); - self.device_set_buffer_sub_data::(device, id, range.start, &bin[..size]) + self.device_wait_for_buffer::(device, id).unwrap(); + self.device_set_buffer_sub_data::(device, id, range.start, &bin[..size]) .unwrap(); } } @@ -354,14 +354,14 @@ impl GlobalPlay for wgc::hub::Global { size, } => { let bin = std::fs::read(dir.join(data)).unwrap(); - self.queue_write_texture::(device, &to, &bin, &layout, &size) + self.queue_write_texture::(device, &to, &bin, &layout, &size) .unwrap(); } A::Submit(_index, ref commands) if commands.is_empty() => { - self.queue_submit::(device, &[]).unwrap(); + self.queue_submit::(device, &[]).unwrap(); } A::Submit(_index, commands) => { - let (encoder, error) = self.device_create_command_encoder::( + let (encoder, error) = self.device_create_command_encoder::( device, &wgt::CommandEncoderDescriptor { label: None }, comb_manager.alloc(device.backend()), @@ -369,8 +369,8 @@ impl GlobalPlay for wgc::hub::Global { if let Some(e) = error { panic!("{:?}", e); } - let cmdbuf = self.encode_commands::(encoder, commands); - self.queue_submit::(device, &[cmdbuf]).unwrap(); + let cmdbuf = self.encode_commands::(encoder, commands); + self.queue_submit::(device, &[cmdbuf]).unwrap(); } } } diff --git a/wgpu-core/Cargo.toml b/wgpu-core/Cargo.toml index 1772bd4d0..cb43a7983 100644 --- a/wgpu-core/Cargo.toml +++ b/wgpu-core/Cargo.toml @@ -13,8 +13,6 @@ license = "MPL-2.0" [features] default = [] -# Enable SPIRV-Cross -cross = ["gfx-backend-metal/cross", "gfx-backend-gl/cross"] # Enable API tracing trace = ["ron", "serde", "wgt/trace", "arrayvec/serde"] # Enable API replaying @@ -36,28 +34,6 @@ serde = { version = "1.0", features = ["serde_derive"], optional = true } smallvec = "1" thiserror = "1" -gpu-alloc = "0.4" -gpu-descriptor = "0.1" - -hal = { package = "gfx-hal", git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521" } -gfx-backend-empty = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521" } - -[target.'cfg(all(not(target_arch = "wasm32"), all(unix, not(target_os = "ios"), not(target_os = "macos"))))'.dependencies] -gfx-backend-vulkan = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521", features = ["naga"] } -gfx-backend-gl = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521" } - -[target.'cfg(all(not(target_arch = "wasm32"), any(target_os = "ios", target_os = "macos")))'.dependencies] -gfx-backend-metal = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521" } -#TODO: could also depend on gfx-backend-vulkan for Vulkan Portability - -[target.'cfg(all(not(target_arch = "wasm32"), windows))'.dependencies] -gfx-backend-dx12 = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521" } -gfx-backend-dx11 = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521" } -gfx-backend-vulkan = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521", features = ["naga"] } - -[target.'cfg(target_arch = "wasm32")'.dependencies] -gfx-backend-gl = { git = "https://github.com/gfx-rs/gfx", rev = "27a1dae3796d33d23812f2bb8c7e3b5aea18b521" } - [dependencies.naga] git = "https://github.com/gfx-rs/naga" tag = "gfx-25" @@ -68,6 +44,11 @@ path = "../wgpu-types" package = "wgpu-types" version = "0.8" +[dependencies.hal] +path = "../wgpu-hal" +package = "wgpu-hal" +version = "0.1" + [dev-dependencies] loom = "0.3" diff --git a/wgpu-core/src/binding_model.rs b/wgpu-core/src/binding_model.rs index 0a4fd65d6..4e1037f96 100644 --- a/wgpu-core/src/binding_model.rs +++ b/wgpu-core/src/binding_model.rs @@ -12,7 +12,7 @@ use crate::{ memory_init_tracker::MemoryInitTrackerAction, track::{TrackerSet, UsageConflict, DUMMY_SELECTOR}, validation::{MissingBufferUsageError, MissingTextureUsageError}, - FastHashMap, Label, LifeGuard, MultiRefCount, Stored, MAX_BIND_GROUPS, + FastHashMap, Label, LifeGuard, MultiRefCount, Stored, }; use arrayvec::ArrayVec; @@ -389,7 +389,7 @@ pub struct BindGroupLayoutDescriptor<'a> { pub(crate) type BindEntryMap = FastHashMap; #[derive(Debug)] -pub struct BindGroupLayout { +pub struct BindGroupLayout { pub(crate) raw: B::DescriptorSetLayout, pub(crate) device_id: Stored, pub(crate) multi_ref_count: MultiRefCount, @@ -401,7 +401,7 @@ pub struct BindGroupLayout { pub(crate) label: String, } -impl Resource for BindGroupLayout { +impl Resource for BindGroupLayout { const TYPE: &'static str = "BindGroupLayout"; fn life_guard(&self) -> &LifeGuard { @@ -498,15 +498,15 @@ pub struct PipelineLayoutDescriptor<'a> { } #[derive(Debug)] -pub struct PipelineLayout { +pub struct PipelineLayout { pub(crate) raw: B::PipelineLayout, pub(crate) device_id: Stored, pub(crate) life_guard: LifeGuard, - pub(crate) bind_group_layout_ids: ArrayVec<[Valid; MAX_BIND_GROUPS]>, + pub(crate) bind_group_layout_ids: ArrayVec<[Valid; hal::MAX_BIND_GROUPS]>, pub(crate) push_constant_ranges: ArrayVec<[wgt::PushConstantRange; SHADER_STAGE_COUNT]>, } -impl PipelineLayout { +impl PipelineLayout { /// Validate push constants match up with expected ranges. pub(crate) fn validate_push_constant_ranges( &self, @@ -586,7 +586,7 @@ impl PipelineLayout { } } -impl Resource for PipelineLayout { +impl Resource for PipelineLayout { const TYPE: &'static str = "PipelineLayout"; fn life_guard(&self) -> &LifeGuard { @@ -636,8 +636,8 @@ pub struct BindGroupDynamicBindingData { } #[derive(Debug)] -pub struct BindGroup { - pub(crate) raw: DescriptorSet, +pub struct BindGroup { + pub(crate) raw: DescriptorSet, pub(crate) device_id: Stored, pub(crate) layout_id: Valid, pub(crate) life_guard: LifeGuard, @@ -646,7 +646,7 @@ pub struct BindGroup { pub(crate) dynamic_binding_info: Vec, } -impl BindGroup { +impl BindGroup { pub(crate) fn validate_dynamic_bindings( &self, offsets: &[wgt::DynamicOffset], @@ -681,13 +681,13 @@ impl BindGroup { } } -impl Borrow<()> for BindGroup { +impl Borrow<()> for BindGroup { fn borrow(&self) -> &() { &DUMMY_SELECTOR } } -impl Resource for BindGroup { +impl Resource for BindGroup { const TYPE: &'static str = "BindGroup"; fn life_guard(&self) -> &LifeGuard { diff --git a/wgpu-core/src/command/allocator.rs b/wgpu-core/src/command/allocator.rs index 14b3507ef..03f6f707e 100644 --- a/wgpu-core/src/command/allocator.rs +++ b/wgpu-core/src/command/allocator.rs @@ -4,7 +4,7 @@ use super::{CommandBuffer, CommandEncoderStatus}; use crate::{ - device::DeviceError, hub::GfxBackend, id::DeviceId, track::TrackerSet, FastHashMap, + device::DeviceError, hub::HalApi, id::DeviceId, track::TrackerSet, FastHashMap, PrivateFeatures, Stored, SubmissionIndex, }; @@ -20,14 +20,14 @@ use std::thread; const GROW_AMOUNT: usize = 20; #[derive(Debug)] -struct CommandPool { +struct CommandPool { raw: B::CommandPool, total: usize, available: Vec, pending: Vec<(B::CommandBuffer, SubmissionIndex)>, } -impl CommandPool { +impl CommandPool { fn maintain(&mut self, last_done_index: SubmissionIndex) { for i in (0..self.pending.len()).rev() { if self.pending[i].1 <= last_done_index { @@ -72,31 +72,31 @@ impl CommandPool { } #[derive(Debug)] -struct Inner { - pools: FastHashMap>, +struct Inner { + pools: FastHashMap>, } #[derive(Debug)] -pub struct CommandAllocator { +pub struct CommandAllocator { queue_family: hal::queue::QueueFamilyId, internal_thread_id: thread::ThreadId, - inner: Mutex>, + inner: Mutex>, } -impl CommandAllocator { +impl CommandAllocator { #[allow(clippy::too_many_arguments)] pub(crate) fn allocate( &self, device_id: Stored, device: &B::Device, limits: wgt::Limits, - downlevel: wgt::DownlevelProperties, + downlevel: wgt::DownlevelCapabilities, features: wgt::Features, private_features: PrivateFeatures, label: &crate::Label, #[cfg(feature = "trace")] enable_tracing: bool, - ) -> Result, CommandAllocatorError> { - //debug_assert_eq!(device_id.backend(), B::VARIANT); + ) -> Result, CommandAllocatorError> { + //debug_assert_eq!(device_id.backend(), A::VARIANT); let thread_id = thread::current().id(); let mut inner = self.inner.lock(); @@ -130,7 +130,7 @@ impl CommandAllocator { status: CommandEncoderStatus::Recording, recorded_thread_id: thread_id, device_id, - trackers: TrackerSet::new(B::VARIANT), + trackers: TrackerSet::new(A::VARIANT), used_swap_chains: Default::default(), buffer_memory_init_actions: Default::default(), limits, @@ -150,7 +150,7 @@ impl CommandAllocator { } } -impl CommandAllocator { +impl CommandAllocator { pub fn new( queue_family: hal::queue::QueueFamilyId, device: &B::Device, @@ -190,7 +190,7 @@ impl CommandAllocator { self.allocate_for_thread_id(self.internal_thread_id) } - pub fn extend(&self, cmd_buf: &CommandBuffer) -> B::CommandBuffer { + pub fn extend(&self, cmd_buf: &CommandBuffer) -> B::CommandBuffer { self.allocate_for_thread_id(cmd_buf.recorded_thread_id) } @@ -203,7 +203,7 @@ impl CommandAllocator { .recycle(raw); } - pub fn discard(&self, mut cmd_buf: CommandBuffer) { + pub fn discard(&self, mut cmd_buf: CommandBuffer) { cmd_buf.trackers.clear(); let mut inner = self.inner.lock(); let pool = inner.pools.get_mut(&cmd_buf.recorded_thread_id).unwrap(); @@ -224,7 +224,7 @@ impl CommandAllocator { pub fn after_submit( &self, - cmd_buf: CommandBuffer, + cmd_buf: CommandBuffer, device: &B::Device, submit_index: SubmissionIndex, ) { diff --git a/wgpu-core/src/command/bind.rs b/wgpu-core/src/command/bind.rs index f24d0b96d..310cd3677 100644 --- a/wgpu-core/src/command/bind.rs +++ b/wgpu-core/src/command/bind.rs @@ -5,7 +5,7 @@ use crate::{ binding_model::{BindGroup, PipelineLayout}, device::SHADER_STAGE_COUNT, - hub::{GfxBackend, Storage}, + hub::{HalApi, Storage}, id::{BindGroupId, BindGroupLayoutId, PipelineLayoutId, Valid}, Stored, MAX_BIND_GROUPS, }; @@ -166,9 +166,9 @@ impl Binder { } } - pub(super) fn change_pipeline_layout<'a, B: GfxBackend>( + pub(super) fn change_pipeline_layout<'a, A: HalApi>( &'a mut self, - guard: &Storage, PipelineLayoutId>, + guard: &Storage, PipelineLayoutId>, new_id: Valid, ) -> (usize, &'a [EntryPayload]) { let old_id_opt = self.pipeline_layout_id.replace(new_id); @@ -187,15 +187,15 @@ impl Binder { (bind_range.start, &self.payloads[bind_range]) } - pub(super) fn assign_group<'a, B: GfxBackend>( + pub(super) fn assign_group<'a, A: HalApi>( &'a mut self, index: usize, bind_group_id: Valid, - bind_group: &BindGroup, + bind_group: &BindGroup, offsets: &[wgt::DynamicOffset], ) -> &'a [EntryPayload] { log::trace!("\tBinding [{}] = group {:?}", index, bind_group_id); - debug_assert_eq!(B::VARIANT, bind_group_id.0.backend()); + debug_assert_eq!(A::VARIANT, bind_group_id.0.backend()); let payload = &mut self.payloads[index]; payload.group_id = Some(Stored { diff --git a/wgpu-core/src/command/bundle.rs b/wgpu-core/src/command/bundle.rs index ea25c6efd..be1dcaa60 100644 --- a/wgpu-core/src/command/bundle.rs +++ b/wgpu-core/src/command/bundle.rs @@ -47,7 +47,7 @@ use crate::{ AttachmentData, Device, DeviceError, RenderPassContext, MAX_VERTEX_BUFFERS, SHADER_STAGE_COUNT, }, - hub::{GfxBackend, GlobalIdentityHandlerFactory, Hub, Resource, Storage, Token}, + hub::{GlobalIdentityHandlerFactory, HalApi, Hub, Resource, Storage, Token}, id, memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction}, resource::BufferUse, @@ -135,12 +135,12 @@ impl RenderBundleEncoder { self.parent_id } - pub(crate) fn finish( + pub(crate) fn finish( self, desc: &RenderBundleDescriptor, - device: &Device, - hub: &Hub, - token: &mut Token>, + device: &Device, + hub: &Hub, + token: &mut Token>, ) -> Result { let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(token); let (bind_group_guard, mut token) = hub.bind_groups.read(&mut token); @@ -565,16 +565,16 @@ impl RenderBundle { /// Note that the function isn't expected to fail, generally. /// All the validation has already been done by this point. /// The only failure condition is if some of the used buffers are destroyed. - pub(crate) unsafe fn execute( + pub(crate) unsafe fn execute( &self, cmd_buf: &mut B::CommandBuffer, pipeline_layout_guard: &Storage< - crate::binding_model::PipelineLayout, + crate::binding_model::PipelineLayout, id::PipelineLayoutId, >, - bind_group_guard: &Storage, id::BindGroupId>, - pipeline_guard: &Storage, id::RenderPipelineId>, - buffer_guard: &Storage, id::BufferId>, + bind_group_guard: &Storage, id::BindGroupId>, + pipeline_guard: &Storage, id::RenderPipelineId>, + buffer_guard: &Storage, id::BufferId>, ) -> Result<(), ExecutionError> { use hal::command::CommandBuffer as _; diff --git a/wgpu-core/src/command/clear.rs b/wgpu-core/src/command/clear.rs index 1698613dd..032b6b4a3 100644 --- a/wgpu-core/src/command/clear.rs +++ b/wgpu-core/src/command/clear.rs @@ -10,7 +10,7 @@ use crate::{ command::CommandBuffer, conv, device::all_buffer_stages, - hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Token}, + hub::{Global, GlobalIdentityHandlerFactory, HalApi, Token}, id::{BufferId, CommandEncoderId, TextureId}, memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction}, resource::{BufferUse, TextureUse}, @@ -48,7 +48,7 @@ pub enum ClearError { MissingCopyDstUsageFlag(Option, Option), #[error("texture lacks the aspects that were specified in the image subresource range. Texture has {texture_aspects:?}, specified was {subresource_range_aspects:?}")] MissingTextureAspect { - texture_aspects: hal::format::Aspects, + texture_aspects: hal::FormatAspect, subresource_range_aspects: TextureAspect, }, #[error("image subresource level range is outside of the texture's level range. texture range is {texture_level_range:?}, \ @@ -68,7 +68,7 @@ whereas subesource range specified start {subresource_base_array_layer} and coun } impl Global { - pub fn command_encoder_clear_buffer( + pub fn command_encoder_clear_buffer( &self, command_encoder_id: CommandEncoderId, dst: BufferId, @@ -77,7 +77,7 @@ impl Global { ) -> Result<(), ClearError> { profiling::scope!("CommandEncoder::fill_buffer"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token); let cmd_buf = CommandBuffer::get_encoder_mut(&mut *cmd_buf_guard, command_encoder_id) @@ -165,7 +165,7 @@ impl Global { Ok(()) } - pub fn command_encoder_clear_image( + pub fn command_encoder_clear_image( &self, command_encoder_id: CommandEncoderId, dst: TextureId, @@ -173,7 +173,7 @@ impl Global { ) -> Result<(), ClearError> { profiling::scope!("CommandEncoder::clear_image"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token); let cmd_buf = CommandBuffer::get_encoder_mut(&mut *cmd_buf_guard, command_encoder_id) @@ -200,8 +200,8 @@ impl Global { // Check if subresource aspects are valid. let aspects = match subresource_range.aspect { wgt::TextureAspect::All => dst_texture.aspects, - wgt::TextureAspect::DepthOnly => hal::format::Aspects::DEPTH, - wgt::TextureAspect::StencilOnly => hal::format::Aspects::STENCIL, + wgt::TextureAspect::DepthOnly => hal::FormatAspect::DEPTH, + wgt::TextureAspect::StencilOnly => hal::FormatAspect::STENCIL, }; if !dst_texture.aspects.contains(aspects) { return Err(ClearError::MissingTextureAspect { diff --git a/wgpu-core/src/command/compute.rs b/wgpu-core/src/command/compute.rs index 7a461d7c5..5e2cdb7fe 100644 --- a/wgpu-core/src/command/compute.rs +++ b/wgpu-core/src/command/compute.rs @@ -9,7 +9,7 @@ use crate::{ CommandEncoderError, CommandEncoderStatus, MapPassErr, PassErrorScope, QueryUseError, StateChange, }, - hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Storage, Token}, + hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token}, id, memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction}, resource::{Buffer, BufferUse, Texture}, @@ -214,13 +214,13 @@ impl State { Ok(()) } - fn flush_states( + fn flush_states( &mut self, raw_cmd_buf: &mut B::CommandBuffer, base_trackers: &mut TrackerSet, - bind_group_guard: &Storage, id::BindGroupId>, - buffer_guard: &Storage, id::BufferId>, - texture_guard: &Storage, id::TextureId>, + bind_group_guard: &Storage, id::BindGroupId>, + buffer_guard: &Storage, id::BufferId>, + texture_guard: &Storage, id::TextureId>, ) -> Result<(), UsageConflict> { for id in self.binder.list_active() { self.trackers.merge_extend(&bind_group_guard[id].used)?; @@ -246,16 +246,16 @@ impl State { // Common routines between render/compute impl Global { - pub fn command_encoder_run_compute_pass( + pub fn command_encoder_run_compute_pass( &self, encoder_id: id::CommandEncoderId, pass: &ComputePass, ) -> Result<(), ComputePassError> { - self.command_encoder_run_compute_pass_impl::(encoder_id, pass.base.as_ref()) + self.command_encoder_run_compute_pass_impl::(encoder_id, pass.base.as_ref()) } #[doc(hidden)] - pub fn command_encoder_run_compute_pass_impl( + pub fn command_encoder_run_compute_pass_impl( &self, encoder_id: id::CommandEncoderId, base: BasePassRef, @@ -263,7 +263,7 @@ impl Global { profiling::scope!("run_compute_pass", "CommandEncoder"); let scope = PassErrorScope::Pass(encoder_id); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token); @@ -308,7 +308,7 @@ impl Global { let mut state = State { binder: Binder::new(), pipeline: StateChange::new(), - trackers: StatefulTrackerSubset::new(B::VARIANT), + trackers: StatefulTrackerSubset::new(A::VARIANT), debug_scope_depth: 0, }; let mut temp_offsets = Vec::new(); diff --git a/wgpu-core/src/command/mod.rs b/wgpu-core/src/command/mod.rs index 5564873e3..1e0188c42 100644 --- a/wgpu-core/src/command/mod.rs +++ b/wgpu-core/src/command/mod.rs @@ -23,7 +23,7 @@ pub use self::transfer::*; use crate::{ device::{all_buffer_stages, all_image_stages}, - hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Storage, Token}, + hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token}, id, memory_init_tracker::MemoryInitTrackerAction, resource::{Buffer, Texture}, @@ -47,7 +47,7 @@ enum CommandEncoderStatus { } #[derive(Debug)] -pub struct CommandBuffer { +pub struct CommandBuffer { pub(crate) raw: Vec, status: CommandEncoderStatus, recorded_thread_id: ThreadId, @@ -56,7 +56,7 @@ pub struct CommandBuffer { pub(crate) used_swap_chains: SmallVec<[Stored; 1]>, pub(crate) buffer_memory_init_actions: Vec>, limits: wgt::Limits, - downlevel: wgt::DownlevelProperties, + downlevel: wgt::DownlevelCapabilities, private_features: PrivateFeatures, support_fill_buffer_texture: bool, has_labels: bool, @@ -66,7 +66,7 @@ pub struct CommandBuffer { pub(crate) label: String, } -impl CommandBuffer { +impl CommandBuffer { fn get_encoder_mut( storage: &mut Storage, id: id::CommandEncoderId, @@ -93,13 +93,13 @@ impl CommandBuffer { base: &mut TrackerSet, head_buffers: &ResourceTracker, head_textures: &ResourceTracker, - buffer_guard: &Storage, id::BufferId>, - texture_guard: &Storage, id::TextureId>, + buffer_guard: &Storage, id::BufferId>, + texture_guard: &Storage, id::TextureId>, ) { use hal::command::CommandBuffer as _; profiling::scope!("insert_barriers"); - debug_assert_eq!(B::VARIANT, base.backend()); + debug_assert_eq!(A::VARIANT, base.backend()); let buffer_barriers = base.buffers.merge_replace(head_buffers).map(|pending| { let buf = &buffer_guard[pending.id]; @@ -122,7 +122,7 @@ impl CommandBuffer { } } -impl crate::hub::Resource for CommandBuffer { +impl crate::hub::Resource for CommandBuffer { const TYPE: &'static str = "CommandBuffer"; fn life_guard(&self) -> &crate::LifeGuard { @@ -206,14 +206,14 @@ pub enum CommandEncoderError { } impl Global { - pub fn command_encoder_finish( + pub fn command_encoder_finish( &self, encoder_id: id::CommandEncoderId, _desc: &wgt::CommandBufferDescriptor, } -impl QueryResetMap { +impl QueryResetMap { pub fn new() -> Self { Self { map: FastHashMap::default(), @@ -35,7 +35,7 @@ impl QueryResetMap { pub fn use_query_set( &mut self, id: id::QuerySetId, - query_set: &QuerySet, + query_set: &QuerySet, query: u32, ) -> bool { let (index, epoch, _) = id.unzip(); @@ -50,7 +50,7 @@ impl QueryResetMap { pub fn reset_queries( self, cmd_buf_raw: &mut B::CommandBuffer, - query_set_storage: &Storage, id::QuerySetId>, + query_set_storage: &Storage, id::QuerySetId>, backend: wgt::Backend, ) -> Result<(), id::QuerySetId> { for (query_set_id, (state, epoch)) in self.map.into_iter() { @@ -161,13 +161,13 @@ pub enum ResolveError { }, } -impl QuerySet { +impl QuerySet { fn validate_query( &self, query_set_id: id::QuerySetId, query_type: SimplifiedQueryType, query_index: u32, - reset_state: Option<&mut QueryResetMap>, + reset_state: Option<&mut QueryResetMap>, ) -> Result, QueryUseError> { // We need to defer our resets because we are in a renderpass, add the usage to the reset map. if let Some(reset) = reset_state { @@ -192,7 +192,7 @@ impl QuerySet { }); } - let hal_query = hal::query::Query:: { + let hal_query = hal::query::Query:: { pool: &self.raw, id: query_index, }; @@ -205,7 +205,7 @@ impl QuerySet { cmd_buf_raw: &mut B::CommandBuffer, query_set_id: id::QuerySetId, query_index: u32, - reset_state: Option<&mut QueryResetMap>, + reset_state: Option<&mut QueryResetMap>, ) -> Result<(), QueryUseError> { let needs_reset = reset_state.is_none(); let hal_query = self.validate_query( @@ -231,7 +231,7 @@ impl QuerySet { cmd_buf_raw: &mut B::CommandBuffer, query_set_id: id::QuerySetId, query_index: u32, - reset_state: Option<&mut QueryResetMap>, + reset_state: Option<&mut QueryResetMap>, active_query: &mut Option<(id::QuerySetId, u32)>, ) -> Result<(), QueryUseError> { let needs_reset = reset_state.is_none(); @@ -261,16 +261,16 @@ impl QuerySet { } } -pub(super) fn end_pipeline_statistics_query( +pub(super) fn end_pipeline_statistics_query( cmd_buf_raw: &mut B::CommandBuffer, - storage: &Storage, id::QuerySetId>, + storage: &Storage, id::QuerySetId>, active_query: &mut Option<(id::QuerySetId, u32)>, ) -> Result<(), QueryUseError> { if let Some((query_set_id, query_index)) = active_query.take() { // We can unwrap here as the validity was validated when the active query was set let query_set = storage.get(query_set_id).unwrap(); - let hal_query = hal::query::Query:: { + let hal_query = hal::query::Query:: { pool: &query_set.raw, id: query_index, }; @@ -284,13 +284,13 @@ pub(super) fn end_pipeline_statistics_query( } impl Global { - pub fn command_encoder_write_timestamp( + pub fn command_encoder_write_timestamp( &self, command_encoder_id: id::CommandEncoderId, query_set_id: id::QuerySetId, query_index: u32, ) -> Result<(), QueryError> { - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token); @@ -321,7 +321,7 @@ impl Global { Ok(()) } - pub fn command_encoder_resolve_query_set( + pub fn command_encoder_resolve_query_set( &self, command_encoder_id: id::CommandEncoderId, query_set_id: id::QuerySetId, @@ -330,7 +330,7 @@ impl Global { destination: id::BufferId, destination_offset: BufferAddress, ) -> Result<(), QueryError> { - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token); diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index 974fe3ff5..cdca1aeee 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -15,7 +15,7 @@ use crate::{ AttachmentData, AttachmentDataVec, Device, FramebufferKey, RenderPassCompatibilityError, RenderPassContext, RenderPassKey, RenderPassLock, MAX_COLOR_TARGETS, MAX_VERTEX_BUFFERS, }, - hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Storage, Token}, + hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token}, id, memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction}, pipeline::PipelineFlags, @@ -122,14 +122,14 @@ pub struct RenderPassDepthStencilAttachment { } impl RenderPassDepthStencilAttachment { - fn is_read_only(&self, aspects: hal::format::Aspects) -> Result { - if aspects.contains(hal::format::Aspects::DEPTH) && !self.depth.read_only { + fn is_read_only(&self, aspects: hal::FormatAspect) -> Result { + if aspects.contains(hal::FormatAspect::DEPTH) && !self.depth.read_only { return Ok(false); } if (self.depth.load_op, self.depth.store_op) != (LoadOp::Load, StoreOp::Store) { return Err(RenderPassErrorInner::InvalidDepthOps); } - if aspects.contains(hal::format::Aspects::STENCIL) && !self.stencil.read_only { + if aspects.contains(hal::FormatAspect::STENCIL) && !self.stencil.read_only { return Ok(false); } if (self.stencil.load_op, self.stencil.store_op) != (LoadOp::Load, StoreOp::Store) { @@ -503,24 +503,26 @@ struct RenderAttachment<'a> { new_use: TextureUse, } -struct RenderPassInfo<'a, B: hal::Backend> { +type AttachmentDataVec = ArrayVec<[T; MAX_COLOR_TARGETS + MAX_COLOR_TARGETS + 1]>; + +struct RenderPassInfo<'a, A: hal::Api> { context: RenderPassContext, trackers: StatefulTrackerSubset, render_attachments: AttachmentDataVec>, used_swap_chain: Option>, is_ds_read_only: bool, extent: wgt::Extent3d, - _phantom: PhantomData, + _phantom: PhantomData, } -impl<'a, B: GfxBackend> RenderPassInfo<'a, B> { +impl<'a, A: HalApi> RenderPassInfo<'a, A> { fn start( - raw: &mut B::CommandBuffer, + raw: &mut A::CommandBuffer, color_attachments: &[RenderPassColorAttachment], depth_stencil_attachment: Option<&RenderPassDepthStencilAttachment>, - cmd_buf: &mut CommandBuffer, - device: &Device, - view_guard: &'a Storage, id::TextureViewId>, + cmd_buf: &mut CommandBuffer, + device: &Device, + view_guard: &'a Storage, id::TextureViewId>, ) -> Result { profiling::scope!("start", "RenderPassInfo"); let sample_count_limit = device.hal_limits.framebuffer_color_sample_counts; @@ -535,10 +537,10 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> { let mut attachment_type_name = ""; let mut extent = None; let mut sample_count = 0; - let mut depth_stencil_aspects = hal::format::Aspects::empty(); + let mut depth_stencil_aspects = hal::FormatAspect::empty(); let mut used_swap_chain = None::>; - let mut add_view = |view: &TextureView, type_name| { + let mut add_view = |view: &TextureView, type_name| { if let Some(ex) = extent { if ex != view.extent { return Err(RenderPassErrorInner::AttachmentsDimensionMismatch { @@ -572,7 +574,7 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> { add_view(view, "depth")?; depth_stencil_aspects = view.aspects; - if view.aspects.contains(hal::format::Aspects::COLOR) { + if view.aspects.contains(hal::FormatAspect::COLOR) { return Err(RenderPassErrorInner::InvalidDepthStencilAttachmentFormat( view.format, )); @@ -635,7 +637,7 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> { .map_err(|_| RenderPassErrorInner::InvalidAttachment(at.view))?; add_view(view, "color")?; - if !view.aspects.contains(hal::format::Aspects::COLOR) { + if !view.aspects.contains(hal::FormatAspect::COLOR) { return Err(RenderPassErrorInner::InvalidColorAttachmentFormat( view.format, )); @@ -656,10 +658,10 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> { }); let new_layout = - conv::map_texture_state(new_use, hal::format::Aspects::COLOR).1; + conv::map_texture_state(new_use, hal::FormatAspect::COLOR).1; let old_layout = match previous_use { Some(usage) => { - conv::map_texture_state(usage, hal::format::Aspects::COLOR).1 + conv::map_texture_state(usage, hal::FormatAspect::COLOR).1 } None => new_layout, }; @@ -725,10 +727,10 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> { }); let new_layout = - conv::map_texture_state(new_use, hal::format::Aspects::COLOR).1; + conv::map_texture_state(new_use, hal::FormatAspect::COLOR).1; let old_layout = match previous_use { Some(usage) => { - conv::map_texture_state(usage, hal::format::Aspects::COLOR).1 + conv::map_texture_state(usage, hal::FormatAspect::COLOR).1 } None => new_layout, }; @@ -964,7 +966,7 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> { Ok(Self { context, - trackers: StatefulTrackerSubset::new(B::VARIANT), + trackers: StatefulTrackerSubset::new(A::VARIANT), render_attachments, used_swap_chain, is_ds_read_only, @@ -975,7 +977,7 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> { fn finish( mut self, - texture_guard: &Storage, id::TextureId>, + texture_guard: &Storage, id::TextureId>, ) -> Result<(StatefulTrackerSubset, Option>), RenderPassErrorInner> { profiling::scope!("finish", "RenderPassInfo"); @@ -1017,12 +1019,12 @@ impl<'a, B: GfxBackend> RenderPassInfo<'a, B> { // Common routines between render/compute impl Global { - pub fn command_encoder_run_render_pass( + pub fn command_encoder_run_render_pass( &self, encoder_id: id::CommandEncoderId, pass: &RenderPass, ) -> Result<(), RenderPassError> { - self.command_encoder_run_render_pass_impl::( + self.command_encoder_run_render_pass_impl::( encoder_id, pass.base.as_ref(), &pass.color_targets, @@ -1031,7 +1033,7 @@ impl Global { } #[doc(hidden)] - pub fn command_encoder_run_render_pass_impl( + pub fn command_encoder_run_render_pass_impl( &self, encoder_id: id::CommandEncoderId, base: BasePassRef, @@ -1041,7 +1043,7 @@ impl Global { profiling::scope!("run_render_pass", "CommandEncoder"); let scope = PassErrorScope::Pass(encoder_id); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); diff --git a/wgpu-core/src/command/transfer.rs b/wgpu-core/src/command/transfer.rs index c63e907a9..3bd761164 100644 --- a/wgpu-core/src/command/transfer.rs +++ b/wgpu-core/src/command/transfer.rs @@ -8,7 +8,7 @@ use crate::{ command::{CommandBuffer, CommandEncoderError}, conv, device::{all_buffer_stages, all_image_stages}, - hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Storage, Token}, + hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token}, id::{BufferId, CommandEncoderId, TextureId}, memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction}, resource::{BufferUse, Texture, TextureErrorDimension, TextureUse}, @@ -105,10 +105,10 @@ pub enum CopyError { //TODO: we currently access each texture twice for a transfer, // once only to get the aspect flags, which is unfortunate. -pub(crate) fn texture_copy_view_to_hal( +pub(crate) fn texture_copy_view_to_hal( view: &ImageCopyTexture, size: &Extent3d, - texture_guard: &Storage, TextureId>, + texture_guard: &Storage, TextureId>, ) -> Result< ( hal::image::SubresourceLayers, @@ -325,7 +325,7 @@ pub(crate) fn validate_texture_copy_range( } impl Global { - pub fn command_encoder_copy_buffer_to_buffer( + pub fn command_encoder_copy_buffer_to_buffer( &self, command_encoder_id: CommandEncoderId, source: BufferId, @@ -339,7 +339,7 @@ impl Global { if source == destination { return Err(TransferError::SameSourceDestinationBuffer.into()); } - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token); @@ -465,7 +465,7 @@ impl Global { Ok(()) } - pub fn command_encoder_copy_buffer_to_texture( + pub fn command_encoder_copy_buffer_to_texture( &self, command_encoder_id: CommandEncoderId, source: &ImageCopyBuffer, @@ -474,7 +474,7 @@ impl Global { ) -> Result<(), CopyError> { profiling::scope!("copy_buffer_to_texture", "CommandEncoder"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token); let cmd_buf = CommandBuffer::get_encoder_mut(&mut *cmd_buf_guard, command_encoder_id)?; @@ -615,7 +615,7 @@ impl Global { Ok(()) } - pub fn command_encoder_copy_texture_to_buffer( + pub fn command_encoder_copy_texture_to_buffer( &self, command_encoder_id: CommandEncoderId, source: &ImageCopyTexture, @@ -624,7 +624,7 @@ impl Global { ) -> Result<(), CopyError> { profiling::scope!("copy_texture_to_buffer", "CommandEncoder"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token); let cmd_buf = CommandBuffer::get_encoder_mut(&mut *cmd_buf_guard, command_encoder_id)?; @@ -768,7 +768,7 @@ impl Global { Ok(()) } - pub fn command_encoder_copy_texture_to_texture( + pub fn command_encoder_copy_texture_to_texture( &self, command_encoder_id: CommandEncoderId, source: &ImageCopyTexture, @@ -777,7 +777,7 @@ impl Global { ) -> Result<(), CopyError> { profiling::scope!("copy_texture_to_texture", "CommandEncoder"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (mut cmd_buf_guard, mut token) = hub.command_buffers.write(&mut token); diff --git a/wgpu-core/src/conv.rs b/wgpu-core/src/conv.rs index 8ee4dc404..4fff746e6 100644 --- a/wgpu-core/src/conv.rs +++ b/wgpu-core/src/conv.rs @@ -2,547 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::{ - command::{LoadOp, PassChannel, StoreOp}, - pipeline::ColorStateError, - resource, PrivateFeatures, -}; - -use std::convert::TryInto; - -pub fn map_adapter_info( - info: hal::adapter::AdapterInfo, - backend: wgt::Backend, -) -> wgt::AdapterInfo { - use hal::adapter::DeviceType as Dt; - - wgt::AdapterInfo { - name: info.name, - vendor: info.vendor, - device: info.device, - device_type: match info.device_type { - Dt::Other => wgt::DeviceType::Other, - Dt::IntegratedGpu => wgt::DeviceType::IntegratedGpu, - Dt::DiscreteGpu => wgt::DeviceType::DiscreteGpu, - Dt::VirtualGpu => wgt::DeviceType::VirtualGpu, - Dt::Cpu => wgt::DeviceType::Cpu, - }, - backend, - } -} - -pub fn map_buffer_usage(usage: wgt::BufferUsage) -> (hal::buffer::Usage, hal::memory::Properties) { - use hal::buffer::Usage as U; - use hal::memory::Properties as P; - use wgt::BufferUsage as W; - - let mut hal_memory = P::empty(); - if usage.contains(W::MAP_READ) { - hal_memory |= P::CPU_VISIBLE | P::CPU_CACHED; - } - if usage.contains(W::MAP_WRITE) { - hal_memory |= P::CPU_VISIBLE; - } - - let mut hal_usage = U::empty(); - if usage.contains(W::COPY_SRC) { - hal_usage |= U::TRANSFER_SRC; - } - if usage.contains(W::COPY_DST) { - hal_usage |= U::TRANSFER_DST; - } - if usage.contains(W::INDEX) { - hal_usage |= U::INDEX; - } - if usage.contains(W::VERTEX) { - hal_usage |= U::VERTEX; - } - if usage.contains(W::UNIFORM) { - hal_usage |= U::UNIFORM; - } - if usage.contains(W::STORAGE) { - hal_usage |= U::STORAGE; - } - if usage.contains(W::INDIRECT) { - hal_usage |= U::INDIRECT; - } - - (hal_usage, hal_memory) -} - -pub fn map_texture_usage( - usage: wgt::TextureUsage, - aspects: hal::format::Aspects, -) -> hal::image::Usage { - use hal::image::Usage as U; - use wgt::TextureUsage as W; - - let mut value = U::empty(); - if usage.contains(W::COPY_SRC) { - value |= U::TRANSFER_SRC; - } - if usage.contains(W::COPY_DST) { - value |= U::TRANSFER_DST; - } - if usage.contains(W::SAMPLED) { - value |= U::SAMPLED; - } - if usage.contains(W::STORAGE) { - value |= U::STORAGE; - } - if usage.contains(W::RENDER_ATTACHMENT) { - if aspects.intersects(hal::format::Aspects::DEPTH | hal::format::Aspects::STENCIL) { - value |= U::DEPTH_STENCIL_ATTACHMENT; - } else { - value |= U::COLOR_ATTACHMENT; - } - } - // Note: TextureUsage::Present does not need to be handled explicitly - // TODO: HAL Transient Attachment, HAL Input Attachment - value -} - -pub fn map_binding_type(binding: &wgt::BindGroupLayoutEntry) -> hal::pso::DescriptorType { - use hal::pso; - use wgt::BindingType as Bt; - match binding.ty { - Bt::Buffer { - ty, - has_dynamic_offset, - min_binding_size: _, - } => pso::DescriptorType::Buffer { - ty: match ty { - wgt::BufferBindingType::Uniform => pso::BufferDescriptorType::Uniform, - wgt::BufferBindingType::Storage { read_only } => { - pso::BufferDescriptorType::Storage { read_only } - } - }, - format: pso::BufferDescriptorFormat::Structured { - dynamic_offset: has_dynamic_offset, - }, - }, - Bt::Sampler { .. } => pso::DescriptorType::Sampler, - Bt::Texture { .. } => pso::DescriptorType::Image { - ty: pso::ImageDescriptorType::Sampled { - with_sampler: false, - }, - }, - Bt::StorageTexture { access, .. } => pso::DescriptorType::Image { - ty: pso::ImageDescriptorType::Storage { - read_only: match access { - wgt::StorageTextureAccess::ReadOnly => true, - _ => false, - }, - }, - }, - } -} - -pub fn map_shader_stage_flags(shader_stage_flags: wgt::ShaderStage) -> hal::pso::ShaderStageFlags { - use hal::pso::ShaderStageFlags as H; - use wgt::ShaderStage as Ss; - - let mut value = H::empty(); - if shader_stage_flags.contains(Ss::VERTEX) { - value |= H::VERTEX; - } - if shader_stage_flags.contains(Ss::FRAGMENT) { - value |= H::FRAGMENT; - } - if shader_stage_flags.contains(Ss::COMPUTE) { - value |= H::COMPUTE; - } - value -} - -pub fn map_hal_flags_to_shader_stage( - shader_stage_flags: hal::pso::ShaderStageFlags, -) -> wgt::ShaderStage { - use hal::pso::ShaderStageFlags as H; - use wgt::ShaderStage as Ss; - - let mut value = Ss::empty(); - if shader_stage_flags.contains(H::VERTEX) { - value |= Ss::VERTEX; - } - if shader_stage_flags.contains(H::FRAGMENT) { - value |= Ss::FRAGMENT; - } - if shader_stage_flags.contains(H::COMPUTE) { - value |= Ss::COMPUTE; - } - value -} - -pub fn map_extent(extent: &wgt::Extent3d, dim: wgt::TextureDimension) -> hal::image::Extent { - hal::image::Extent { - width: extent.width, - height: extent.height, - depth: match dim { - wgt::TextureDimension::D1 | wgt::TextureDimension::D2 => 1, - wgt::TextureDimension::D3 => extent.depth_or_array_layers, - }, - } -} - -pub fn map_primitive_topology(primitive_topology: wgt::PrimitiveTopology) -> hal::pso::Primitive { - use hal::pso::Primitive as H; - use wgt::PrimitiveTopology as Pt; - match primitive_topology { - Pt::PointList => H::PointList, - Pt::LineList => H::LineList, - Pt::LineStrip => H::LineStrip, - Pt::TriangleList => H::TriangleList, - Pt::TriangleStrip => H::TriangleStrip, - } -} - -pub fn map_color_target_state( - desc: &wgt::ColorTargetState, -) -> Result { - let color_mask = desc.write_mask; - let blend = desc - .blend - .as_ref() - .map(|bs| { - Ok(hal::pso::BlendState { - color: map_blend_component(&bs.color)?, - alpha: map_blend_component(&bs.alpha)?, - }) - }) - .transpose()?; - Ok(hal::pso::ColorBlendDesc { - mask: map_color_write_flags(color_mask), - blend, - }) -} - -fn map_color_write_flags(flags: wgt::ColorWrite) -> hal::pso::ColorMask { - use hal::pso::ColorMask as H; - use wgt::ColorWrite as Cw; - - let mut value = H::empty(); - if flags.contains(Cw::RED) { - value |= H::RED; - } - if flags.contains(Cw::GREEN) { - value |= H::GREEN; - } - if flags.contains(Cw::BLUE) { - value |= H::BLUE; - } - if flags.contains(Cw::ALPHA) { - value |= H::ALPHA; - } - value -} - -fn map_blend_component( - component: &wgt::BlendComponent, -) -> Result { - use hal::pso::BlendOp as H; - use wgt::BlendOperation as Bo; - Ok(match *component { - wgt::BlendComponent { - operation: Bo::Add, - src_factor, - dst_factor, - } => H::Add { - src: map_blend_factor(src_factor), - dst: map_blend_factor(dst_factor), - }, - wgt::BlendComponent { - operation: Bo::Subtract, - src_factor, - dst_factor, - } => H::Sub { - src: map_blend_factor(src_factor), - dst: map_blend_factor(dst_factor), - }, - wgt::BlendComponent { - operation: Bo::ReverseSubtract, - src_factor, - dst_factor, - } => H::RevSub { - src: map_blend_factor(src_factor), - dst: map_blend_factor(dst_factor), - }, - wgt::BlendComponent { - operation: Bo::Min, - src_factor: wgt::BlendFactor::One, - dst_factor: wgt::BlendFactor::One, - } => H::Min, - wgt::BlendComponent { - operation: Bo::Max, - src_factor: wgt::BlendFactor::One, - dst_factor: wgt::BlendFactor::One, - } => H::Max, - _ => return Err(ColorStateError::InvalidMinMaxBlendFactors(*component)), - }) -} - -fn map_blend_factor(blend_factor: wgt::BlendFactor) -> hal::pso::Factor { - use hal::pso::Factor as H; - use wgt::BlendFactor as Bf; - match blend_factor { - Bf::Zero => H::Zero, - Bf::One => H::One, - Bf::Src => H::SrcColor, - Bf::OneMinusSrc => H::OneMinusSrcColor, - Bf::SrcAlpha => H::SrcAlpha, - Bf::OneMinusSrcAlpha => H::OneMinusSrcAlpha, - Bf::Dst => H::DstColor, - Bf::OneMinusDst => H::OneMinusDstColor, - Bf::DstAlpha => H::DstAlpha, - Bf::OneMinusDstAlpha => H::OneMinusDstAlpha, - Bf::SrcAlphaSaturated => H::SrcAlphaSaturate, - Bf::Constant => H::ConstColor, - Bf::OneMinusConstant => H::OneMinusConstColor, - } -} - -pub fn map_depth_stencil_state(desc: &wgt::DepthStencilState) -> hal::pso::DepthStencilDesc { - hal::pso::DepthStencilDesc { - depth: if desc.is_depth_enabled() { - Some(hal::pso::DepthTest { - fun: map_compare_function(desc.depth_compare), - write: desc.depth_write_enabled, - }) - } else { - None - }, - depth_bounds: false, // TODO - stencil: if desc.stencil.is_enabled() { - let s = &desc.stencil; - Some(hal::pso::StencilTest { - faces: hal::pso::Sided { - front: map_stencil_face(&s.front), - back: map_stencil_face(&s.back), - }, - read_masks: hal::pso::State::Static(hal::pso::Sided::new(s.read_mask)), - write_masks: hal::pso::State::Static(hal::pso::Sided::new(s.write_mask)), - reference_values: if s.needs_ref_value() { - hal::pso::State::Dynamic - } else { - hal::pso::State::Static(hal::pso::Sided::new(0)) - }, - }) - } else { - None - }, - } -} - -fn map_stencil_face(stencil_state_face_desc: &wgt::StencilFaceState) -> hal::pso::StencilFace { - hal::pso::StencilFace { - fun: map_compare_function(stencil_state_face_desc.compare), - op_fail: map_stencil_operation(stencil_state_face_desc.fail_op), - op_depth_fail: map_stencil_operation(stencil_state_face_desc.depth_fail_op), - op_pass: map_stencil_operation(stencil_state_face_desc.pass_op), - } -} - -pub fn map_compare_function(compare_function: wgt::CompareFunction) -> hal::pso::Comparison { - use hal::pso::Comparison as H; - use wgt::CompareFunction as Cf; - match compare_function { - Cf::Never => H::Never, - Cf::Less => H::Less, - Cf::Equal => H::Equal, - Cf::LessEqual => H::LessEqual, - Cf::Greater => H::Greater, - Cf::NotEqual => H::NotEqual, - Cf::GreaterEqual => H::GreaterEqual, - Cf::Always => H::Always, - } -} - -fn map_stencil_operation(stencil_operation: wgt::StencilOperation) -> hal::pso::StencilOp { - use hal::pso::StencilOp as H; - use wgt::StencilOperation as So; - match stencil_operation { - So::Keep => H::Keep, - So::Zero => H::Zero, - So::Replace => H::Replace, - So::Invert => H::Invert, - So::IncrementClamp => H::IncrementClamp, - So::DecrementClamp => H::DecrementClamp, - So::IncrementWrap => H::IncrementWrap, - So::DecrementWrap => H::DecrementWrap, - } -} - -pub(crate) fn map_texture_format( - texture_format: wgt::TextureFormat, - private_features: PrivateFeatures, -) -> hal::format::Format { - use hal::format::Format as H; - use wgt::TextureFormat as Tf; - match texture_format { - // Normal 8 bit formats - Tf::R8Unorm => H::R8Unorm, - Tf::R8Snorm => H::R8Snorm, - Tf::R8Uint => H::R8Uint, - Tf::R8Sint => H::R8Sint, - - // Normal 16 bit formats - Tf::R16Uint => H::R16Uint, - Tf::R16Sint => H::R16Sint, - Tf::R16Float => H::R16Sfloat, - Tf::Rg8Unorm => H::Rg8Unorm, - Tf::Rg8Snorm => H::Rg8Snorm, - Tf::Rg8Uint => H::Rg8Uint, - Tf::Rg8Sint => H::Rg8Sint, - - // Normal 32 bit formats - Tf::R32Uint => H::R32Uint, - Tf::R32Sint => H::R32Sint, - Tf::R32Float => H::R32Sfloat, - Tf::Rg16Uint => H::Rg16Uint, - Tf::Rg16Sint => H::Rg16Sint, - Tf::Rg16Float => H::Rg16Sfloat, - Tf::Rgba8Unorm => H::Rgba8Unorm, - Tf::Rgba8UnormSrgb => H::Rgba8Srgb, - Tf::Rgba8Snorm => H::Rgba8Snorm, - Tf::Rgba8Uint => H::Rgba8Uint, - Tf::Rgba8Sint => H::Rgba8Sint, - Tf::Bgra8Unorm => H::Bgra8Unorm, - Tf::Bgra8UnormSrgb => H::Bgra8Srgb, - - // Packed 32 bit formats - Tf::Rgb10a2Unorm => H::A2r10g10b10Unorm, - Tf::Rg11b10Float => H::B10g11r11Ufloat, - - // Normal 64 bit formats - Tf::Rg32Uint => H::Rg32Uint, - Tf::Rg32Sint => H::Rg32Sint, - Tf::Rg32Float => H::Rg32Sfloat, - Tf::Rgba16Uint => H::Rgba16Uint, - Tf::Rgba16Sint => H::Rgba16Sint, - Tf::Rgba16Float => H::Rgba16Sfloat, - - // Normal 128 bit formats - Tf::Rgba32Uint => H::Rgba32Uint, - Tf::Rgba32Sint => H::Rgba32Sint, - Tf::Rgba32Float => H::Rgba32Sfloat, - - // Depth and stencil formats - Tf::Depth32Float => H::D32Sfloat, - Tf::Depth24Plus => { - if private_features.texture_d24 { - H::X8D24Unorm - } else { - H::D32Sfloat - } - } - Tf::Depth24PlusStencil8 => { - if private_features.texture_d24_s8 { - H::D24UnormS8Uint - } else { - H::D32SfloatS8Uint - } - } - - // BCn compressed formats - Tf::Bc1RgbaUnorm => H::Bc1RgbaUnorm, - Tf::Bc1RgbaUnormSrgb => H::Bc1RgbaSrgb, - Tf::Bc2RgbaUnorm => H::Bc2Unorm, - Tf::Bc2RgbaUnormSrgb => H::Bc2Srgb, - Tf::Bc3RgbaUnorm => H::Bc3Unorm, - Tf::Bc3RgbaUnormSrgb => H::Bc3Srgb, - Tf::Bc4RUnorm => H::Bc4Unorm, - Tf::Bc4RSnorm => H::Bc4Snorm, - Tf::Bc5RgUnorm => H::Bc5Unorm, - Tf::Bc5RgSnorm => H::Bc5Snorm, - Tf::Bc6hRgbSfloat => H::Bc6hSfloat, - Tf::Bc6hRgbUfloat => H::Bc6hUfloat, - Tf::Bc7RgbaUnorm => H::Bc7Unorm, - Tf::Bc7RgbaUnormSrgb => H::Bc7Srgb, - - // ETC compressed formats - Tf::Etc2RgbUnorm => H::Etc2R8g8b8Unorm, - Tf::Etc2RgbUnormSrgb => H::Etc2R8g8b8Srgb, - Tf::Etc2RgbA1Unorm => H::Etc2R8g8b8a1Unorm, - Tf::Etc2RgbA1UnormSrgb => H::Etc2R8g8b8a1Srgb, - Tf::Etc2RgbA8Unorm => H::Etc2R8g8b8a8Unorm, - Tf::Etc2RgbA8UnormSrgb => H::Etc2R8g8b8a8Unorm, - Tf::EacRUnorm => H::EacR11Unorm, - Tf::EacRSnorm => H::EacR11Snorm, - Tf::EtcRgUnorm => H::EacR11g11Unorm, - Tf::EtcRgSnorm => H::EacR11g11Snorm, - - // ASTC compressed formats - Tf::Astc4x4RgbaUnorm => H::Astc4x4Srgb, - Tf::Astc4x4RgbaUnormSrgb => H::Astc4x4Srgb, - Tf::Astc5x4RgbaUnorm => H::Astc5x4Unorm, - Tf::Astc5x4RgbaUnormSrgb => H::Astc5x4Srgb, - Tf::Astc5x5RgbaUnorm => H::Astc5x5Unorm, - Tf::Astc5x5RgbaUnormSrgb => H::Astc5x5Srgb, - Tf::Astc6x5RgbaUnorm => H::Astc6x5Unorm, - Tf::Astc6x5RgbaUnormSrgb => H::Astc6x5Srgb, - Tf::Astc6x6RgbaUnorm => H::Astc6x6Unorm, - Tf::Astc6x6RgbaUnormSrgb => H::Astc6x6Srgb, - Tf::Astc8x5RgbaUnorm => H::Astc8x5Unorm, - Tf::Astc8x5RgbaUnormSrgb => H::Astc8x5Srgb, - Tf::Astc8x6RgbaUnorm => H::Astc8x6Unorm, - Tf::Astc8x6RgbaUnormSrgb => H::Astc8x6Srgb, - Tf::Astc10x5RgbaUnorm => H::Astc10x5Unorm, - Tf::Astc10x5RgbaUnormSrgb => H::Astc10x5Srgb, - Tf::Astc10x6RgbaUnorm => H::Astc10x6Unorm, - Tf::Astc10x6RgbaUnormSrgb => H::Astc10x6Srgb, - Tf::Astc8x8RgbaUnorm => H::Astc8x8Unorm, - Tf::Astc8x8RgbaUnormSrgb => H::Astc8x8Srgb, - Tf::Astc10x8RgbaUnorm => H::Astc10x8Unorm, - Tf::Astc10x8RgbaUnormSrgb => H::Astc10x8Srgb, - Tf::Astc10x10RgbaUnorm => H::Astc10x10Unorm, - Tf::Astc10x10RgbaUnormSrgb => H::Astc10x10Srgb, - Tf::Astc12x10RgbaUnorm => H::Astc12x10Unorm, - Tf::Astc12x10RgbaUnormSrgb => H::Astc12x10Srgb, - Tf::Astc12x12RgbaUnorm => H::Astc12x12Unorm, - Tf::Astc12x12RgbaUnormSrgb => H::Astc12x12Srgb, - } -} - -pub fn map_vertex_format(vertex_format: wgt::VertexFormat) -> hal::format::Format { - use hal::format::Format as H; - use wgt::VertexFormat as Vf; - match vertex_format { - Vf::Uint8x2 => H::Rg8Uint, - Vf::Uint8x4 => H::Rgba8Uint, - Vf::Sint8x2 => H::Rg8Sint, - Vf::Sint8x4 => H::Rgba8Sint, - Vf::Unorm8x2 => H::Rg8Unorm, - Vf::Unorm8x4 => H::Rgba8Unorm, - Vf::Snorm8x2 => H::Rg8Snorm, - Vf::Snorm8x4 => H::Rgba8Snorm, - Vf::Uint16x2 => H::Rg16Uint, - Vf::Uint16x4 => H::Rgba16Uint, - Vf::Sint16x2 => H::Rg16Sint, - Vf::Sint16x4 => H::Rgba16Sint, - Vf::Unorm16x2 => H::Rg16Unorm, - Vf::Unorm16x4 => H::Rgba16Unorm, - Vf::Snorm16x2 => H::Rg16Snorm, - Vf::Snorm16x4 => H::Rgba16Snorm, - Vf::Float16x2 => H::Rg16Sfloat, - Vf::Float16x4 => H::Rgba16Sfloat, - Vf::Float32 => H::R32Sfloat, - Vf::Float32x2 => H::Rg32Sfloat, - Vf::Float32x3 => H::Rgb32Sfloat, - Vf::Float32x4 => H::Rgba32Sfloat, - Vf::Uint32 => H::R32Uint, - Vf::Uint32x2 => H::Rg32Uint, - Vf::Uint32x3 => H::Rgb32Uint, - Vf::Uint32x4 => H::Rgba32Uint, - Vf::Sint32 => H::R32Sint, - Vf::Sint32x2 => H::Rg32Sint, - Vf::Sint32x3 => H::Rgb32Sint, - Vf::Sint32x4 => H::Rgba32Sint, - Vf::Float64 => H::R64Sfloat, - Vf::Float64x2 => H::Rg64Sfloat, - Vf::Float64x3 => H::Rgb64Sfloat, - Vf::Float64x4 => H::Rgba64Sfloat, - } -} +use crate::resource; pub fn is_power_of_two(val: u32) -> bool { val != 0 && (val & (val - 1)) == 0 @@ -564,7 +24,7 @@ pub fn is_valid_copy_dst_texture_format(format: wgt::TextureFormat) -> bool { } } -pub fn map_texture_dimension_size( +pub fn check_texture_dimension_size( dimension: wgt::TextureDimension, wgt::Extent3d { width, @@ -573,15 +33,14 @@ pub fn map_texture_dimension_size( }: wgt::Extent3d, sample_size: u32, limits: &wgt::Limits, -) -> Result { - use hal::image::Kind as H; +) -> Result<(), resource::TextureDimensionError> { use resource::{TextureDimensionError as Tde, TextureErrorDimension as Ted}; + use std::convert::TryInto; use wgt::TextureDimension::*; let layers = depth_or_array_layers.try_into().unwrap_or(!0); - let (kind, extent_limits, sample_limit) = match dimension { + let (extent_limits, sample_limit) = match dimension { D1 => ( - H::D1(width, layers), [ limits.max_texture_dimension_1d, 1, @@ -590,7 +49,6 @@ pub fn map_texture_dimension_size( 1, ), D2 => ( - H::D2(width, height, layers, sample_size as u8), [ limits.max_texture_dimension_2d, limits.max_texture_dimension_2d, @@ -599,7 +57,6 @@ pub fn map_texture_dimension_size( 32, ), D3 => ( - H::D3(width, height, depth_or_array_layers), [ limits.max_texture_dimension_3d, limits.max_texture_dimension_3d, @@ -625,165 +82,10 @@ pub fn map_texture_dimension_size( return Err(Tde::InvalidSampleCount(sample_size)); } - Ok(kind) + Ok(()) } -pub fn map_texture_view_dimension(dimension: wgt::TextureViewDimension) -> hal::image::ViewKind { - use hal::image::ViewKind as H; - use wgt::TextureViewDimension::*; - match dimension { - D1 => H::D1, - D2 => H::D2, - D2Array => H::D2Array, - Cube => H::Cube, - CubeArray => H::CubeArray, - D3 => H::D3, - } -} - -pub(crate) fn map_buffer_state(usage: resource::BufferUse) -> hal::buffer::State { - use crate::resource::BufferUse as W; - use hal::buffer::Access as A; - - let mut access = A::empty(); - if usage.contains(W::MAP_READ) { - access |= A::HOST_READ; - } - if usage.contains(W::MAP_WRITE) { - access |= A::HOST_WRITE; - } - if usage.contains(W::COPY_SRC) { - access |= A::TRANSFER_READ; - } - if usage.contains(W::COPY_DST) { - access |= A::TRANSFER_WRITE; - } - if usage.contains(W::INDEX) { - access |= A::INDEX_BUFFER_READ; - } - if usage.contains(W::VERTEX) { - access |= A::VERTEX_BUFFER_READ; - } - if usage.contains(W::UNIFORM) { - access |= A::UNIFORM_READ | A::SHADER_READ; - } - if usage.contains(W::STORAGE_LOAD) { - access |= A::SHADER_READ; - } - if usage.contains(W::STORAGE_STORE) { - access |= A::SHADER_READ | A::SHADER_WRITE; - } - if usage.contains(W::INDIRECT) { - access |= A::INDIRECT_COMMAND_READ; - } - - access -} - -pub(crate) fn map_texture_state( - usage: resource::TextureUse, - aspects: hal::format::Aspects, -) -> hal::image::State { - use crate::resource::TextureUse as W; - use hal::image::{Access as A, Layout as L}; - - let is_color = aspects.contains(hal::format::Aspects::COLOR); - let layout = match usage { - W::UNINITIALIZED => return (A::empty(), L::Undefined), - W::COPY_SRC => L::TransferSrcOptimal, - W::COPY_DST => L::TransferDstOptimal, - W::SAMPLED if is_color => L::ShaderReadOnlyOptimal, - W::ATTACHMENT_READ | W::ATTACHMENT_WRITE if is_color => L::ColorAttachmentOptimal, - _ if is_color => L::General, - W::ATTACHMENT_WRITE => L::DepthStencilAttachmentOptimal, - _ => L::DepthStencilReadOnlyOptimal, - }; - - let mut access = A::empty(); - if usage.contains(W::COPY_SRC) { - access |= A::TRANSFER_READ; - } - if usage.contains(W::COPY_DST) { - access |= A::TRANSFER_WRITE; - } - if usage.contains(W::SAMPLED) { - access |= A::SHADER_READ; - } - if usage.contains(W::ATTACHMENT_READ) { - access |= if is_color { - A::COLOR_ATTACHMENT_READ - } else { - A::DEPTH_STENCIL_ATTACHMENT_READ - }; - } - if usage.contains(W::ATTACHMENT_WRITE) { - access |= if is_color { - A::COLOR_ATTACHMENT_WRITE - } else { - A::DEPTH_STENCIL_ATTACHMENT_WRITE - }; - } - if usage.contains(W::STORAGE_LOAD) { - access |= A::SHADER_READ; - } - if usage.contains(W::STORAGE_STORE) { - access |= A::SHADER_WRITE; - } - - (access, layout) -} - -pub fn map_query_type(ty: &wgt::QueryType) -> (hal::query::Type, u32) { - match *ty { - wgt::QueryType::PipelineStatistics(pipeline_statistics) => { - let mut ps = hal::query::PipelineStatistic::empty(); - ps.set( - hal::query::PipelineStatistic::VERTEX_SHADER_INVOCATIONS, - pipeline_statistics - .contains(wgt::PipelineStatisticsTypes::VERTEX_SHADER_INVOCATIONS), - ); - ps.set( - hal::query::PipelineStatistic::CLIPPING_INVOCATIONS, - pipeline_statistics.contains(wgt::PipelineStatisticsTypes::CLIPPER_INVOCATIONS), - ); - ps.set( - hal::query::PipelineStatistic::CLIPPING_PRIMITIVES, - pipeline_statistics.contains(wgt::PipelineStatisticsTypes::CLIPPER_PRIMITIVES_OUT), - ); - ps.set( - hal::query::PipelineStatistic::FRAGMENT_SHADER_INVOCATIONS, - pipeline_statistics - .contains(wgt::PipelineStatisticsTypes::FRAGMENT_SHADER_INVOCATIONS), - ); - ps.set( - hal::query::PipelineStatistic::COMPUTE_SHADER_INVOCATIONS, - pipeline_statistics - .contains(wgt::PipelineStatisticsTypes::COMPUTE_SHADER_INVOCATIONS), - ); - - ( - hal::query::Type::PipelineStatistics(ps), - pipeline_statistics.bits().count_ones(), - ) - } - wgt::QueryType::Timestamp => (hal::query::Type::Timestamp, 1), - } -} - -pub fn map_load_store_ops(channel: &PassChannel) -> hal::pass::AttachmentOps { - hal::pass::AttachmentOps { - load: match channel.load_op { - LoadOp::Clear => hal::pass::AttachmentLoadOp::Clear, - LoadOp::Load => hal::pass::AttachmentLoadOp::Load, - }, - store: match channel.store_op { - StoreOp::Clear => hal::pass::AttachmentStoreOp::DontCare, //TODO! - StoreOp::Store => hal::pass::AttachmentStoreOp::Store, - }, - } -} - -pub fn map_color_f32(color: &wgt::Color) -> hal::pso::ColorValue { +pub fn map_color_f32(color: &wgt::Color) -> [f32; 4] { [ color.r as f32, color.g as f32, @@ -808,86 +110,6 @@ pub fn map_color_u32(color: &wgt::Color) -> [u32; 4] { ] } -pub fn map_filter(filter: wgt::FilterMode) -> hal::image::Filter { - match filter { - wgt::FilterMode::Nearest => hal::image::Filter::Nearest, - wgt::FilterMode::Linear => hal::image::Filter::Linear, - } -} - -pub fn map_wrap(address: wgt::AddressMode) -> hal::image::WrapMode { - use hal::image::WrapMode as W; - use wgt::AddressMode as Am; - match address { - Am::ClampToEdge => W::Clamp, - Am::Repeat => W::Tile, - Am::MirrorRepeat => W::Mirror, - Am::ClampToBorder => W::Border, - } -} - -pub fn map_primitive_state_to_input_assembler( - desc: &wgt::PrimitiveState, -) -> hal::pso::InputAssemblerDesc { - hal::pso::InputAssemblerDesc { - primitive: map_primitive_topology(desc.topology), - with_adjacency: false, - restart_index: desc.strip_index_format.map(map_index_format), - } -} - -pub fn map_primitive_state_to_rasterizer( - desc: &wgt::PrimitiveState, - depth_stencil: Option<&wgt::DepthStencilState>, -) -> hal::pso::Rasterizer { - use hal::pso; - let depth_bias = match depth_stencil { - Some(dsd) if dsd.bias.is_enabled() => Some(pso::State::Static(pso::DepthBias { - const_factor: dsd.bias.constant as f32, - slope_factor: dsd.bias.slope_scale, - clamp: dsd.bias.clamp, - })), - _ => None, - }; - pso::Rasterizer { - depth_clamping: desc.clamp_depth, - polygon_mode: match desc.polygon_mode { - wgt::PolygonMode::Fill => pso::PolygonMode::Fill, - wgt::PolygonMode::Line => pso::PolygonMode::Line, - wgt::PolygonMode::Point => pso::PolygonMode::Point, - }, - cull_face: match desc.cull_mode { - None => pso::Face::empty(), - Some(wgt::Face::Front) => pso::Face::FRONT, - Some(wgt::Face::Back) => pso::Face::BACK, - }, - front_face: match desc.front_face { - wgt::FrontFace::Ccw => pso::FrontFace::CounterClockwise, - wgt::FrontFace::Cw => pso::FrontFace::Clockwise, - }, - depth_bias, - conservative: desc.conservative, - line_width: pso::State::Static(1.0), - } -} - -pub fn map_multisample_state(desc: &wgt::MultisampleState) -> hal::pso::Multisampling { - hal::pso::Multisampling { - rasterization_samples: desc.count as _, - sample_shading: None, - sample_mask: desc.mask, - alpha_coverage: desc.alpha_to_coverage_enabled, - alpha_to_one: false, - } -} - -pub fn map_index_format(index_format: wgt::IndexFormat) -> hal::IndexType { - match index_format { - wgt::IndexFormat::Uint16 => hal::IndexType::U16, - wgt::IndexFormat::Uint32 => hal::IndexType::U32, - } -} - /// Take `value` and round it up to the nearest alignment `alignment`. /// /// ```text diff --git a/wgpu-core/src/device/alloc.rs b/wgpu-core/src/device/alloc.rs index 5366126a3..94c4dd19e 100644 --- a/wgpu-core/src/device/alloc.rs +++ b/wgpu-core/src/device/alloc.rs @@ -7,12 +7,12 @@ use hal::device::Device as _; use std::{borrow::Cow, iter, ptr::NonNull}; #[derive(Debug)] -pub struct MemoryAllocator(gpu_alloc::GpuAllocator); +pub struct MemoryAllocator(gpu_alloc::GpuAllocator); #[derive(Debug)] -pub struct MemoryBlock(gpu_alloc::MemoryBlock); -struct MemoryDevice<'a, B: hal::Backend>(&'a B::Device); +pub struct MemoryBlock(gpu_alloc::MemoryBlock); +struct MemoryDevice<'a, A: hal::Api>(&'a B::Device); -impl MemoryAllocator { +impl MemoryAllocator { pub fn new(mem_props: hal::adapter::MemoryProperties, limits: hal::Limits) -> Self { let mem_config = gpu_alloc::Config { dedicated_threshold: 32 << 20, @@ -60,7 +60,7 @@ impl MemoryAllocator { device: &B::Device, requirements: hal::memory::Requirements, usage: gpu_alloc::UsageFlags, - ) -> Result, DeviceError> { + ) -> Result, DeviceError> { assert!(requirements.alignment.is_power_of_two()); let request = gpu_alloc::Request { size: requirements.size, @@ -69,7 +69,7 @@ impl MemoryAllocator { usage, }; - unsafe { self.0.alloc(&MemoryDevice::(device), request) } + unsafe { self.0.alloc(&MemoryDevice::(device), request) } .map(MemoryBlock) .map_err(|err| match err { gpu_alloc::AllocationError::OutOfHostMemory @@ -78,16 +78,16 @@ impl MemoryAllocator { }) } - pub fn free(&mut self, device: &B::Device, block: MemoryBlock) { - unsafe { self.0.dealloc(&MemoryDevice::(device), block.0) } + pub fn free(&mut self, device: &B::Device, block: MemoryBlock) { + unsafe { self.0.dealloc(&MemoryDevice::(device), block.0) } } pub fn clear(&mut self, device: &B::Device) { - unsafe { self.0.cleanup(&MemoryDevice::(device)) } + unsafe { self.0.cleanup(&MemoryDevice::(device)) } } } -impl MemoryBlock { +impl MemoryBlock { pub fn bind_buffer( &self, device: &B::Device, @@ -125,13 +125,13 @@ impl MemoryBlock { let offset = inner_offset; unsafe { self.0 - .map(&MemoryDevice::(device), offset, size as usize) + .map(&MemoryDevice::(device), offset, size as usize) .map_err(DeviceError::from) } } pub fn unmap(&mut self, device: &B::Device) { - unsafe { self.0.unmap(&MemoryDevice::(device)) }; + unsafe { self.0.unmap(&MemoryDevice::(device)) }; } pub fn write_bytes( @@ -144,7 +144,7 @@ impl MemoryBlock { let offset = inner_offset; unsafe { self.0 - .write_bytes(&MemoryDevice::(device), offset, data) + .write_bytes(&MemoryDevice::(device), offset, data) .map_err(DeviceError::from) } } @@ -159,7 +159,7 @@ impl MemoryBlock { let offset = inner_offset; unsafe { self.0 - .read_bytes(&MemoryDevice::(device), offset, data) + .read_bytes(&MemoryDevice::(device), offset, data) .map_err(DeviceError::from) } } @@ -206,7 +206,7 @@ impl MemoryBlock { } } -impl gpu_alloc::MemoryDevice for MemoryDevice<'_, B> { +impl gpu_alloc::MemoryDevice for MemoryDevice<'_, B> { unsafe fn allocate_memory( &self, size: u64, diff --git a/wgpu-core/src/device/descriptor.rs b/wgpu-core/src/device/descriptor.rs index d2c4f7aaa..e0403d61c 100644 --- a/wgpu-core/src/device/descriptor.rs +++ b/wgpu-core/src/device/descriptor.rs @@ -7,15 +7,15 @@ use arrayvec::ArrayVec; pub use gpu_descriptor::DescriptorTotalCount; -pub type DescriptorSet = gpu_descriptor::DescriptorSet<::DescriptorSet>; +pub type DescriptorSet = gpu_descriptor::DescriptorSet<::DescriptorSet>; #[derive(Debug)] -pub struct DescriptorAllocator( +pub struct DescriptorAllocator( gpu_descriptor::DescriptorAllocator, ); -struct DescriptorDevice<'a, B: hal::Backend>(&'a B::Device); +struct DescriptorDevice<'a, A: hal::Api>(&'a B::Device); -impl DescriptorAllocator { +impl DescriptorAllocator { pub fn new() -> Self { DescriptorAllocator(gpu_descriptor::DescriptorAllocator::new(0)) } @@ -26,10 +26,10 @@ impl DescriptorAllocator { layout: &B::DescriptorSetLayout, layout_descriptor_count: &DescriptorTotalCount, count: u32, - ) -> Result>, DeviceError> { + ) -> Result>, DeviceError> { unsafe { self.0.allocate( - &DescriptorDevice::(device), + &DescriptorDevice::(device), layout, gpu_descriptor::DescriptorSetLayoutCreateFlags::empty(), layout_descriptor_count, @@ -42,16 +42,16 @@ impl DescriptorAllocator { }) } - pub fn free(&mut self, device: &B::Device, sets: impl IntoIterator>) { - unsafe { self.0.free(&DescriptorDevice::(device), sets) } + pub fn free(&mut self, device: &B::Device, sets: impl IntoIterator>) { + unsafe { self.0.free(&DescriptorDevice::(device), sets) } } pub fn cleanup(&mut self, device: &B::Device) { - unsafe { self.0.cleanup(&DescriptorDevice::(device)) } + unsafe { self.0.cleanup(&DescriptorDevice::(device)) } } } -impl +impl gpu_descriptor::DescriptorDevice for DescriptorDevice<'_, B> { diff --git a/wgpu-core/src/device/life.rs b/wgpu-core/src/device/life.rs index 2a7d3b1b3..20e82c420 100644 --- a/wgpu-core/src/device/life.rs +++ b/wgpu-core/src/device/life.rs @@ -11,7 +11,7 @@ use crate::{ queue::TempResource, DeviceError, }, - hub::{GfxBackend, GlobalIdentityHandlerFactory, Hub, Token}, + hub::{GlobalIdentityHandlerFactory, HalApi, Hub, Token}, id, resource, track::TrackerSet, RefCount, Stored, SubmissionIndex, @@ -90,15 +90,15 @@ impl SuspectedResources { /// A struct that keeps lists of resources that are no longer needed. #[derive(Debug)] -struct NonReferencedResources { - buffers: Vec<(B::Buffer, alloc::MemoryBlock)>, - images: Vec<(B::Image, alloc::MemoryBlock)>, +struct NonReferencedResources { + buffers: Vec<(B::Buffer, alloc::MemoryBlock)>, + images: Vec<(B::Image, alloc::MemoryBlock)>, // Note: we keep the associated ID here in order to be able to check // at any point what resources are used in a submission. image_views: Vec<(id::Valid, B::ImageView)>, samplers: Vec, framebuffers: Vec, - desc_sets: Vec>, + desc_sets: Vec>, compute_pipes: Vec, graphics_pipes: Vec, descriptor_set_layouts: Vec, @@ -106,7 +106,7 @@ struct NonReferencedResources { query_sets: Vec, } -impl NonReferencedResources { +impl NonReferencedResources { fn new() -> Self { Self { buffers: Vec::new(), @@ -140,8 +140,8 @@ impl NonReferencedResources { unsafe fn clean( &mut self, device: &B::Device, - memory_allocator_mutex: &Mutex>, - descriptor_allocator_mutex: &Mutex>, + memory_allocator_mutex: &Mutex>, + descriptor_allocator_mutex: &Mutex>, ) { if !self.buffers.is_empty() || !self.images.is_empty() { let mut allocator = memory_allocator_mutex.lock(); @@ -192,10 +192,10 @@ impl NonReferencedResources { } #[derive(Debug)] -struct ActiveSubmission { +struct ActiveSubmission { index: SubmissionIndex, fence: B::Fence, - last_resources: NonReferencedResources, + last_resources: NonReferencedResources, mapped: Vec>, } @@ -216,7 +216,7 @@ pub enum WaitIdleError { /// 3. When `ActiveSubmission` is retired, the mapped buffers associated with it are moved to `ready_to_map` vector. /// 4. Finally, `handle_mapping` issues all the callbacks. #[derive(Debug)] -pub(super) struct LifetimeTracker { +pub(super) struct LifetimeTracker { /// Resources that the user has requested be mapped, but are still in use. mapped: Vec>, /// Buffers can be used in a submission that is yet to be made, by the @@ -229,14 +229,14 @@ pub(super) struct LifetimeTracker { /// Resources that are not referenced any more but still used by GPU. /// Grouped by submissions associated with a fence and a submission index. /// The active submissions have to be stored in FIFO order: oldest come first. - active: Vec>, + active: Vec>, /// Resources that are neither referenced or used, just life_tracker /// actual deletion. - free_resources: NonReferencedResources, + free_resources: NonReferencedResources, ready_to_map: Vec>, } -impl LifetimeTracker { +impl LifetimeTracker { pub fn new() -> Self { Self { mapped: Vec::new(), @@ -254,7 +254,7 @@ impl LifetimeTracker { index: SubmissionIndex, fence: B::Fence, new_suspects: &SuspectedResources, - temp_resources: impl Iterator, alloc::MemoryBlock)>, + temp_resources: impl Iterator, alloc::MemoryBlock)>, ) { let mut last_resources = NonReferencedResources::new(); for (res, memory) in temp_resources { @@ -347,8 +347,8 @@ impl LifetimeTracker { pub fn cleanup( &mut self, device: &B::Device, - memory_allocator_mutex: &Mutex>, - descriptor_allocator_mutex: &Mutex>, + memory_allocator_mutex: &Mutex>, + descriptor_allocator_mutex: &Mutex>, ) { profiling::scope!("cleanup"); unsafe { @@ -360,8 +360,8 @@ impl LifetimeTracker { pub fn schedule_resource_destruction( &mut self, - temp_resource: TempResource, - memory: alloc::MemoryBlock, + temp_resource: TempResource, + memory: alloc::MemoryBlock, last_submit_index: SubmissionIndex, ) { let resources = self @@ -376,13 +376,13 @@ impl LifetimeTracker { } } -impl LifetimeTracker { +impl LifetimeTracker { pub(super) fn triage_suspected( &mut self, - hub: &Hub, + hub: &Hub, trackers: &Mutex, #[cfg(feature = "trace")] trace: Option<&Mutex>, - token: &mut Token>, + token: &mut Token>, ) { profiling::scope!("triage_suspected"); @@ -662,8 +662,8 @@ impl LifetimeTracker { pub(super) fn triage_mapped( &mut self, - hub: &Hub, - token: &mut Token>, + hub: &Hub, + token: &mut Token>, ) { if self.mapped.is_empty() { return; @@ -692,10 +692,10 @@ impl LifetimeTracker { pub(super) fn handle_mapping( &mut self, - hub: &Hub, + hub: &Hub, raw: &B::Device, trackers: &Mutex, - token: &mut Token>, + token: &mut Token>, ) -> Vec { if self.ready_to_map.is_empty() { return Vec::new(); diff --git a/wgpu-core/src/device/mod.rs b/wgpu-core/src/device/mod.rs index 5a0bda3c6..5c1f4445f 100644 --- a/wgpu-core/src/device/mod.rs +++ b/wgpu-core/src/device/mod.rs @@ -5,25 +5,18 @@ use crate::{ binding_model, command, conv, device::life::WaitIdleError, - hub::{ - GfxBackend, Global, GlobalIdentityHandlerFactory, Hub, Input, InvalidId, Storage, Token, - }, + hub::{Global, GlobalIdentityHandlerFactory, HalApi, Hub, Input, InvalidId, Storage, Token}, id, instance, memory_init_tracker::{MemoryInitKind, MemoryInitTracker, MemoryInitTrackerAction}, pipeline, resource, swap_chain, track::{BufferState, TextureSelector, TextureState, TrackerSet, UsageConflict}, validation::{self, check_buffer_usage, check_texture_usage}, - FastHashMap, Label, LabelHelpers, LifeGuard, MultiRefCount, PrivateFeatures, Stored, - SubmissionIndex, MAX_BIND_GROUPS, + FastHashMap, Label, LabelHelpers, LifeGuard, MultiRefCount, Stored, SubmissionIndex, }; use arrayvec::ArrayVec; use copyless::VecHelper as _; -use hal::{ - command::CommandBuffer as _, - device::Device as _, - window::{PresentationSurface as _, Surface as _}, -}; +use hal::{CommandBuffer as _, Device as _}; use parking_lot::{Mutex, MutexGuard}; use thiserror::Error; use wgt::{BufferAddress, InputStepMode, TextureDimension, TextureFormat, TextureViewDimension}; @@ -51,34 +44,12 @@ use smallvec::SmallVec; pub const MAX_COLOR_TARGETS: usize = 4; pub const MAX_MIP_LEVELS: u32 = 16; pub const MAX_VERTEX_BUFFERS: usize = 16; -pub const MAX_ANISOTROPY: u8 = 16; pub const SHADER_STAGE_COUNT: usize = 3; const IMPLICIT_FAILURE: &str = "failed implicit"; pub type DeviceDescriptor<'a> = wgt::DeviceDescriptor>; -pub fn all_buffer_stages() -> hal::pso::PipelineStage { - use hal::pso::PipelineStage as Ps; - Ps::DRAW_INDIRECT - | Ps::VERTEX_INPUT - | Ps::VERTEX_SHADER - | Ps::FRAGMENT_SHADER - | Ps::COMPUTE_SHADER - | Ps::TRANSFER - | Ps::HOST -} -pub fn all_image_stages() -> hal::pso::PipelineStage { - use hal::pso::PipelineStage as Ps; - Ps::EARLY_FRAGMENT_TESTS - | Ps::LATE_FRAGMENT_TESTS - | Ps::COLOR_ATTACHMENT_OUTPUT - | Ps::VERTEX_SHADER - | Ps::FRAGMENT_SHADER - | Ps::COMPUTE_SHADER - | Ps::TRANSFER -} - #[repr(C)] #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "trace", derive(serde::Serialize))] @@ -113,15 +84,6 @@ impl AttachmentData { } } -pub(crate) type AttachmentDataVec = ArrayVec<[T; MAX_COLOR_TARGETS + MAX_COLOR_TARGETS + 1]>; -pub(crate) type RenderPassKey = AttachmentData<(hal::pass::Attachment, hal::image::Layout)>; -#[derive(Debug, Eq, Hash, PartialEq)] -pub(crate) struct FramebufferKey { - pub(crate) attachments: AttachmentData, - pub(crate) extent: wgt::Extent3d, - pub(crate) samples: hal::image::NumSamples, -} - #[derive(Clone, Debug, Hash, PartialEq)] #[cfg_attr(feature = "serial-pass", derive(serde::Deserialize, serde::Serialize))] pub(crate) struct RenderPassContext { @@ -173,28 +135,23 @@ impl RenderPassContext { type BufferMapPendingCallback = (resource::BufferMapOperation, resource::BufferMapAsyncStatus); -fn map_buffer( - raw: &B::Device, - buffer: &mut resource::Buffer, - offset: hal::buffer::Offset, +fn map_buffer( + raw: &A::Device, + buffer: &mut resource::Buffer, + offset: BufferAddress, size: BufferAddress, kind: HostMap, ) -> Result, resource::BufferAccessError> { - let &mut (_, ref mut block) = buffer - .raw - .as_mut() - .ok_or(resource::BufferAccessError::Destroyed)?; - let ptr = block.map(raw, offset, size).map_err(DeviceError::from)?; + let ptr = raw + .map_buffer(&buffer.raw, offset, offset + size) + .map_err(DeviceError::from)?; buffer.sync_mapped_writes = match kind { - HostMap::Read if !block.is_coherent() => { - block.invalidate_range(raw, offset, Some(size))?; + HostMap::Read if !buffer.is_coherent => { + raw.invalidate_memory_ranges(&buffer.raw, iter::once(offset..offset + size)); None } - HostMap::Write if !block.is_coherent() => Some(hal::memory::Segment { - offset, - size: Some(size), - }), + HostMap::Write if !buffer.is_coherent => Some(offset..offset + size), _ => None, }; @@ -206,7 +163,7 @@ fn map_buffer( // we instead just initialize the memory here and make sure it is GPU visible, so this happens at max only once for every buffer region. // // If this is a write mapping zeroing out the memory here is the only reasonable way as all data is pushed to GPU anyways. - let zero_init_needs_flush_now = !block.is_coherent() && buffer.sync_mapped_writes.is_none(); // No need to flush if it is flushed later anyways. + let zero_init_needs_flush_now = !buffer.is_coherent && buffer.sync_mapped_writes.is_none(); // No need to flush if it is flushed later anyways. for uninitialized_range in buffer.initialization_status.drain(offset..(size + offset)) { let num_bytes = uninitialized_range.end - uninitialized_range.start; unsafe { @@ -217,28 +174,16 @@ fn map_buffer( ) }; if zero_init_needs_flush_now { - block.flush_range(raw, uninitialized_range.start, Some(num_bytes))?; + raw.flush_memory_ranges( + &buffer.raw, + iter::once(uninitialized_range.start..uninitialized_range.start + num_bytes), + ); } } Ok(ptr) } -fn unmap_buffer( - raw: &B::Device, - buffer: &mut resource::Buffer, -) -> Result<(), resource::BufferAccessError> { - let &mut (_, ref mut block) = buffer - .raw - .as_mut() - .ok_or(resource::BufferAccessError::Destroyed)?; - if let Some(segment) = buffer.sync_mapped_writes.take() { - block.flush_range(raw, segment.offset, segment.size)?; - } - block.unmap(raw); - Ok(()) -} - //Note: this logic is specifically moved out of `handle_mapping()` in order to // have nothing locked by the time we execute users callback code. fn fire_map_callbacks>(callbacks: I) { @@ -247,12 +192,6 @@ fn fire_map_callbacks>(callback } } -#[derive(Debug)] -pub(crate) struct RenderPassLock { - pub(crate) render_passes: FastHashMap, - pub(crate) framebuffers: FastHashMap, -} - /// Structure describing a logical device. Some members are internally mutable, /// stored behind mutexes. /// TODO: establish clear order of locking for these: @@ -264,31 +203,29 @@ pub(crate) struct RenderPassLock { /// 1. `self.trackers` is locked last (unenforced) /// 1. `self.trace` is locked last (unenforced) #[derive(Debug)] -pub struct Device { - pub(crate) raw: B::Device, +pub struct Device { + pub(crate) raw: A::Device, pub(crate) adapter_id: Stored, - pub(crate) queue_group: hal::queue::QueueGroup, - pub(crate) cmd_allocator: command::CommandAllocator, - mem_allocator: Mutex>, - desc_allocator: Mutex>, + pub(crate) queue: A::Queue, + //pub(crate) cmd_allocator: command::CommandAllocator, + //mem_allocator: Mutex>, + //desc_allocator: Mutex>, //Note: The submission index here corresponds to the last submission that is done. pub(crate) life_guard: LifeGuard, pub(crate) active_submission_index: SubmissionIndex, /// Has to be locked temporarily only (locked last) pub(crate) trackers: Mutex, - pub(crate) render_passes: Mutex>, // Life tracker should be locked right after the device and before anything else. - life_tracker: Mutex>, + life_tracker: Mutex>, temp_suspected: life::SuspectedResources, - pub(crate) hal_limits: hal::Limits, - pub(crate) private_features: PrivateFeatures, + pub(crate) alignments: hal::Alignments, pub(crate) limits: wgt::Limits, pub(crate) features: wgt::Features, - pub(crate) downlevel: wgt::DownlevelProperties, + pub(crate) downlevel: wgt::DownlevelCapabilities, spv_options: naga::back::spv::Options, //TODO: move this behind another mutex. This would allow several methods to switch // to borrow Device immutably, such as `write_buffer`, `write_texture`, and `buffer_unmap`. - pending_writes: queue::PendingWrites, + pending_writes: queue::PendingWrites, #[cfg(feature = "trace")] pub(crate) trace: Option>, } @@ -299,24 +236,16 @@ pub enum CreateDeviceError { OutOfMemory, } -impl Device { +impl Device { #[allow(clippy::too_many_arguments)] pub(crate) fn new( - raw: B::Device, + device: hal::OpenDevice, adapter_id: Stored, - queue_group: hal::queue::QueueGroup, - mem_props: hal::adapter::MemoryProperties, - hal_limits: hal::Limits, - private_features: PrivateFeatures, - downlevel: wgt::DownlevelProperties, + alignments: hal::Alignments, + downlevel: wgt::DownlevelCapabilities, desc: &DeviceDescriptor, trace_path: Option<&std::path::Path>, ) -> Result { - let cmd_allocator = command::CommandAllocator::new(queue_group.family, &raw) - .or(Err(CreateDeviceError::OutOfMemory))?; - - let mem_allocator = alloc::MemoryAllocator::new(mem_props, hal_limits); - let descriptors = descriptor::DescriptorAllocator::new(); #[cfg(not(feature = "trace"))] if let Some(_) = trace_path { log::error!("Feature 'trace' is not enabled"); @@ -352,19 +281,12 @@ impl Device { }; Ok(Self { - raw, + raw: device.device, adapter_id, - cmd_allocator, - mem_allocator: Mutex::new(mem_allocator), - desc_allocator: Mutex::new(descriptors), - queue_group, + queue: device.queue, life_guard: LifeGuard::new(""), active_submission_index: 0, - trackers: Mutex::new(TrackerSet::new(B::VARIANT)), - render_passes: Mutex::new(RenderPassLock { - render_passes: FastHashMap::default(), - framebuffers: FastHashMap::default(), - }), + trackers: Mutex::new(TrackerSet::new(A::VARIANT)), life_tracker: Mutex::new(life::LifetimeTracker::new()), temp_suspected: life::SuspectedResources::default(), #[cfg(feature = "trace")] @@ -372,7 +294,7 @@ impl Device { Ok(mut trace) => { trace.add(trace::Action::Init { desc: desc.clone(), - backend: B::VARIANT, + backend: A::VARIANT, }); Some(Mutex::new(trace)) } @@ -381,8 +303,7 @@ impl Device { None } }), - hal_limits, - private_features, + alignments, limits: desc.limits.clone(), features: desc.features, downlevel, @@ -404,9 +325,9 @@ impl Device { } fn lock_life_internal<'this, 'token: 'this>( - tracker: &'this Mutex>, + tracker: &'this Mutex>, _token: &mut Token<'token, Self>, - ) -> MutexGuard<'this, life::LifetimeTracker> { + ) -> MutexGuard<'this, life::LifetimeTracker> { tracker.lock() } @@ -414,13 +335,13 @@ impl Device { &'this self, //TODO: fix this - the token has to be borrowed for the lock token: &mut Token<'token, Self>, - ) -> MutexGuard<'this, life::LifetimeTracker> { + ) -> MutexGuard<'this, life::LifetimeTracker> { Self::lock_life_internal(&self.life_tracker, token) } fn maintain<'this, 'token: 'this, G: GlobalIdentityHandlerFactory>( &'this self, - hub: &Hub, + hub: &Hub, force_wait: bool, token: &mut Token<'token, Self>, ) -> Result, WaitIdleError> { @@ -448,7 +369,7 @@ impl Device { fn untrack<'this, 'token: 'this, G: GlobalIdentityHandlerFactory>( &'this mut self, - hub: &Hub, + hub: &Hub, trackers: &TrackerSet, mut token: &mut Token<'token, Self>, ) { @@ -517,89 +438,37 @@ impl Device { self_id: id::DeviceId, desc: &resource::BufferDescriptor, transient: bool, - ) -> Result, resource::CreateBufferError> { - debug_assert_eq!(self_id.backend(), B::VARIANT); - let (mut usage, _memory_properties) = conv::map_buffer_usage(desc.usage); + ) -> Result, resource::CreateBufferError> { + debug_assert_eq!(self_id.backend(), A::VARIANT); + let mut usage = desc.usage; if desc.mapped_at_creation { if desc.size % wgt::COPY_BUFFER_ALIGNMENT != 0 { return Err(resource::CreateBufferError::UnalignedSize); } if !desc.usage.contains(wgt::BufferUsage::MAP_WRITE) { // we are going to be copying into it, internally - usage |= hal::buffer::Usage::TRANSFER_DST; + usage |= wgt::BufferUsage::COPY_DST; } } else { // We are required to zero out (initialize) all memory. // This is done on demand using fill_buffer which requires write transfer usage! - usage |= hal::buffer::Usage::TRANSFER_DST; + usage |= wgt::BufferUsage::TRANSFER_DST; } if desc.usage.is_empty() { return Err(resource::CreateBufferError::EmptyUsage); } - let mem_usage = { - use gpu_alloc::UsageFlags as Uf; - use wgt::BufferUsage as Bu; - - let mut flags = Uf::empty(); - let map_flags = desc.usage & (Bu::MAP_READ | Bu::MAP_WRITE); - let map_copy_flags = - desc.usage & (Bu::MAP_READ | Bu::MAP_WRITE | Bu::COPY_SRC | Bu::COPY_DST); - if map_flags.is_empty() || !(desc.usage - map_copy_flags).is_empty() { - flags |= Uf::FAST_DEVICE_ACCESS; - } - if transient { - flags |= Uf::TRANSIENT; - } - - if !map_flags.is_empty() { - let upload_usage = Bu::MAP_WRITE | Bu::COPY_SRC; - let download_usage = Bu::MAP_READ | Bu::COPY_DST; - - flags |= Uf::HOST_ACCESS; - if desc.usage.contains(upload_usage) { - flags |= Uf::UPLOAD; - } - if desc.usage.contains(download_usage) { - flags |= Uf::DOWNLOAD; - } - - let is_native_only = self - .features - .contains(wgt::Features::MAPPABLE_PRIMARY_BUFFERS); - if !is_native_only - && !upload_usage.contains(desc.usage) - && !download_usage.contains(desc.usage) - { - return Err(resource::CreateBufferError::UsageMismatch(desc.usage)); - } - } - - flags - }; - - let mut buffer = unsafe { - self.raw - .create_buffer(desc.size.max(1), usage, hal::memory::SparseFlags::empty()) + let buffer = unsafe { + self.raw.create_buffer(&resource::BufferDescriptor { + usage, + ..desc.clone() + }) } - .map_err(|err| match err { - hal::buffer::CreationError::OutOfMemory(_) => DeviceError::OutOfMemory, - _ => panic!("failed to create buffer: {}", err), - })?; - if let Some(ref label) = desc.label { - unsafe { self.raw.set_buffer_name(&mut buffer, label) }; - } - - let requirements = unsafe { self.raw.get_buffer_requirements(&buffer) }; - let block = self - .mem_allocator - .lock() - .allocate(&self.raw, requirements, mem_usage)?; - block.bind_buffer(&self.raw, &mut buffer)?; + .map_err(DeviceError::from)?; Ok(resource::Buffer { - raw: Some((buffer, block)), + raw: Some(buffer), device_id: Stored { value: id::Valid(self_id), ref_count: self.life_guard.add_ref(), @@ -616,10 +485,10 @@ impl Device { fn create_texture( &self, self_id: id::DeviceId, - adapter: &crate::instance::Adapter, + adapter: &crate::instance::Adapter, desc: &resource::TextureDescriptor, - ) -> Result, resource::CreateTextureError> { - debug_assert_eq!(self_id.backend(), B::VARIANT); + ) -> Result, resource::CreateTextureError> { + debug_assert_eq!(self_id.backend(), A::VARIANT); let format_desc = desc.format.describe(); self.require_features(format_desc.required_features) @@ -659,91 +528,31 @@ impl Device { )); } - let kind = conv::map_texture_dimension_size( + conv::check_texture_dimension_size( desc.dimension, desc.size, desc.sample_count, &self.limits, )?; - let format = conv::map_texture_format(desc.format, self.private_features); - let aspects = format.surface_desc().aspects; - let usage = conv::map_texture_usage(desc.usage, aspects); - let mip_level_count = desc.mip_level_count; - if mip_level_count == 0 - || mip_level_count > MAX_MIP_LEVELS - || mip_level_count > kind.compute_num_levels() as u32 - { - return Err(resource::CreateTextureError::InvalidMipLevelCount( - mip_level_count, - )); + let mips = desc.mip_level_count; + if mips == 0 || mips > MAX_MIP_LEVELS || mips > desc.extent.max_mips() as u32 { + return Err(resource::CreateTextureError::InvalidMipLevelCount(mips)); } - let mut view_caps = hal::image::ViewCapabilities::empty(); - // 2D textures with array layer counts that are multiples of 6 could be cubemaps - // Following gpuweb/gpuweb#68 always add the hint in that case - if desc.dimension == TextureDimension::D2 - && desc.size.depth_or_array_layers % 6 == 0 - && (desc.size.depth_or_array_layers == 6 - || self - .downlevel - .flags - .contains(wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES)) - { - view_caps |= hal::image::ViewCapabilities::KIND_CUBE; - }; - // TODO: 2D arrays, cubemap arrays - - let mut image = unsafe { - let mut image = self - .raw - .create_image( - kind, - desc.mip_level_count as hal::image::Level, - format, - hal::image::Tiling::Optimal, - usage, - hal::memory::SparseFlags::empty(), - view_caps, - ) - .map_err(|err| match err { - hal::image::CreationError::OutOfMemory(_) => DeviceError::OutOfMemory, - _ => panic!("failed to create texture: {}", err), - })?; - if let Some(ref label) = desc.label { - self.raw.set_image_name(&mut image, label); - } - image - }; - - let requirements = unsafe { self.raw.get_image_requirements(&image) }; - let block = self.mem_allocator.lock().allocate( - &self.raw, - requirements, - gpu_alloc::UsageFlags::FAST_DEVICE_ACCESS, - )?; - block.bind_image(&self.raw, &mut image)?; + let mut image = unsafe { self.raw.create_image(desc).map_err(DeviceError::from)? }; Ok(resource::Texture { - raw: Some((image, block)), + raw: Some(image), device_id: Stored { value: id::Valid(self_id), ref_count: self.life_guard.add_ref(), }, - usage: desc.usage, - aspects, - dimension: desc.dimension, - kind, - format: desc.format, + desc: desc.map_label(|_| ()), format_features, - framebuffer_attachment: hal::image::FramebufferAttachment { - usage, - view_caps, - format, - }, full_range: TextureSelector { - levels: 0..desc.mip_level_count as hal::image::Level, - layers: 0..kind.num_layers(), + levels: 0..desc.mip_level_count as hal::MipLevel, + layers: 0..desc.array_layer_count as hal::ArrayLayer, }, life_guard: LifeGuard::new(desc.label.borrow_or_default()), }) @@ -751,10 +560,10 @@ impl Device { fn create_texture_view( &self, - texture: &resource::Texture, + texture: &resource::Texture, texture_id: id::TextureId, desc: &resource::TextureViewDescriptor, - ) -> Result, resource::CreateTextureViewError> { + ) -> Result, resource::CreateTextureViewError> { let &(ref texture_raw, _) = texture .raw .as_ref() @@ -763,8 +572,6 @@ impl Device { let view_dim = match desc.dimension { Some(dim) => { - use hal::image::Kind; - let required_tex_dim = dim.compatible_texture_dimension(); if required_tex_dim != texture.dimension { @@ -796,15 +603,16 @@ impl Device { dim } - None => match texture.kind { - hal::image::Kind::D1(..) => wgt::TextureViewDimension::D1, - hal::image::Kind::D2(_, _, depth, _) - if depth > 1 && desc.range.array_layer_count.is_none() => + None => match texture.desc.dimension { + wgt::TextureDimension::D1 => wgt::TextureViewDimension::D1, + wgt::TextureDimension::D2 + if texture.desc.array_layer_count > 1 + && desc.range.array_layer_count.is_none() => { wgt::TextureViewDimension::D2Array } - hal::image::Kind::D2(..) => wgt::TextureViewDimension::D2, - hal::image::Kind::D3(..) => wgt::TextureViewDimension::D3, + wgt::TextureDimension::D2 => wgt::TextureViewDimension::D2, + wgt::TextureDimension::D3 => wgt::TextureViewDimension::D3, }, }; @@ -827,15 +635,16 @@ impl Device { }); }; - let aspects = match desc.range.aspect { - wgt::TextureAspect::All => texture.aspects, - wgt::TextureAspect::DepthOnly => hal::format::Aspects::DEPTH, - wgt::TextureAspect::StencilOnly => hal::format::Aspects::STENCIL, + let full_aspect = hal::FormatAspect::from(texture.desc.format); + let aspect = match desc.range.aspect { + wgt::TextureAspect::All => full_aspect, + wgt::TextureAspect::DepthOnly => hal::FormatAspect::DEPTH, + wgt::TextureAspect::StencilOnly => hal::FormatAspect::STENCIL, }; - if !texture.aspects.contains(aspects) { + if !full_aspect.contains(aspect) { return Err(resource::CreateTextureViewError::InvalidAspect { - requested: aspects, - total: texture.aspects, + requested: aspect, + total: full_aspect, }); } @@ -868,31 +677,22 @@ impl Device { }); } - let format = desc.format.unwrap_or(texture.format); - let range = hal::image::SubresourceRange { - aspects, - level_start: desc.range.base_mip_level as _, - level_count: desc.range.mip_level_count.map(|v| v.get() as _), - layer_start: desc.range.base_array_layer as _, - layer_count: desc.range.array_layer_count.map(|v| v.get() as _), + let mut extent = texture.desc.extent.at_level(desc.range.base_mip_level as _); + if view_dim != wgt::TextureViewDimension::D3 { + extent.depth_or_array_layers = view_layer_count; + } + + let hal_desc = hal::TextureViewDescriptor { + label: desc.label, + format: desc.format.unwrap_or(texture.format), + dimension: view_dim, + range: desc.range.clone(), }; - let hal_extent = texture - .kind - .extent() - .at_level(desc.range.base_mip_level as _); let raw = unsafe { self.raw - .create_image_view( - texture_raw, - conv::map_texture_view_dimension(view_dim), - conv::map_texture_format(format, self.private_features), - hal::format::Swizzle::NO, - // conservatively assume the same usage - conv::map_texture_usage(texture.usage, aspects), - range, - ) - .or(Err(resource::CreateTextureViewError::OutOfMemory))? + .create_image_view(texture_raw, &hal_desc) + .map_err(DeviceError::from)? }; Ok(resource::TextureView { @@ -903,17 +703,10 @@ impl Device { ref_count: texture.life_guard.add_ref(), }, }, - aspects, - format: texture.format, + desc: hal_desc.map_label(|_| ()), format_features: texture.format_features, - dimension: view_dim, - extent: wgt::Extent3d { - width: hal_extent.width, - height: hal_extent.height, - depth_or_array_layers: view_layer_count, - }, + extent, samples: texture.kind.num_samples(), - framebuffer_attachment: texture.framebuffer_attachment.clone(), // once a storage - forever a storage sampled_internal_use: if texture.usage.contains(wgt::TextureUsage::STORAGE) { resource::TextureUse::SAMPLED | resource::TextureUse::STORAGE_LOAD @@ -929,7 +722,7 @@ impl Device { &self, self_id: id::DeviceId, desc: &resource::SamplerDescriptor, - ) -> Result, resource::CreateSamplerError> { + ) -> Result, resource::CreateSamplerError> { if desc .address_modes .iter() @@ -938,13 +731,19 @@ impl Device { self.require_features(wgt::Features::ADDRESS_MODE_CLAMP_TO_BORDER)?; } - let actual_clamp = if let Some(clamp) = desc.anisotropy_clamp { + let lod_clamp = if desc.lod_min_clamp > 0.0 || desc.load_max_clamp < 32.0 { + Some(desc.lod_min_clamp..desc.lod_max_clamp) + } else { + None + }; + + let anisotropy_clamp = if let Some(clamp) = desc.anisotropy_clamp { let clamp = clamp.get(); - let valid_clamp = clamp <= MAX_ANISOTROPY && conv::is_power_of_two(clamp as u32); + let valid_clamp = clamp <= hal::MAX_ANISOTROPY && conv::is_power_of_two(clamp as u32); if !valid_clamp { return Err(resource::CreateSamplerError::InvalidClamp(clamp)); } - if self.private_features.anisotropic_filtering { + if self.downlevel.anisotropic_filtering { Some(clamp) } else { None @@ -953,45 +752,19 @@ impl Device { None }; - let border = match desc.border_color { - None | Some(wgt::SamplerBorderColor::TransparentBlack) => { - hal::image::BorderColor::TransparentBlack - } - Some(wgt::SamplerBorderColor::OpaqueBlack) => hal::image::BorderColor::OpaqueBlack, - Some(wgt::SamplerBorderColor::OpaqueWhite) => hal::image::BorderColor::OpaqueWhite, + let hal_desc = hal::SamplerDescriptor { + label: desc.label, + address_modes: desc.address_modes, + mag_filter: desc.mag_filter, + min_filter: desc.min_filter, + mipmap_filter: desc.mipmap_filter, + lod_clamp, + compare: desc.compare, + anisotropy_clamp, + border_color: desc.border_color, }; - let filtering = [desc.min_filter, desc.mag_filter, desc.mipmap_filter] - .contains(&wgt::FilterMode::Linear); - - let info = hal::image::SamplerDesc { - min_filter: conv::map_filter(desc.min_filter), - mag_filter: conv::map_filter(desc.mag_filter), - mip_filter: conv::map_filter(desc.mipmap_filter), - reduction_mode: hal::image::ReductionMode::WeightedAverage, - wrap_mode: ( - conv::map_wrap(desc.address_modes[0]), - conv::map_wrap(desc.address_modes[1]), - conv::map_wrap(desc.address_modes[2]), - ), - lod_bias: hal::image::Lod(0.0), - lod_range: hal::image::Lod(desc.lod_min_clamp)..hal::image::Lod(desc.lod_max_clamp), - comparison: desc.compare.map(conv::map_compare_function), - border, - normalized: true, - anisotropy_clamp: actual_clamp, - }; - - let raw = unsafe { - self.raw.create_sampler(&info).map_err(|err| match err { - hal::device::AllocationError::OutOfMemory(_) => { - resource::CreateSamplerError::Device(DeviceError::OutOfMemory) - } - hal::device::AllocationError::TooManyObjects => { - resource::CreateSamplerError::TooManyObjects - } - })? - }; + let raw = unsafe { self.raw.create_sampler(desc).map_err(DeviceError::from)? }; Ok(resource::Sampler { raw, device_id: Stored { @@ -999,8 +772,9 @@ impl Device { ref_count: self.life_guard.add_ref(), }, life_guard: LifeGuard::new(desc.label.borrow_or_default()), - comparison: info.comparison.is_some(), - filtering, + comparison: desc.compare.is_some(), + filtering: desc.min_filter == wgt::FilterMode::Linear + || desc.mag_filter == wgt::FilterMode::Linear, }) } @@ -1009,7 +783,7 @@ impl Device { self_id: id::DeviceId, desc: &pipeline::ShaderModuleDescriptor<'a>, source: pipeline::ShaderModuleSource<'a>, - ) -> Result, pipeline::CreateShaderModuleError> { + ) -> Result, pipeline::CreateShaderModuleError> { // First, try to produce a Naga module. let (spv, module) = match source { pipeline::ShaderModuleSource::SpirV(spv) => { @@ -1177,7 +951,7 @@ impl Device { fn deduplicate_bind_group_layout( self_id: id::DeviceId, entry_map: &binding_model::BindEntryMap, - guard: &Storage, id::BindGroupLayoutId>, + guard: &Storage, id::BindGroupLayoutId>, ) -> Option { guard .iter(self_id.backend()) @@ -1189,9 +963,9 @@ impl Device { } fn get_introspection_bind_group_layouts<'a>( - pipeline_layout: &binding_model::PipelineLayout, - bgl_guard: &'a Storage, id::BindGroupLayoutId>, - ) -> ArrayVec<[&'a binding_model::BindEntryMap; MAX_BIND_GROUPS]> { + pipeline_layout: &binding_model::PipelineLayout, + bgl_guard: &'a Storage, id::BindGroupLayoutId>, + ) -> ArrayVec<[&'a binding_model::BindEntryMap; hal::MAX_BIND_GROUPS]> { pipeline_layout .bind_group_layout_ids .iter() @@ -1204,7 +978,7 @@ impl Device { self_id: id::DeviceId, label: Option<&str>, entry_map: binding_model::BindEntryMap, - ) -> Result, binding_model::CreateBindGroupLayoutError> { + ) -> Result, binding_model::CreateBindGroupLayoutError> { let mut desc_count = descriptor::DescriptorTotalCount::default(); for entry in entry_map.values() { use wgt::BindingType as Bt; @@ -1348,7 +1122,7 @@ impl Device { used_buffer_ranges: &mut Vec>, dynamic_binding_info: &mut Vec, used: &mut TrackerSet, - storage: &'a Storage, id::BufferId>, + storage: &'a Storage, id::BufferId>, limits: &wgt::Limits, ) -> Result, binding_model::CreateBindGroupError> { use crate::binding_model::CreateBindGroupError as Error; @@ -1457,11 +1231,11 @@ impl Device { fn create_bind_group( &self, self_id: id::DeviceId, - layout: &binding_model::BindGroupLayout, + layout: &binding_model::BindGroupLayout, desc: &binding_model::BindGroupDescriptor, - hub: &Hub, - token: &mut Token>, - ) -> Result, binding_model::CreateBindGroupError> { + hub: &Hub, + token: &mut Token>, + ) -> Result, binding_model::CreateBindGroupError> { use crate::binding_model::{BindingResource as Br, CreateBindGroupError as Error}; { // Check that the number of entries in the descriptor matches @@ -1477,7 +1251,7 @@ impl Device { // Record binding info for dynamic offset validation let mut dynamic_binding_info = Vec::new(); // fill out the descriptors - let mut used = TrackerSet::new(B::VARIANT); + let mut used = TrackerSet::new(A::VARIANT); let (buffer_guard, mut token) = hub.buffers.read(token); let (texture_guard, mut token) = hub.textures.read(&mut token); //skip token @@ -1678,7 +1452,7 @@ impl Device { }; if view .aspects - .contains(hal::format::Aspects::DEPTH | hal::format::Aspects::STENCIL) + .contains(hal::FormatAspect::DEPTH | hal::FormatAspect::STENCIL) { return Err(Error::DepthStencilAspect); } @@ -1819,8 +1593,8 @@ impl Device { &self, self_id: id::DeviceId, desc: &binding_model::PipelineLayoutDescriptor, - bgl_guard: &Storage, id::BindGroupLayoutId>, - ) -> Result, binding_model::CreatePipelineLayoutError> { + bgl_guard: &Storage, id::BindGroupLayoutId>, + ) -> Result, binding_model::CreatePipelineLayoutError> { use crate::binding_model::CreatePipelineLayoutError as Error; let bind_group_layouts_count = desc.bind_group_layouts.len(); @@ -1929,9 +1703,9 @@ impl Device { &self, self_id: id::DeviceId, implicit_context: Option, - mut derived_group_layouts: ArrayVec<[binding_model::BindEntryMap; MAX_BIND_GROUPS]>, - bgl_guard: &mut Storage, id::BindGroupLayoutId>, - pipeline_layout_guard: &mut Storage, id::PipelineLayoutId>, + mut derived_group_layouts: ArrayVec<[binding_model::BindEntryMap; hal::MAX_BIND_GROUPS]>, + bgl_guard: &mut Storage, id::BindGroupLayoutId>, + pipeline_layout_guard: &mut Storage, id::PipelineLayoutId>, ) -> Result { while derived_group_layouts .last() @@ -1977,9 +1751,9 @@ impl Device { self_id: id::DeviceId, desc: &pipeline::ComputePipelineDescriptor, implicit_context: Option, - hub: &Hub, + hub: &Hub, token: &mut Token, - ) -> Result, pipeline::CreateComputePipelineError> { + ) -> Result, pipeline::CreateComputePipelineError> { //TODO: only lock mutable if the layout is derived let (mut pipeline_layout_guard, mut token) = hub.pipeline_layouts.write(token); let (mut bgl_guard, mut token) = hub.bind_group_layouts.write(&mut token); @@ -2002,7 +1776,7 @@ impl Device { } let mut derived_group_layouts = - ArrayVec::<[binding_model::BindEntryMap; MAX_BIND_GROUPS]>::new(); + ArrayVec::<[binding_model::BindEntryMap; hal::MAX_BIND_GROUPS]>::new(); let io = validation::StageIo::default(); let (shader_module_guard, _) = hub.shader_modules.read(&mut token); @@ -2039,7 +1813,7 @@ impl Device { return Err(pipeline::ImplicitLayoutError::ReflectionError(flag).into()); } - let shader = hal::pso::EntryPoint:: { + let shader = hal::pso::EntryPoint:: { entry: &entry_point_name, // TODO module: &shader_module.raw, specialization: hal::pso::Specialization::EMPTY, @@ -2108,9 +1882,9 @@ impl Device { self_id: id::DeviceId, desc: &pipeline::RenderPipelineDescriptor, implicit_context: Option, - hub: &Hub, + hub: &Hub, token: &mut Token, - ) -> Result, pipeline::CreateRenderPipelineError> { + ) -> Result, pipeline::CreateRenderPipelineError> { //TODO: only lock mutable if the layout is derived let (mut pipeline_layout_guard, mut token) = hub.pipeline_layouts.write(token); let (mut bgl_guard, mut token) = hub.bind_group_layouts.write(&mut token); @@ -2125,7 +1899,7 @@ impl Device { } let mut derived_group_layouts = - ArrayVec::<[binding_model::BindEntryMap; MAX_BIND_GROUPS]>::new(); + ArrayVec::<[binding_model::BindEntryMap; hal::MAX_BIND_GROUPS]>::new(); let color_states = desc .fragment @@ -2426,7 +2200,7 @@ impl Device { validated_stages |= flag; } - hal::pso::EntryPoint:: { + hal::pso::EntryPoint:: { entry: &stage.entry_point, module: &shader_module.raw, specialization: hal::pso::Specialization::EMPTY, @@ -2474,7 +2248,7 @@ impl Device { } } - Some(hal::pso::EntryPoint:: { + Some(hal::pso::EntryPoint:: { entry: &entry_point_name, module: &shader_module.raw, specialization: hal::pso::Specialization::EMPTY, @@ -2656,7 +2430,7 @@ impl Device { &self, self_id: id::DeviceId, desc: &wgt::QuerySetDescriptor, - ) -> Result, resource::CreateQuerySetError> { + ) -> Result, resource::CreateQuerySetError> { use resource::CreateQuerySetError as Error; match desc.ty { @@ -2694,14 +2468,14 @@ impl Device { } } -impl Device { - pub(crate) fn destroy_bind_group(&self, bind_group: binding_model::BindGroup) { +impl Device { + pub(crate) fn destroy_bind_group(&self, bind_group: binding_model::BindGroup) { self.desc_allocator .lock() .free(&self.raw, iter::once(bind_group.raw)); } - pub(crate) fn destroy_buffer(&self, buffer: resource::Buffer) { + pub(crate) fn destroy_buffer(&self, buffer: resource::Buffer) { if let Some((raw, memory)) = buffer.raw { unsafe { self.mem_allocator.lock().free(&self.raw, memory); @@ -2710,7 +2484,7 @@ impl Device { } } - pub(crate) fn destroy_texture(&self, texture: resource::Texture) { + pub(crate) fn destroy_texture(&self, texture: resource::Texture) { if let Some((raw, memory)) = texture.raw { unsafe { self.mem_allocator.lock().free(&self.raw, memory); @@ -2748,7 +2522,7 @@ impl Device { } } -impl crate::hub::Resource for Device { +impl crate::hub::Resource for Device { const TYPE: &'static str = "Device"; fn life_guard(&self) -> &LifeGuard { @@ -2808,7 +2582,7 @@ pub struct MissingFeatures(pub wgt::Features); #[cfg_attr(feature = "replay", derive(serde::Deserialize))] pub struct ImplicitPipelineContext { pub root_id: id::PipelineLayoutId, - pub group_ids: ArrayVec<[id::BindGroupLayoutId; MAX_BIND_GROUPS]>, + pub group_ids: ArrayVec<[id::BindGroupLayoutId; hal::MAX_BIND_GROUPS]>, } pub struct ImplicitPipelineIds<'a, G: GlobalIdentityHandlerFactory> { @@ -2817,7 +2591,7 @@ pub struct ImplicitPipelineIds<'a, G: GlobalIdentityHandlerFactory> { } impl ImplicitPipelineIds<'_, G> { - fn prepare(self, hub: &Hub) -> ImplicitPipelineContext { + fn prepare(self, hub: &Hub) -> ImplicitPipelineContext { ImplicitPipelineContext { root_id: hub.pipeline_layouts.prepare(self.root_id).into_id(), group_ids: self @@ -2830,12 +2604,12 @@ impl ImplicitPipelineIds<'_, G> { } impl Global { - pub fn adapter_get_swap_chain_preferred_format( + pub fn adapter_get_swap_chain_preferred_format( &self, adapter_id: id::AdapterId, surface_id: id::SurfaceId, ) -> Result { - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (mut surface_guard, mut token) = self.surfaces.write(&mut token); @@ -2850,11 +2624,11 @@ impl Global { adapter.get_swap_chain_preferred_format(surface) } - pub fn device_features( + pub fn device_features( &self, device_id: id::DeviceId, ) -> Result { - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, _) = hub.devices.read(&mut token); let device = device_guard.get(device_id).map_err(|_| InvalidDevice)?; @@ -2862,11 +2636,11 @@ impl Global { Ok(device.features) } - pub fn device_limits( + pub fn device_limits( &self, device_id: id::DeviceId, ) -> Result { - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, _) = hub.devices.read(&mut token); let device = device_guard.get(device_id).map_err(|_| InvalidDevice)?; @@ -2874,11 +2648,11 @@ impl Global { Ok(device.limits.clone()) } - pub fn device_downlevel_properties( + pub fn device_downlevel_properties( &self, device_id: id::DeviceId, - ) -> Result { - let hub = B::hub(self); + ) -> Result { + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, _) = hub.devices.read(&mut token); let device = device_guard.get(device_id).map_err(|_| InvalidDevice)?; @@ -2886,7 +2660,7 @@ impl Global { Ok(device.downlevel) } - pub fn device_create_buffer( + pub fn device_create_buffer( &self, device_id: id::DeviceId, desc: &resource::BufferDescriptor, @@ -2894,7 +2668,7 @@ impl Global { ) -> (id::BufferId, Option) { profiling::scope!("create_buffer", "Device"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let fid = hub.buffers.prepare(id_in); @@ -3017,12 +2791,12 @@ impl Global { } #[cfg(feature = "replay")] - pub fn device_wait_for_buffer( + pub fn device_wait_for_buffer( &self, device_id: id::DeviceId, buffer_id: id::BufferId, ) -> Result<(), WaitIdleError> { - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); let last_submission = { @@ -3039,7 +2813,7 @@ impl Global { .wait_for_submit(last_submission, &mut token) } - pub fn device_set_buffer_sub_data( + pub fn device_set_buffer_sub_data( &self, device_id: id::DeviceId, buffer_id: id::BufferId, @@ -3048,7 +2822,7 @@ impl Global { ) -> Result<(), resource::BufferAccessError> { profiling::scope!("set_buffer_sub_data", "Device"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); @@ -3084,7 +2858,7 @@ impl Global { Ok(()) } - pub fn device_get_buffer_sub_data( + pub fn device_get_buffer_sub_data( &self, device_id: id::DeviceId, buffer_id: id::BufferId, @@ -3093,7 +2867,7 @@ impl Global { ) -> Result<(), resource::BufferAccessError> { profiling::scope!("get_buffer_sub_data", "Device"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); @@ -3117,17 +2891,17 @@ impl Global { Ok(()) } - pub fn buffer_label(&self, id: id::BufferId) -> String { - B::hub(self).buffers.label_for_resource(id) + pub fn buffer_label(&self, id: id::BufferId) -> String { + A::hub(self).buffers.label_for_resource(id) } - pub fn buffer_destroy( + pub fn buffer_destroy( &self, buffer_id: id::BufferId, ) -> Result<(), resource::DestroyError> { profiling::scope!("destroy", "Buffer"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); //TODO: lock pending writes separately, keep the device read-only @@ -3167,10 +2941,10 @@ impl Global { Ok(()) } - pub fn buffer_drop(&self, buffer_id: id::BufferId, wait: bool) { + pub fn buffer_drop(&self, buffer_id: id::BufferId, wait: bool) { profiling::scope!("drop", "Buffer"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); log::info!("Buffer {:?} is dropped", buffer_id); @@ -3216,7 +2990,7 @@ impl Global { } } - pub fn device_create_texture( + pub fn device_create_texture( &self, device_id: id::DeviceId, desc: &resource::TextureDescriptor, @@ -3224,7 +2998,7 @@ impl Global { ) -> (id::TextureId, Option) { profiling::scope!("create_texture", "Device"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let fid = hub.textures.prepare(id_in); @@ -3267,17 +3041,17 @@ impl Global { (id, Some(error)) } - pub fn texture_label(&self, id: id::TextureId) -> String { - B::hub(self).textures.label_for_resource(id) + pub fn texture_label(&self, id: id::TextureId) -> String { + A::hub(self).textures.label_for_resource(id) } - pub fn texture_destroy( + pub fn texture_destroy( &self, texture_id: id::TextureId, ) -> Result<(), resource::DestroyError> { profiling::scope!("destroy", "Texture"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); //TODO: lock pending writes separately, keep the device read-only @@ -3317,10 +3091,10 @@ impl Global { Ok(()) } - pub fn texture_drop(&self, texture_id: id::TextureId, wait: bool) { + pub fn texture_drop(&self, texture_id: id::TextureId, wait: bool) { profiling::scope!("drop", "Texture"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (ref_count, last_submit_index, device_id) = { @@ -3366,7 +3140,7 @@ impl Global { } } - pub fn texture_create_view( + pub fn texture_create_view( &self, texture_id: id::TextureId, desc: &resource::TextureViewDescriptor, @@ -3374,7 +3148,7 @@ impl Global { ) -> (id::TextureViewId, Option) { profiling::scope!("create_view", "Texture"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let fid = hub.texture_views.prepare(id_in); @@ -3415,18 +3189,18 @@ impl Global { (id, Some(error)) } - pub fn texture_view_label(&self, id: id::TextureViewId) -> String { - B::hub(self).texture_views.label_for_resource(id) + pub fn texture_view_label(&self, id: id::TextureViewId) -> String { + A::hub(self).texture_views.label_for_resource(id) } - pub fn texture_view_drop( + pub fn texture_view_drop( &self, texture_view_id: id::TextureViewId, wait: bool, ) -> Result<(), resource::TextureViewDestroyError> { profiling::scope!("drop", "TextureView"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (last_submit_index, device_id) = { @@ -3477,7 +3251,7 @@ impl Global { Ok(()) } - pub fn device_create_sampler( + pub fn device_create_sampler( &self, device_id: id::DeviceId, desc: &resource::SamplerDescriptor, @@ -3485,7 +3259,7 @@ impl Global { ) -> (id::SamplerId, Option) { profiling::scope!("create_sampler", "Device"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let fid = hub.samplers.prepare(id_in); @@ -3522,14 +3296,14 @@ impl Global { (id, Some(error)) } - pub fn sampler_label(&self, id: id::SamplerId) -> String { - B::hub(self).samplers.label_for_resource(id) + pub fn sampler_label(&self, id: id::SamplerId) -> String { + A::hub(self).samplers.label_for_resource(id) } - pub fn sampler_drop(&self, sampler_id: id::SamplerId) { + pub fn sampler_drop(&self, sampler_id: id::SamplerId) { profiling::scope!("drop", "Sampler"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let device_id = { @@ -3555,7 +3329,7 @@ impl Global { .push(id::Valid(sampler_id)); } - pub fn device_create_bind_group_layout( + pub fn device_create_bind_group_layout( &self, device_id: id::DeviceId, desc: &binding_model::BindGroupLayoutDescriptor, @@ -3567,7 +3341,7 @@ impl Global { profiling::scope!("create_bind_group_layout", "Device"); let mut token = Token::root(); - let hub = B::hub(self); + let hub = A::hub(self); let fid = hub.bind_group_layouts.prepare(id_in); let error = 'outer: loop { @@ -3621,17 +3395,14 @@ impl Global { (id, Some(error)) } - pub fn bind_group_layout_label(&self, id: id::BindGroupLayoutId) -> String { - B::hub(self).bind_group_layouts.label_for_resource(id) + pub fn bind_group_layout_label(&self, id: id::BindGroupLayoutId) -> String { + A::hub(self).bind_group_layouts.label_for_resource(id) } - pub fn bind_group_layout_drop( - &self, - bind_group_layout_id: id::BindGroupLayoutId, - ) { + pub fn bind_group_layout_drop(&self, bind_group_layout_id: id::BindGroupLayoutId) { profiling::scope!("drop", "BindGroupLayout"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let device_id = { let (mut bind_group_layout_guard, _) = hub.bind_group_layouts.write(&mut token); @@ -3653,7 +3424,7 @@ impl Global { .push(id::Valid(bind_group_layout_id)); } - pub fn device_create_pipeline_layout( + pub fn device_create_pipeline_layout( &self, device_id: id::DeviceId, desc: &binding_model::PipelineLayoutDescriptor, @@ -3664,7 +3435,7 @@ impl Global { ) { profiling::scope!("create_pipeline_layout", "Device"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let fid = hub.pipeline_layouts.prepare(id_in); @@ -3697,14 +3468,14 @@ impl Global { (id, Some(error)) } - pub fn pipeline_layout_label(&self, id: id::PipelineLayoutId) -> String { - B::hub(self).pipeline_layouts.label_for_resource(id) + pub fn pipeline_layout_label(&self, id: id::PipelineLayoutId) -> String { + A::hub(self).pipeline_layouts.label_for_resource(id) } - pub fn pipeline_layout_drop(&self, pipeline_layout_id: id::PipelineLayoutId) { + pub fn pipeline_layout_drop(&self, pipeline_layout_id: id::PipelineLayoutId) { profiling::scope!("drop", "PipelineLayout"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device_id, ref_count) = { let (mut pipeline_layout_guard, _) = hub.pipeline_layouts.write(&mut token); @@ -3732,7 +3503,7 @@ impl Global { }); } - pub fn device_create_bind_group( + pub fn device_create_bind_group( &self, device_id: id::DeviceId, desc: &binding_model::BindGroupDescriptor, @@ -3740,7 +3511,7 @@ impl Global { ) -> (id::BindGroupId, Option) { profiling::scope!("create_bind_group", "Device"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let fid = hub.bind_groups.prepare(id_in); @@ -3795,14 +3566,14 @@ impl Global { (id, Some(error)) } - pub fn bind_group_label(&self, id: id::BindGroupId) -> String { - B::hub(self).bind_groups.label_for_resource(id) + pub fn bind_group_label(&self, id: id::BindGroupId) -> String { + A::hub(self).bind_groups.label_for_resource(id) } - pub fn bind_group_drop(&self, bind_group_id: id::BindGroupId) { + pub fn bind_group_drop(&self, bind_group_id: id::BindGroupId) { profiling::scope!("drop", "BindGroup"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let device_id = { @@ -3828,7 +3599,7 @@ impl Global { .push(id::Valid(bind_group_id)); } - pub fn device_create_shader_module( + pub fn device_create_shader_module( &self, device_id: id::DeviceId, desc: &pipeline::ShaderModuleDescriptor, @@ -3840,7 +3611,7 @@ impl Global { ) { profiling::scope!("create_shader_module", "Device"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let fid = hub.shader_modules.prepare(id_in); @@ -3886,14 +3657,14 @@ impl Global { (id, Some(error)) } - pub fn shader_module_label(&self, id: id::ShaderModuleId) -> String { - B::hub(self).shader_modules.label_for_resource(id) + pub fn shader_module_label(&self, id: id::ShaderModuleId) -> String { + A::hub(self).shader_modules.label_for_resource(id) } - pub fn shader_module_drop(&self, shader_module_id: id::ShaderModuleId) { + pub fn shader_module_drop(&self, shader_module_id: id::ShaderModuleId) { profiling::scope!("drop", "ShaderModule"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); let (module, _) = hub.shader_modules.unregister(shader_module_id, &mut token); @@ -3911,7 +3682,7 @@ impl Global { } } - pub fn device_create_command_encoder( + pub fn device_create_command_encoder( &self, device_id: id::DeviceId, desc: &wgt::CommandEncoderDescriptor(command_buffer_id) } pub fn device_create_render_bundle_encoder( @@ -4008,7 +3779,7 @@ impl Global { (Box::into_raw(Box::new(encoder)), error) } - pub fn render_bundle_encoder_finish( + pub fn render_bundle_encoder_finish( &self, bundle_encoder: command::RenderBundleEncoder, desc: &command::RenderBundleDescriptor, @@ -4016,7 +3787,7 @@ impl Global { ) -> (id::RenderBundleId, Option) { profiling::scope!("finish", "RenderBundleEncoder"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let fid = hub.render_bundles.prepare(id_in); @@ -4060,13 +3831,13 @@ impl Global { (id, Some(error)) } - pub fn render_bundle_label(&self, id: id::RenderBundleId) -> String { - B::hub(self).render_bundles.label_for_resource(id) + pub fn render_bundle_label(&self, id: id::RenderBundleId) -> String { + A::hub(self).render_bundles.label_for_resource(id) } - pub fn render_bundle_drop(&self, render_bundle_id: id::RenderBundleId) { + pub fn render_bundle_drop(&self, render_bundle_id: id::RenderBundleId) { profiling::scope!("drop", "RenderBundle"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); @@ -4092,7 +3863,7 @@ impl Global { .push(id::Valid(render_bundle_id)); } - pub fn device_create_query_set( + pub fn device_create_query_set( &self, device_id: id::DeviceId, desc: &wgt::QuerySetDescriptor, @@ -4100,7 +3871,7 @@ impl Global { ) -> (id::QuerySetId, Option) { profiling::scope!("create_query_set", "Device"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let fid = hub.query_sets.prepare(id_in); @@ -4140,10 +3911,10 @@ impl Global { (id, Some(error)) } - pub fn query_set_drop(&self, query_set_id: id::QuerySetId) { + pub fn query_set_drop(&self, query_set_id: id::QuerySetId) { profiling::scope!("drop", "QuerySet"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let device_id = { @@ -4170,7 +3941,7 @@ impl Global { .push(id::Valid(query_set_id)); } - pub fn device_create_render_pipeline( + pub fn device_create_render_pipeline( &self, device_id: id::DeviceId, desc: &pipeline::RenderPipelineDescriptor, @@ -4182,7 +3953,7 @@ impl Global { ) { profiling::scope!("create_render_pipeline", "Device"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let fid = hub.render_pipelines.prepare(id_in); @@ -4224,7 +3995,7 @@ impl Global { /// Get an ID of one of the bind group layouts. The ID adds a refcount, /// which needs to be released by calling `bind_group_layout_drop`. - pub fn render_pipeline_get_bind_group_layout( + pub fn render_pipeline_get_bind_group_layout( &self, pipeline_id: id::RenderPipelineId, index: u32, @@ -4233,7 +4004,7 @@ impl Global { id::BindGroupLayoutId, Option, ) { - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(&mut token); @@ -4265,13 +4036,13 @@ impl Global { (id, Some(error)) } - pub fn render_pipeline_label(&self, id: id::RenderPipelineId) -> String { - B::hub(self).render_pipelines.label_for_resource(id) + pub fn render_pipeline_label(&self, id: id::RenderPipelineId) -> String { + A::hub(self).render_pipelines.label_for_resource(id) } - pub fn render_pipeline_drop(&self, render_pipeline_id: id::RenderPipelineId) { + pub fn render_pipeline_drop(&self, render_pipeline_id: id::RenderPipelineId) { profiling::scope!("drop", "RenderPipeline"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); @@ -4301,7 +4072,7 @@ impl Global { .push(layout_id); } - pub fn device_create_compute_pipeline( + pub fn device_create_compute_pipeline( &self, device_id: id::DeviceId, desc: &pipeline::ComputePipelineDescriptor, @@ -4313,7 +4084,7 @@ impl Global { ) { profiling::scope!("create_compute_pipeline", "Device"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let fid = hub.compute_pipelines.prepare(id_in); @@ -4355,7 +4126,7 @@ impl Global { /// Get an ID of one of the bind group layouts. The ID adds a refcount, /// which needs to be released by calling `bind_group_layout_drop`. - pub fn compute_pipeline_get_bind_group_layout( + pub fn compute_pipeline_get_bind_group_layout( &self, pipeline_id: id::ComputePipelineId, index: u32, @@ -4364,7 +4135,7 @@ impl Global { id::BindGroupLayoutId, Option, ) { - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (pipeline_layout_guard, mut token) = hub.pipeline_layouts.read(&mut token); @@ -4396,13 +4167,13 @@ impl Global { (id, Some(error)) } - pub fn compute_pipeline_label(&self, id: id::ComputePipelineId) -> String { - B::hub(self).compute_pipelines.label_for_resource(id) + pub fn compute_pipeline_label(&self, id: id::ComputePipelineId) -> String { + A::hub(self).compute_pipelines.label_for_resource(id) } - pub fn compute_pipeline_drop(&self, compute_pipeline_id: id::ComputePipelineId) { + pub fn compute_pipeline_drop(&self, compute_pipeline_id: id::ComputePipelineId) { profiling::scope!("drop", "ComputePipeline"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); @@ -4432,7 +4203,7 @@ impl Global { .push(layout_id); } - pub fn device_create_swap_chain( + pub fn device_create_swap_chain( &self, device_id: id::DeviceId, surface_id: id::SurfaceId, @@ -4473,8 +4244,8 @@ impl Global { } log::info!("creating swap chain {:?}", desc); - let sc_id = surface_id.to_swap_chain_id(B::VARIANT); - let hub = B::hub(self); + let sc_id = surface_id.to_swap_chain_id(A::VARIANT); + let hub = A::hub(self); let mut token = Token::root(); let (mut surface_guard, mut token) = self.surfaces.write(&mut token); @@ -4578,11 +4349,11 @@ impl Global { #[cfg(feature = "replay")] /// Only triange suspected resource IDs. This helps us to avoid ID collisions /// upon creating new resources when re-playing a trace. - pub fn device_maintain_ids( + pub fn device_maintain_ids( &self, device_id: id::DeviceId, ) -> Result<(), InvalidDevice> { - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); let device = device_guard.get(device_id).map_err(|_| InvalidDevice)?; @@ -4596,12 +4367,12 @@ impl Global { Ok(()) } - pub fn device_poll( + pub fn device_poll( &self, device_id: id::DeviceId, force_wait: bool, ) -> Result<(), WaitIdleError> { - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let callbacks = { let (device_guard, mut token) = hub.devices.read(&mut token); @@ -4614,17 +4385,17 @@ impl Global { Ok(()) } - fn poll_devices( + fn poll_devices( &self, force_wait: bool, callbacks: &mut Vec, ) -> Result<(), WaitIdleError> { profiling::scope!("poll_devices"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); - for (_, device) in device_guard.iter(B::VARIANT) { + for (_, device) in device_guard.iter(A::VARIANT) { let cbs = device.maintain(&hub, force_wait, &mut token)?; callbacks.extend(cbs); } @@ -4635,6 +4406,7 @@ impl Global { use crate::backend; let mut callbacks = Vec::new(); + /* #[cfg(vulkan)] { self.poll_devices::(force_wait, &mut callbacks)?; @@ -4651,18 +4423,19 @@ impl Global { { self.poll_devices::(force_wait, &mut callbacks)?; } + */ fire_map_callbacks(callbacks); Ok(()) } - pub fn device_label(&self, id: id::DeviceId) -> String { - B::hub(self).devices.label_for_resource(id) + pub fn device_label(&self, id: id::DeviceId) -> String { + A::hub(self).devices.label_for_resource(id) } - pub fn device_start_capture(&self, id: id::DeviceId) { - let hub = B::hub(self); + pub fn device_start_capture(&self, id: id::DeviceId) { + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, _) = hub.devices.read(&mut token); if let Ok(device) = device_guard.get(id) { @@ -4670,8 +4443,8 @@ impl Global { } } - pub fn device_stop_capture(&self, id: id::DeviceId) { - let hub = B::hub(self); + pub fn device_stop_capture(&self, id: id::DeviceId) { + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, _) = hub.devices.read(&mut token); if let Ok(device) = device_guard.get(id) { @@ -4679,10 +4452,10 @@ impl Global { } } - pub fn device_drop(&self, device_id: id::DeviceId) { + pub fn device_drop(&self, device_id: id::DeviceId) { profiling::scope!("drop", "Device"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device, _) = hub.devices.unregister(device_id, &mut token); if let Some(mut device) = device { @@ -4700,7 +4473,7 @@ impl Global { } } - pub fn buffer_map_async( + pub fn buffer_map_async( &self, buffer_id: id::BufferId, range: Range, @@ -4708,7 +4481,7 @@ impl Global { ) -> Result<(), resource::BufferAccessError> { profiling::scope!("map_async", "Buffer"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, mut token) = hub.devices.read(&mut token); let (pub_usage, internal_use) = match op.host { @@ -4763,7 +4536,7 @@ impl Global { Ok(()) } - pub fn buffer_get_mapped_range( + pub fn buffer_get_mapped_range( &self, buffer_id: id::BufferId, offset: BufferAddress, @@ -4771,7 +4544,7 @@ impl Global { ) -> Result<(*mut u8, u64), resource::BufferAccessError> { profiling::scope!("get_mapped_range", "Buffer"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (buffer_guard, _) = hub.buffers.read(&mut token); let buffer = buffer_guard @@ -4831,13 +4604,13 @@ impl Global { } } - fn buffer_unmap_inner( + fn buffer_unmap_inner( &self, buffer_id: id::BufferId, ) -> Result, resource::BufferAccessError> { profiling::scope!("unmap", "Buffer"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (mut device_guard, mut token) = hub.devices.write(&mut token); @@ -4941,17 +4714,17 @@ impl Global { } let _ = (ptr, sub_range); } - unmap_buffer(&device.raw, buffer)?; + device.raw.unmap_buffer(&buffer.raw)?; } } Ok(None) } - pub fn buffer_unmap( + pub fn buffer_unmap( &self, buffer_id: id::BufferId, ) -> Result<(), resource::BufferAccessError> { - self.buffer_unmap_inner::(buffer_id) + self.buffer_unmap_inner::(buffer_id) //Note: outside inner function so no locks are held when calling the callback .map(|pending_callback| fire_map_callbacks(pending_callback.into_iter())) } diff --git a/wgpu-core/src/device/queue.rs b/wgpu-core/src/device/queue.rs index d05beaafd..87551f547 100644 --- a/wgpu-core/src/device/queue.rs +++ b/wgpu-core/src/device/queue.rs @@ -11,7 +11,7 @@ use crate::{ }, conv, device::{alloc, DeviceError, WaitIdleError}, - hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Storage, Token}, + hub::{Global, GlobalIdentityHandlerFactory, HalApi, Storage, Token}, id, memory_init_tracker::{MemoryInitKind, MemoryInitTrackerAction}, resource::{Buffer, BufferAccessError, BufferMapState, BufferUse, TextureUse}, @@ -23,27 +23,27 @@ use smallvec::SmallVec; use std::{iter, ops::Range, ptr}; use thiserror::Error; -struct StagingData { +struct StagingData { buffer: B::Buffer, - memory: alloc::MemoryBlock, + memory: alloc::MemoryBlock, cmdbuf: B::CommandBuffer, } #[derive(Debug)] -pub enum TempResource { +pub enum TempResource { Buffer(B::Buffer), Image(B::Image), } #[derive(Debug)] -pub(crate) struct PendingWrites { +pub(crate) struct PendingWrites { pub command_buffer: Option, - pub temp_resources: Vec<(TempResource, alloc::MemoryBlock)>, + pub temp_resources: Vec<(TempResource, alloc::MemoryBlock)>, pub dst_buffers: FastHashSet, pub dst_textures: FastHashSet, } -impl PendingWrites { +impl PendingWrites { pub fn new() -> Self { Self { command_buffer: None, @@ -56,8 +56,8 @@ impl PendingWrites { pub fn dispose( self, device: &B::Device, - cmd_allocator: &CommandAllocator, - mem_allocator: &mut alloc::MemoryAllocator, + cmd_allocator: &CommandAllocator, + mem_allocator: &mut alloc::MemoryAllocator, ) { if let Some(raw) = self.command_buffer { cmd_allocator.discard_internal(raw); @@ -75,11 +75,11 @@ impl PendingWrites { } } - pub fn consume_temp(&mut self, resource: TempResource, memory: alloc::MemoryBlock) { + pub fn consume_temp(&mut self, resource: TempResource, memory: alloc::MemoryBlock) { self.temp_resources.push((resource, memory)); } - fn consume(&mut self, stage: StagingData) { + fn consume(&mut self, stage: StagingData) { self.temp_resources .push((TempResource::Buffer(stage.buffer), stage.memory)); self.command_buffer = Some(stage.cmdbuf); @@ -95,7 +95,7 @@ impl PendingWrites { }) } - fn borrow_cmd_buf(&mut self, cmd_allocator: &CommandAllocator) -> &mut B::CommandBuffer { + fn borrow_cmd_buf(&mut self, cmd_allocator: &CommandAllocator) -> &mut B::CommandBuffer { if self.command_buffer.is_none() { let mut cmdbuf = cmd_allocator.allocate_internal(); unsafe { @@ -113,10 +113,10 @@ struct RequiredBufferInits { } impl RequiredBufferInits { - fn add( + fn add( &mut self, buffer_memory_init_actions: &[MemoryInitTrackerAction], - buffer_guard: &mut Storage, id::BufferId>, + buffer_guard: &mut Storage, id::BufferId>, ) -> Result<(), QueueSubmitError> { for buffer_use in buffer_memory_init_actions.iter() { let buffer = buffer_guard @@ -140,12 +140,12 @@ impl RequiredBufferInits { } } -impl super::Device { +impl super::Device { pub fn borrow_pending_writes(&mut self) -> &mut B::CommandBuffer { self.pending_writes.borrow_cmd_buf(&self.cmd_allocator) } - fn prepare_stage(&mut self, size: wgt::BufferAddress) -> Result, DeviceError> { + fn prepare_stage(&mut self, size: wgt::BufferAddress) -> Result, DeviceError> { profiling::scope!("prepare_stage"); let mut buffer = unsafe { self.raw @@ -192,7 +192,7 @@ impl super::Device { fn initialize_buffer_memory( &mut self, mut required_buffer_inits: RequiredBufferInits, - buffer_guard: &mut Storage, id::BufferId>, + buffer_guard: &mut Storage, id::BufferId>, ) -> Result<(), QueueSubmitError> { self.pending_writes .dst_buffers @@ -285,7 +285,7 @@ pub enum QueueSubmitError { //TODO: move out common parts of write_xxx. impl Global { - pub fn queue_write_buffer( + pub fn queue_write_buffer( &self, queue_id: id::QueueId, buffer_id: id::BufferId, @@ -294,7 +294,7 @@ impl Global { ) -> Result<(), QueueWriteError> { profiling::scope!("write_buffer", "Queue"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (mut device_guard, mut token) = hub.devices.write(&mut token); let device = device_guard @@ -391,7 +391,7 @@ impl Global { Ok(()) } - pub fn queue_write_texture( + pub fn queue_write_texture( &self, queue_id: id::QueueId, destination: &ImageCopyTexture, @@ -401,7 +401,7 @@ impl Global { ) -> Result<(), QueueWriteError> { profiling::scope!("write_texture", "Queue"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (mut device_guard, mut token) = hub.devices.write(&mut token); let device = device_guard @@ -586,14 +586,14 @@ impl Global { Ok(()) } - pub fn queue_submit( + pub fn queue_submit( &self, queue_id: id::QueueId, command_buffer_ids: &[id::CommandBufferId], ) -> Result<(), QueueSubmitError> { profiling::scope!("submit", "Queue"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let callbacks = { @@ -676,7 +676,7 @@ impl Global { if !buffer.life_guard.use_at(submit_index) { if let BufferMapState::Active { .. } = buffer.map_state { log::warn!("Dropped buffer has a pending mapping."); - super::unmap_buffer(&device.raw, buffer)?; + unsafe { device.raw.unmap_buffer(buffer)? }; } device.temp_suspected.buffers.push(id); } else { @@ -828,11 +828,11 @@ impl Global { Ok(()) } - pub fn queue_get_timestamp_period( + pub fn queue_get_timestamp_period( &self, queue_id: id::QueueId, ) -> Result { - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (device_guard, _) = hub.devices.read(&mut token); match device_guard.get(queue_id) { diff --git a/wgpu-core/src/hub.rs b/wgpu-core/src/hub.rs index 3d92bfeb6..2d48b30bb 100644 --- a/wgpu-core/src/hub.rs +++ b/wgpu-core/src/hub.rs @@ -3,7 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::{ - backend, binding_model::{BindGroup, BindGroupLayout, PipelineLayout}, command::{CommandBuffer, RenderBundle}, device::Device, @@ -226,7 +225,7 @@ impl Storage { } /// Type system for enforcing the lock order on shared HUB structures. -/// If type A implements `Access`, that means we are allowed to proceed +/// If type A implements `Access`, that means we are allowed to proceed /// with locking resource `B` after we lock `A`. /// /// The implenentations basically describe the edges in a directed graph @@ -234,66 +233,66 @@ impl Storage { /// multiple concurrent paths on this graph (from multiple threads) without /// deadlocks, i.e. there is always a path whose next resource is not locked /// by some other path, at any time. -pub trait Access {} +pub trait Access {} pub enum Root {} //TODO: establish an order instead of declaring all the pairs. impl Access for Root {} impl Access for Root {} impl Access for Instance {} -impl Access> for Root {} -impl Access> for Surface {} -impl Access> for Root {} -impl Access> for Surface {} -impl Access> for Adapter {} -impl Access> for Root {} -impl Access> for Device {} -impl Access> for Root {} -impl Access> for Device {} -impl Access> for RenderBundle {} -impl Access> for Root {} -impl Access> for Device {} -impl Access> for PipelineLayout {} -impl Access> for Root {} -impl Access> for Device {} -impl Access> for BindGroupLayout {} -impl Access> for PipelineLayout {} -impl Access> for CommandBuffer {} -impl Access> for Root {} -impl Access> for Device {} -impl Access> for SwapChain {} -impl Access for Device {} -impl Access for CommandBuffer {} -impl Access> for Device {} -impl Access> for BindGroup {} -impl Access> for Device {} -impl Access> for BindGroup {} -impl Access> for ComputePipeline {} -impl Access> for Root {} -impl Access> for Device {} -impl Access> for CommandBuffer {} -impl Access> for RenderPipeline {} -impl Access> for ComputePipeline {} -impl Access> for Device {} -impl Access> for BindGroupLayout {} -impl Access> for Root {} -impl Access> for Device {} -impl Access> for BindGroupLayout {} -impl Access> for BindGroup {} -impl Access> for CommandBuffer {} -impl Access> for ComputePipeline {} -impl Access> for RenderPipeline {} -impl Access> for QuerySet {} -impl Access> for Root {} -impl Access> for Device {} -impl Access> for Buffer {} -impl Access> for Root {} -impl Access> for SwapChain {} -impl Access> for Device {} -impl Access> for Texture {} -impl Access> for Root {} -impl Access> for Device {} -impl Access> for TextureView {} +impl Access> for Root {} +impl Access> for Surface {} +impl Access> for Root {} +impl Access> for Surface {} +impl Access> for Adapter {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for RenderBundle {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for PipelineLayout {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for BindGroupLayout {} +impl Access> for PipelineLayout {} +impl Access> for CommandBuffer {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for SwapChain {} +impl Access for Device {} +impl Access for CommandBuffer {} +impl Access> for Device {} +impl Access> for BindGroup {} +impl Access> for Device {} +impl Access> for BindGroup {} +impl Access> for ComputePipeline {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for CommandBuffer {} +impl Access> for RenderPipeline {} +impl Access> for ComputePipeline {} +impl Access> for Device {} +impl Access> for BindGroupLayout {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for BindGroupLayout {} +impl Access> for BindGroup {} +impl Access> for CommandBuffer {} +impl Access> for ComputePipeline {} +impl Access> for RenderPipeline {} +impl Access> for QuerySet {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for Buffer {} +impl Access> for Root {} +impl Access> for SwapChain {} +impl Access> for Device {} +impl Access> for Texture {} +impl Access> for Root {} +impl Access> for Device {} +impl Access> for TextureView {} #[cfg(debug_assertions)] thread_local! { @@ -537,55 +536,55 @@ impl> Registry { - pub adapters: Registry, AdapterId, F>, - pub devices: Registry, DeviceId, F>, - pub swap_chains: Registry, SwapChainId, F>, - pub pipeline_layouts: Registry, PipelineLayoutId, F>, - pub shader_modules: Registry, ShaderModuleId, F>, - pub bind_group_layouts: Registry, BindGroupLayoutId, F>, - pub bind_groups: Registry, BindGroupId, F>, - pub command_buffers: Registry, CommandBufferId, F>, +pub struct Hub { + pub adapters: Registry, AdapterId, F>, + pub devices: Registry, DeviceId, F>, + pub swap_chains: Registry, SwapChainId, F>, + pub pipeline_layouts: Registry, PipelineLayoutId, F>, + pub shader_modules: Registry, ShaderModuleId, F>, + pub bind_group_layouts: Registry, BindGroupLayoutId, F>, + pub bind_groups: Registry, BindGroupId, F>, + pub command_buffers: Registry, CommandBufferId, F>, pub render_bundles: Registry, - pub render_pipelines: Registry, RenderPipelineId, F>, - pub compute_pipelines: Registry, ComputePipelineId, F>, - pub query_sets: Registry, QuerySetId, F>, - pub buffers: Registry, BufferId, F>, - pub textures: Registry, TextureId, F>, - pub texture_views: Registry, TextureViewId, F>, - pub samplers: Registry, SamplerId, F>, + pub render_pipelines: Registry, RenderPipelineId, F>, + pub compute_pipelines: Registry, ComputePipelineId, F>, + pub query_sets: Registry, QuerySetId, F>, + pub buffers: Registry, BufferId, F>, + pub textures: Registry, TextureId, F>, + pub texture_views: Registry, TextureViewId, F>, + pub samplers: Registry, SamplerId, F>, } -impl Hub { +impl Hub { fn new(factory: &F) -> Self { Self { - adapters: Registry::new(B::VARIANT, factory), - devices: Registry::new(B::VARIANT, factory), - swap_chains: Registry::new(B::VARIANT, factory), - pipeline_layouts: Registry::new(B::VARIANT, factory), - shader_modules: Registry::new(B::VARIANT, factory), - bind_group_layouts: Registry::new(B::VARIANT, factory), - bind_groups: Registry::new(B::VARIANT, factory), - command_buffers: Registry::new(B::VARIANT, factory), - render_bundles: Registry::new(B::VARIANT, factory), - render_pipelines: Registry::new(B::VARIANT, factory), - compute_pipelines: Registry::new(B::VARIANT, factory), - query_sets: Registry::new(B::VARIANT, factory), - buffers: Registry::new(B::VARIANT, factory), - textures: Registry::new(B::VARIANT, factory), - texture_views: Registry::new(B::VARIANT, factory), - samplers: Registry::new(B::VARIANT, factory), + adapters: Registry::new(A::VARIANT, factory), + devices: Registry::new(A::VARIANT, factory), + swap_chains: Registry::new(A::VARIANT, factory), + pipeline_layouts: Registry::new(A::VARIANT, factory), + shader_modules: Registry::new(A::VARIANT, factory), + bind_group_layouts: Registry::new(A::VARIANT, factory), + bind_groups: Registry::new(A::VARIANT, factory), + command_buffers: Registry::new(A::VARIANT, factory), + render_bundles: Registry::new(A::VARIANT, factory), + render_pipelines: Registry::new(A::VARIANT, factory), + compute_pipelines: Registry::new(A::VARIANT, factory), + query_sets: Registry::new(A::VARIANT, factory), + buffers: Registry::new(A::VARIANT, factory), + textures: Registry::new(A::VARIANT, factory), + texture_views: Registry::new(A::VARIANT, factory), + samplers: Registry::new(A::VARIANT, factory), } } } -impl Hub { +impl Hub { //TODO: instead of having a hacky `with_adapters` parameter, // we should have `clear_device(device_id)` that specifically destroys // everything related to a logical device. fn clear(&self, surface_guard: &mut Storage, with_adapters: bool) { use crate::resource::TextureViewInner; - use hal::{device::Device as _, window::PresentationSurface as _}; + use hal::Device as _; let mut devices = self.devices.data.write(); for element in devices.map.iter_mut() { @@ -693,7 +692,7 @@ impl Hub { unsafe { device.raw.destroy_semaphore(swap_chain.semaphore); } - let suf_id = TypedId::zip(index as Index, epoch, B::VARIANT); + let suf_id = TypedId::zip(index as Index, epoch, A::VARIANT); //TODO: hold the surface alive by the swapchain if surface_guard.contains(suf_id) { let surface = surface_guard.get_mut(suf_id).unwrap(); @@ -727,21 +726,22 @@ impl Hub { #[derive(Debug)] pub struct Hubs { - #[cfg(vulkan)] - vulkan: Hub, - #[cfg(metal)] - metal: Hub, - #[cfg(dx12)] - dx12: Hub, - #[cfg(dx11)] - dx11: Hub, - #[cfg(gl)] - gl: Hub, -} + /* +#[cfg(vulkan)] +vulkan: Hub, +#[cfg(metal)] +metal: Hub, +#[cfg(dx12)] +dx12: Hub, +#[cfg(dx11)] +dx11: Hub, +#[cfg(gl)] +gl: Hub,*/} impl Hubs { fn new(factory: &F) -> Self { Self { + /* #[cfg(vulkan)] vulkan: Hub::new(factory), #[cfg(metal)] @@ -752,6 +752,7 @@ impl Hubs { dx11: Hub::new(factory), #[cfg(gl)] gl: Hub::new(factory), + */ } } } @@ -773,9 +774,9 @@ impl Global { } } - pub fn clear_backend(&self, _dummy: ()) { + pub fn clear_backend(&self, _dummy: ()) { let mut surface_guard = self.surfaces.data.write(); - let hub = B::hub(self); + let hub = A::hub(self); // this is used for tests, which keep the adapter hub.clear(&mut *surface_guard, false); } @@ -788,6 +789,7 @@ impl Drop for Global { let mut surface_guard = self.surfaces.data.write(); // destroy hubs before the instance gets dropped + /* #[cfg(vulkan)] { self.hubs.vulkan.clear(&mut *surface_guard, true); @@ -808,6 +810,7 @@ impl Drop for Global { { self.hubs.gl.clear(&mut *surface_guard, true); } + */ // destroy surfaces for element in surface_guard.map.drain(..) { @@ -818,14 +821,15 @@ impl Drop for Global { } } -pub trait GfxBackend: hal::Backend { +pub trait HalApi: hal::Api { const VARIANT: Backend; fn hub(global: &Global) -> &Hub; fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface; } +/* #[cfg(vulkan)] -impl GfxBackend for backend::Vulkan { +impl HalApi for backend::Vulkan { const VARIANT: Backend = Backend::Vulkan; fn hub(global: &Global) -> &Hub { &global.hubs.vulkan @@ -836,7 +840,7 @@ impl GfxBackend for backend::Vulkan { } #[cfg(metal)] -impl GfxBackend for backend::Metal { +impl HalApi for backend::Metal { const VARIANT: Backend = Backend::Metal; fn hub(global: &Global) -> &Hub { &global.hubs.metal @@ -847,7 +851,7 @@ impl GfxBackend for backend::Metal { } #[cfg(dx12)] -impl GfxBackend for backend::Dx12 { +impl HalApi for backend::Dx12 { const VARIANT: Backend = Backend::Dx12; fn hub(global: &Global) -> &Hub { &global.hubs.dx12 @@ -858,7 +862,7 @@ impl GfxBackend for backend::Dx12 { } #[cfg(dx11)] -impl GfxBackend for backend::Dx11 { +impl HalApi for backend::Dx11 { const VARIANT: Backend = Backend::Dx11; fn hub(global: &Global) -> &Hub { &global.hubs.dx11 @@ -869,7 +873,7 @@ impl GfxBackend for backend::Dx11 { } #[cfg(gl)] -impl GfxBackend for backend::Gl { +impl HalApi for backend::Gl { const VARIANT: Backend = Backend::Gl; fn hub(global: &Global) -> &Hub { &global.hubs.gl @@ -877,7 +881,7 @@ impl GfxBackend for backend::Gl { fn get_surface_mut(surface: &mut Surface) -> &mut Self::Surface { surface.gl.as_mut().unwrap() } -} +}*/ #[cfg(test)] fn _test_send_sync(global: &Global) { diff --git a/wgpu-core/src/instance.rs b/wgpu-core/src/instance.rs index 882fcfa48..6a39e7d28 100644 --- a/wgpu-core/src/instance.rs +++ b/wgpu-core/src/instance.rs @@ -3,41 +3,34 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::{ - backend, conv, + conv, device::{Device, DeviceDescriptor}, - hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Input, Token}, + hub::{Global, GlobalIdentityHandlerFactory, HalApi, Input, Token}, id::{AdapterId, DeviceId, SurfaceId, Valid}, - LabelHelpers, LifeGuard, PrivateFeatures, Stored, DOWNLEVEL_WARNING_MESSAGE, MAX_BIND_GROUPS, + LabelHelpers, LifeGuard, Stored, DOWNLEVEL_WARNING_MESSAGE, }; use wgt::{Backend, BackendBit, PowerPreference, BIND_BUFFER_ALIGNMENT}; -use hal::{ - adapter::PhysicalDevice as _, queue::QueueFamily as _, window::Surface as _, Instance as _, -}; +use hal::Adapter as _; use thiserror::Error; -/// Size that is guaranteed to be available in push constants. -/// -/// This is needed because non-vulkan backends might not -/// provide a push-constant size limit. -const MIN_PUSH_CONSTANT_SIZE: u32 = 128; - pub type RequestAdapterOptions = wgt::RequestAdapterOptions; #[derive(Debug)] pub struct Instance { - #[cfg(vulkan)] - pub vulkan: Option, - #[cfg(metal)] - pub metal: Option, - #[cfg(dx12)] - pub dx12: Option, - #[cfg(dx11)] - pub dx11: Option, - #[cfg(gl)] - pub gl: Option, -} + /* +#[cfg(vulkan)] +pub vulkan: Option, +#[cfg(metal)] +pub metal: Option, +#[cfg(dx12)] +pub dx12: Option, +#[cfg(dx11)] +pub dx11: Option, +#[cfg(gl)] +pub gl: Option, +*/} impl Instance { pub fn new(name: &str, version: u32, backends: BackendBit) -> Self { @@ -50,6 +43,7 @@ impl Instance { } }; Self { + /* #[cfg(vulkan)] vulkan: map((Backend::Vulkan, gfx_backend_vulkan::Instance::create)), #[cfg(metal)] @@ -60,6 +54,7 @@ impl Instance { dx11: map((Backend::Dx11, gfx_backend_dx11::Instance::create)), #[cfg(gl)] gl: map((Backend::Gl, gfx_backend_gl::Instance::create)), + */ } } } @@ -74,6 +69,7 @@ impl Instance { } }; + /* #[cfg(vulkan)] map((surface.vulkan, &self.vulkan)), #[cfg(metal)] @@ -84,25 +80,27 @@ impl Instance { map((surface.dx11, &self.dx11)), #[cfg(gl)] map((surface.gl, &self.gl)), + */ } } } -type GfxSurface = ::Surface; +type GfxSurface = ::Surface; #[derive(Debug)] pub struct Surface { - #[cfg(vulkan)] - pub vulkan: Option>, - #[cfg(metal)] - pub metal: Option>, - #[cfg(dx12)] - pub dx12: Option>, - #[cfg(dx11)] - pub dx11: Option>, - #[cfg(gl)] - pub gl: Option>, -} + /* +#[cfg(vulkan)] +pub vulkan: Option>, +#[cfg(metal)] +pub metal: Option>, +#[cfg(dx12)] +pub dx12: Option>, +#[cfg(dx11)] +pub dx11: Option>, +#[cfg(gl)] +pub gl: Option>, +*/} impl crate::hub::Resource for Surface { const TYPE: &'static str = "Surface"; @@ -116,236 +114,16 @@ impl crate::hub::Resource for Surface { } } -const FEATURE_MAP: &[(wgt::Features, hal::Features)] = &[ - (wgt::Features::DEPTH_CLAMPING, hal::Features::DEPTH_CLAMP), - ( - wgt::Features::TEXTURE_COMPRESSION_BC, - hal::Features::FORMAT_BC, - ), - ( - wgt::Features::TEXTURE_COMPRESSION_ETC2, - hal::Features::FORMAT_ETC2, - ), - ( - wgt::Features::TEXTURE_COMPRESSION_ASTC_LDR, - hal::Features::FORMAT_ASTC_LDR, - ), - ( - wgt::Features::SAMPLED_TEXTURE_BINDING_ARRAY, - hal::Features::TEXTURE_DESCRIPTOR_ARRAY, - ), - ( - wgt::Features::SAMPLED_TEXTURE_ARRAY_DYNAMIC_INDEXING, - hal::Features::SHADER_SAMPLED_IMAGE_ARRAY_DYNAMIC_INDEXING, - ), - ( - wgt::Features::SAMPLED_TEXTURE_ARRAY_NON_UNIFORM_INDEXING, - hal::Features::SAMPLED_TEXTURE_DESCRIPTOR_INDEXING, - ), - ( - wgt::Features::UNSIZED_BINDING_ARRAY, - hal::Features::UNSIZED_DESCRIPTOR_ARRAY, - ), - ( - wgt::Features::MULTI_DRAW_INDIRECT, - hal::Features::MULTI_DRAW_INDIRECT, - ), - ( - wgt::Features::MULTI_DRAW_INDIRECT_COUNT, - hal::Features::DRAW_INDIRECT_COUNT, - ), - ( - wgt::Features::NON_FILL_POLYGON_MODE, - hal::Features::NON_FILL_POLYGON_MODE, - ), - ( - wgt::Features::PIPELINE_STATISTICS_QUERY, - hal::Features::PIPELINE_STATISTICS_QUERY, - ), - (wgt::Features::SHADER_FLOAT64, hal::Features::SHADER_FLOAT64), - ( - wgt::Features::CONSERVATIVE_RASTERIZATION, - hal::Features::CONSERVATIVE_RASTERIZATION, - ), - ( - wgt::Features::BUFFER_BINDING_ARRAY, - hal::Features::BUFFER_DESCRIPTOR_ARRAY, - ), - ( - wgt::Features::UNIFORM_BUFFER_ARRAY_DYNAMIC_INDEXING, - hal::Features::SHADER_UNIFORM_BUFFER_ARRAY_DYNAMIC_INDEXING, - ), - ( - wgt::Features::UNIFORM_BUFFER_ARRAY_NON_UNIFORM_INDEXING, - hal::Features::UNIFORM_BUFFER_DESCRIPTOR_INDEXING, - ), - ( - wgt::Features::STORAGE_BUFFER_ARRAY_DYNAMIC_INDEXING, - hal::Features::SHADER_STORAGE_BUFFER_ARRAY_DYNAMIC_INDEXING, - ), - ( - wgt::Features::STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING, - hal::Features::STORAGE_BUFFER_DESCRIPTOR_INDEXING, - ), - ( - wgt::Features::VERTEX_WRITABLE_STORAGE, - hal::Features::VERTEX_STORES_AND_ATOMICS, - ), - ( - wgt::Features::ADDRESS_MODE_CLAMP_TO_BORDER, - hal::Features::SAMPLER_BORDER_COLOR, - ), -]; - #[derive(Debug)] -pub struct Adapter { - pub(crate) raw: hal::adapter::Adapter, - features: wgt::Features, - pub(crate) private_features: PrivateFeatures, - limits: wgt::Limits, - downlevel: wgt::DownlevelProperties, +pub struct Adapter { + pub(crate) raw: hal::ExposedAdapter, life_guard: LifeGuard, } -impl Adapter { - fn new(raw: hal::adapter::Adapter) -> Self { - profiling::scope!("new", "Adapter"); - - let adapter_features = raw.physical_device.features(); - let properties = raw.physical_device.properties(); - - let mut features = wgt::Features::default() - | wgt::Features::MAPPABLE_PRIMARY_BUFFERS - | wgt::Features::PUSH_CONSTANTS - | wgt::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES - | wgt::Features::CLEAR_COMMANDS; - for &(hi, lo) in FEATURE_MAP.iter() { - features.set(hi, adapter_features.contains(lo)); - } - features.set( - wgt::Features::TIMESTAMP_QUERY, - properties.limits.timestamp_compute_and_graphics, - ); - - let private_features = PrivateFeatures { - anisotropic_filtering: adapter_features.contains(hal::Features::SAMPLER_ANISOTROPY), - texture_d24: raw - .physical_device - .format_properties(Some(hal::format::Format::X8D24Unorm)) - .optimal_tiling - .contains(hal::format::ImageFeature::DEPTH_STENCIL_ATTACHMENT), - texture_d24_s8: raw - .physical_device - .format_properties(Some(hal::format::Format::D24UnormS8Uint)) - .optimal_tiling - .contains(hal::format::ImageFeature::DEPTH_STENCIL_ATTACHMENT), - }; - - let default_limits = wgt::Limits::default(); - - // All these casts to u32 are safe as the underlying vulkan types are u32s. - // If another backend provides larger limits than u32, we need to clamp them to u32::MAX. - // TODO: fix all gfx-hal backends to produce limits we care about, and remove .max - let desc_limits = &properties.limits.descriptor_limits; - let limits = wgt::Limits { - max_texture_dimension_1d: properties - .limits - .max_image_1d_size - .max(default_limits.max_texture_dimension_1d), - max_texture_dimension_2d: properties - .limits - .max_image_2d_size - .max(default_limits.max_texture_dimension_1d), - max_texture_dimension_3d: properties - .limits - .max_image_3d_size - .max(default_limits.max_texture_dimension_1d), - max_texture_array_layers: (properties.limits.max_image_array_layers as u32) - .max(default_limits.max_texture_array_layers), - max_bind_groups: (properties.limits.max_bound_descriptor_sets as u32) - .min(MAX_BIND_GROUPS as u32) - .max(default_limits.max_bind_groups), - max_dynamic_uniform_buffers_per_pipeline_layout: desc_limits - .max_descriptor_set_uniform_buffers_dynamic - .max(default_limits.max_dynamic_uniform_buffers_per_pipeline_layout), - max_dynamic_storage_buffers_per_pipeline_layout: desc_limits - .max_descriptor_set_storage_buffers_dynamic - .max(default_limits.max_dynamic_storage_buffers_per_pipeline_layout), - max_sampled_textures_per_shader_stage: desc_limits - .max_per_stage_descriptor_sampled_images - .max(default_limits.max_sampled_textures_per_shader_stage), - max_samplers_per_shader_stage: desc_limits - .max_per_stage_descriptor_samplers - .max(default_limits.max_samplers_per_shader_stage), - max_storage_buffers_per_shader_stage: desc_limits - .max_per_stage_descriptor_storage_buffers - .max(default_limits.max_storage_buffers_per_shader_stage), - max_storage_textures_per_shader_stage: desc_limits - .max_per_stage_descriptor_storage_images - .max(default_limits.max_storage_textures_per_shader_stage), - max_uniform_buffers_per_shader_stage: desc_limits - .max_per_stage_descriptor_uniform_buffers - .max(default_limits.max_uniform_buffers_per_shader_stage), - max_uniform_buffer_binding_size: (properties.limits.max_uniform_buffer_range as u32) - .max(default_limits.max_uniform_buffer_binding_size), - max_storage_buffer_binding_size: (properties.limits.max_storage_buffer_range as u32) - .max(default_limits.max_storage_buffer_binding_size), - max_vertex_buffers: (properties.limits.max_vertex_input_bindings as u32) - .max(default_limits.max_vertex_buffers), - max_vertex_attributes: (properties.limits.max_vertex_input_attributes as u32) - .max(default_limits.max_vertex_attributes), - max_vertex_buffer_array_stride: (properties.limits.max_vertex_input_binding_stride - as u32) - .max(default_limits.max_vertex_buffer_array_stride), - max_push_constant_size: (properties.limits.max_push_constants_size as u32) - .max(MIN_PUSH_CONSTANT_SIZE), // As an extension, the default is always 0, so define a separate minimum. - }; - - let mut downlevel_flags = wgt::DownlevelFlags::empty(); - downlevel_flags.set( - wgt::DownlevelFlags::COMPUTE_SHADERS, - properties.downlevel.compute_shaders, - ); - downlevel_flags.set( - wgt::DownlevelFlags::STORAGE_IMAGES, - properties.downlevel.storage_images, - ); - downlevel_flags.set( - wgt::DownlevelFlags::READ_ONLY_DEPTH_STENCIL, - properties.downlevel.read_only_depth_stencil, - ); - downlevel_flags.set( - wgt::DownlevelFlags::DEVICE_LOCAL_IMAGE_COPIES, - properties.downlevel.device_local_image_copies, - ); - downlevel_flags.set( - wgt::DownlevelFlags::NON_POWER_OF_TWO_MIPMAPPED_TEXTURES, - properties.downlevel.non_power_of_two_mipmapped_textures, - ); - downlevel_flags.set( - wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES, - adapter_features.contains(hal::Features::IMAGE_CUBE_ARRAY), - ); - downlevel_flags.set( - wgt::DownlevelFlags::ANISOTROPIC_FILTERING, - private_features.anisotropic_filtering, - ); - - let downlevel = wgt::DownlevelProperties { - flags: downlevel_flags, - shader_model: match properties.downlevel.shader_model { - hal::DownlevelShaderModel::ShaderModel2 => wgt::ShaderModel::Sm2, - hal::DownlevelShaderModel::ShaderModel4 => wgt::ShaderModel::Sm4, - hal::DownlevelShaderModel::ShaderModel5 => wgt::ShaderModel::Sm5, - }, - }; - +impl Adapter { + fn new(raw: hal::ExposedAdapter) -> Self { Self { raw, - features, - private_features, - limits, - downlevel, life_guard: LifeGuard::new(""), } } @@ -354,75 +132,58 @@ impl Adapter { &self, surface: &mut Surface, ) -> Result { - let formats = { - let surface = B::get_surface_mut(surface); - let queue_family = &self.raw.queue_families[0]; - if !surface.supports_queue_family(queue_family) { - return Err(GetSwapChainPreferredFormatError::UnsupportedQueueFamily); - } - surface.supported_formats(&self.raw.physical_device) - }; - if let Some(formats) = formats { - // Check the four formats mentioned in the WebGPU spec: - // Bgra8UnormSrgb, Rgba8UnormSrgb, Bgra8Unorm, Rgba8Unorm - // Also, prefer sRGB over linear as it is better in - // representing perceived colors. - if formats.contains(&hal::format::Format::Bgra8Srgb) { - return Ok(wgt::TextureFormat::Bgra8UnormSrgb); - } - if formats.contains(&hal::format::Format::Rgba8Srgb) { - return Ok(wgt::TextureFormat::Rgba8UnormSrgb); - } - if formats.contains(&hal::format::Format::Bgra8Unorm) { - return Ok(wgt::TextureFormat::Bgra8Unorm); - } - if formats.contains(&hal::format::Format::Rgba8Unorm) { - return Ok(wgt::TextureFormat::Rgba8Unorm); - } - return Err(GetSwapChainPreferredFormatError::NotFound); - } + // Check the four formats mentioned in the WebGPU spec. + // Also, prefer sRGB over linear as it is better in + // representing perceived colors. + let preferred_formats = [ + wgt::TextureFormat::Bgra8UnormSrgb, + wgt::TextureFormat::Rgba8UnormSrgb, + wgt::TextureFormat::Bgra8Unorm, + wgt::TextureFormat::Rgba8Unorm, + ]; - // If no formats were returned, use Bgra8UnormSrgb - Ok(wgt::TextureFormat::Bgra8UnormSrgb) + let formats = B::get_surface(surface).supported_formats(&self.raw.adapter); + preferred_formats + .iter() + .cloned() + .find(|preferred| formats.contains(preferred)) + .ok_or(GetSwapChainPreferredFormatError::NotFound) } pub(crate) fn get_texture_format_features( &self, format: wgt::TextureFormat, ) -> wgt::TextureFormatFeatures { - let texture_format_properties = self - .raw - .physical_device - .format_properties(Some(conv::map_texture_format( - format, - self.private_features, - ))) - .optimal_tiling; + let caps = self.raw.adapter.texture_format_capabilities(format); let mut allowed_usages = format.describe().guaranteed_format_features.allowed_usages; - if texture_format_properties.contains(hal::format::ImageFeature::SAMPLED) { - allowed_usages |= wgt::TextureUsage::SAMPLED; - } - if texture_format_properties.contains(hal::format::ImageFeature::STORAGE) { - allowed_usages |= wgt::TextureUsage::STORAGE; - } - if texture_format_properties.contains(hal::format::ImageFeature::COLOR_ATTACHMENT) { - allowed_usages |= wgt::TextureUsage::RENDER_ATTACHMENT; - } - if texture_format_properties.contains(hal::format::ImageFeature::DEPTH_STENCIL_ATTACHMENT) { - allowed_usages |= wgt::TextureUsage::RENDER_ATTACHMENT; - } + allowed_usages.set( + wgt::TextureUsage::SAMPLED, + caps.contains(hal::TextureFormatCapability::SAMPLED), + ); + allowed_usages.set( + wgt::TextureUsage::STORAGE, + caps.contains(hal::TextureFormatCapability::STORAGE), + ); + allowed_usages.set( + wgt::TextureUsage::RENDER_ATTACHMENT, + caps.intersects( + hal::TextureFormatCapability::COLOR_ATTACHMENT + | hal::TextureFormatCapability::DEPTH_STENCIL_ATTACHMENT, + ), + ); let mut flags = wgt::TextureFormatFeatureFlags::empty(); - if texture_format_properties.contains(hal::format::ImageFeature::STORAGE_ATOMIC) { - flags |= wgt::TextureFormatFeatureFlags::STORAGE_ATOMICS; - } - if texture_format_properties.contains(hal::format::ImageFeature::STORAGE_READ_WRITE) { - flags |= wgt::TextureFormatFeatureFlags::STORAGE_READ_WRITE; - } + flags.set( + wgt::TextureFormatFeatureFlags::STORAGE_ATOMICS, + caps.contains(hal::TextureFormatCapability::STORAGE_ATOMIC), + ); + flags.set( + wgt::TextureFormatFeatureFlags::STORAGE_READ_WRITE, + caps.contains(hal::TextureFormatCapability::STORAGE_READ_WRITE), + ); - let filterable = - texture_format_properties.contains(hal::format::ImageFeature::SAMPLED_LINEAR); + let filterable = caps.contains(hal::TextureFormatCapability::SAMPLED_LINEAR); wgt::TextureFormatFeatures { allowed_usages, @@ -436,11 +197,11 @@ impl Adapter { self_id: AdapterId, desc: &DeviceDescriptor, trace_path: Option<&std::path::Path>, - ) -> Result, RequestDeviceError> { + ) -> Result, RequestDeviceError> { // Verify all features were exposed by the adapter - if !self.features.contains(desc.features) { + if !self.raw.features.contains(desc.features) { return Err(RequestDeviceError::UnsupportedFeature( - desc.features - self.features, + desc.features - self.raw.features, )); } @@ -452,85 +213,43 @@ impl Adapter { if desc .features .contains(wgt::Features::MAPPABLE_PRIMARY_BUFFERS) - && self.raw.info.device_type == hal::adapter::DeviceType::DiscreteGpu + && self.raw.info.device_type == wgt::DeviceType::DiscreteGpu { log::warn!("Feature MAPPABLE_PRIMARY_BUFFERS enabled on a discrete gpu. This is a massive performance footgun and likely not what you wanted"); } - let phd = &self.raw.physical_device; - let available_features = phd.features(); - - // Check features that are always needed - let wishful_features = hal::Features::ROBUST_BUFFER_ACCESS - | hal::Features::FRAGMENT_STORES_AND_ATOMICS - | hal::Features::NDC_Y_UP - | hal::Features::INDEPENDENT_BLENDING - | hal::Features::SAMPLER_ANISOTROPY - | hal::Features::IMAGE_CUBE_ARRAY - | hal::Features::SAMPLE_RATE_SHADING; - let mut enabled_features = available_features & wishful_features; - if enabled_features != wishful_features { - log::warn!( - "Missing internal features: {:?}", - wishful_features - enabled_features - ); - } - - // Enable low-level features - for &(hi, lo) in FEATURE_MAP.iter() { - enabled_features.set(lo, desc.features.contains(hi)); - } - - let family = self - .raw - .queue_families - .iter() - .find(|family| family.queue_type().supports_graphics()) - .ok_or(RequestDeviceError::NoGraphicsQueue)?; - - let mut gpu = - unsafe { phd.open(&[(family, &[1.0])], enabled_features) }.map_err(|err| { - use hal::device::CreationError::*; - match err { - DeviceLost => RequestDeviceError::DeviceLost, - InitializationFailed => RequestDeviceError::Internal, - OutOfMemory(_) => RequestDeviceError::OutOfMemory, - _ => panic!("failed to create `gfx-hal` device: {}", err), - } - })?; + let gpu = unsafe { self.raw.adapter.open(desc.features) }.map_err(|err| match err { + hal::Error::DeviceLost => RequestDeviceError::DeviceLost, + hal::Error::OutOfMemory => RequestDeviceError::OutOfMemory, + })?; if let Some(_) = desc.label { //TODO } - let limits = phd.properties().limits; + let caps = &self.raw.capabilities; assert_eq!( 0, - BIND_BUFFER_ALIGNMENT % limits.min_storage_buffer_offset_alignment, + BIND_BUFFER_ALIGNMENT % caps.alignments.storage_buffer_offset, "Adapter storage buffer offset alignment not compatible with WGPU" ); assert_eq!( 0, - BIND_BUFFER_ALIGNMENT % limits.min_uniform_buffer_offset_alignment, + BIND_BUFFER_ALIGNMENT % caps.alignments.uniform_buffer_offset, "Adapter uniform buffer offset alignment not compatible with WGPU" ); - if self.limits < desc.limits { + if self.raw.limits < desc.limits { return Err(RequestDeviceError::LimitsExceeded); } - let mem_props = phd.memory_properties(); - Device::new( - gpu.device, + gpu, Stored { value: Valid(self_id), ref_count: self.life_guard.add_ref(), }, - gpu.queue_groups.swap_remove(0), - mem_props, - limits, - self.private_features, - self.downlevel, + caps.alignments.clone(), + caps.downlevel.clone(), desc, trace_path, ) @@ -538,7 +257,7 @@ impl Adapter { } } -impl crate::hub::Resource for Adapter { +impl crate::hub::Resource for Adapter { const TYPE: &'static str = "Adapter"; fn life_guard(&self) -> &LifeGuard { @@ -700,6 +419,7 @@ impl Global { } }; + /* #[cfg(vulkan)] map((&instance.vulkan, Backend::Vulkan, "Vulkan", backend::Vulkan::hub)), #[cfg(metal)] @@ -710,6 +430,7 @@ impl Global { map((&instance.dx11, Backend::Dx11, "Dx11", backend::Dx11::hub)), #[cfg(gl)] map((&instance.gl, Backend::Gl, "GL", backend::Gl::hub)), + */ } adapters @@ -754,7 +475,7 @@ impl Global { .map_or(false, |qf| surface_backend.supports_queue_family(qf)) }); } - device_types.extend(adapters.iter().map(|ad| ad.info.device_type.clone())); + device_types.extend(adapters.iter().map(|ad| ad.info.device_type)); adapters } _ => Vec::new(), @@ -763,6 +484,7 @@ impl Global { // NB: The internal function definitions are a workaround for Rust // being weird with lifetimes for closure literals... + /* #[cfg(vulkan)] let adapters_vk = map((&instance.vulkan, &id_vulkan, { fn surface_vulkan(surf: &Surface) -> Option<&GfxSurface> { @@ -797,7 +519,7 @@ impl Global { surf.gl.as_ref() } surface_gl - })); + }));*/ } if device_types.is_empty() { @@ -809,19 +531,19 @@ impl Global { for (i, ty) in device_types.into_iter().enumerate() { match ty { - hal::adapter::DeviceType::IntegratedGpu => { + wgt::DeviceType::IntegratedGpu => { integrated = integrated.or(Some(i)); } - hal::adapter::DeviceType::DiscreteGpu => { + wgt::DeviceType::DiscreteGpu => { discrete = discrete.or(Some(i)); } - hal::adapter::DeviceType::VirtualGpu => { + wgt::DeviceType::VirtualGpu => { virt = virt.or(Some(i)); } - hal::adapter::DeviceType::Cpu => { + wgt::DeviceType::Cpu => { cpu = cpu.or(Some(i)); } - hal::adapter::DeviceType::Other => { + wgt::DeviceType::Other => { other = other.or(Some(i)); } } @@ -847,6 +569,7 @@ impl Global { selected -= adapters_backend.len(); }; + /* #[cfg(vulkan)] map(("Vulkan", &mut id_vulkan, adapters_vk, backend::Vulkan::hub)), #[cfg(metal)] @@ -857,6 +580,7 @@ impl Global { map(("Dx11", &mut id_dx11, adapters_dx11, backend::Dx11::hub)), #[cfg(gl)] map(("GL", &mut id_gl, adapters_gl, backend::Gl::hub)), + */ } let _ = ( @@ -871,11 +595,11 @@ impl Global { Err(RequestAdapterError::NotFound) } - pub fn adapter_get_info( + pub fn adapter_get_info( &self, adapter_id: AdapterId, ) -> Result { - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (adapter_guard, _) = hub.adapters.read(&mut token); adapter_guard @@ -884,12 +608,12 @@ impl Global { .map_err(|_| InvalidAdapter) } - pub fn adapter_get_texture_format_features( + pub fn adapter_get_texture_format_features( &self, adapter_id: AdapterId, format: wgt::TextureFormat, ) -> Result { - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (adapter_guard, _) = hub.adapters.read(&mut token); adapter_guard @@ -898,11 +622,11 @@ impl Global { .map_err(|_| InvalidAdapter) } - pub fn adapter_features( + pub fn adapter_features( &self, adapter_id: AdapterId, ) -> Result { - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (adapter_guard, _) = hub.adapters.read(&mut token); adapter_guard @@ -911,11 +635,11 @@ impl Global { .map_err(|_| InvalidAdapter) } - pub fn adapter_limits( + pub fn adapter_limits( &self, adapter_id: AdapterId, ) -> Result { - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (adapter_guard, _) = hub.adapters.read(&mut token); adapter_guard @@ -924,23 +648,23 @@ impl Global { .map_err(|_| InvalidAdapter) } - pub fn adapter_downlevel_properties( + pub fn adapter_downlevel_properties( &self, adapter_id: AdapterId, - ) -> Result { - let hub = B::hub(self); + ) -> Result { + let hub = A::hub(self); let mut token = Token::root(); let (adapter_guard, _) = hub.adapters.read(&mut token); adapter_guard .get(adapter_id) - .map(|adapter| adapter.downlevel) + .map(|adapter| adapter.raw.downlevel) .map_err(|_| InvalidAdapter) } - pub fn adapter_drop(&self, adapter_id: AdapterId) { + pub fn adapter_drop(&self, adapter_id: AdapterId) { profiling::scope!("drop", "Adapter"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (mut adapter_guard, _) = hub.adapters.write(&mut token); @@ -956,7 +680,7 @@ impl Global { } impl Global { - pub fn adapter_request_device( + pub fn adapter_request_device( &self, adapter_id: AdapterId, desc: &DeviceDescriptor, @@ -965,7 +689,7 @@ impl Global { ) -> (DeviceId, Option) { profiling::scope!("request_device", "Adapter"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let fid = hub.devices.prepare(id_in); diff --git a/wgpu-core/src/lib.rs b/wgpu-core/src/lib.rs index 01db1471e..ea3b9b84d 100644 --- a/wgpu-core/src/lib.rs +++ b/wgpu-core/src/lib.rs @@ -27,8 +27,8 @@ mod macros; pub mod backend { - pub use gfx_backend_empty::Backend as Empty; - + pub use hal::empty::Api as Empty; + /* #[cfg(dx11)] pub use gfx_backend_dx11::Backend as Dx11; #[cfg(dx12)] @@ -39,6 +39,7 @@ pub mod backend { pub use gfx_backend_metal::Backend as Metal; #[cfg(vulkan)] pub use gfx_backend_vulkan::Backend as Vulkan; + */ } pub mod binding_model; @@ -64,8 +65,6 @@ use atomic::{AtomicUsize, Ordering}; use std::{borrow::Cow, os::raw::c_char, ptr}; -pub const MAX_BIND_GROUPS: usize = 8; - type SubmissionIndex = usize; type Index = u32; type Epoch = u32; @@ -230,13 +229,6 @@ struct Stored { ref_count: RefCount, } -#[derive(Clone, Copy, Debug)] -struct PrivateFeatures { - anisotropic_filtering: bool, - texture_d24: bool, - texture_d24_s8: bool, -} - const DOWNLEVEL_WARNING_MESSAGE: &str = "The underlying API or device in use does not \ support enough features to be a fully compliant implementation of WebGPU. A subset of the features can still be used. \ If you are running this program on native and not in a browser and wish to limit the features you use to the supported subset, \ @@ -254,6 +246,7 @@ macro_rules! gfx_select { // Note: For some reason the cfg aliases defined in build.rs don't succesfully apply in this // macro so we must specify their equivalents manually match $id.backend() { + /* #[cfg(all(not(target_arch = "wasm32"), not(target_os = "ios"), not(target_os = "macos")))] wgt::Backend::Vulkan => $global.$method::<$crate::backend::Vulkan>( $($param),* ), #[cfg(all(not(target_arch = "wasm32"), any(target_os = "ios", target_os = "macos")))] @@ -264,7 +257,9 @@ macro_rules! gfx_select { wgt::Backend::Dx11 => $global.$method::<$crate::backend::Dx11>( $($param),* ), #[cfg(any(target_arch = "wasm32", all(unix, not(any(target_os = "ios", target_os = "macos")))))] wgt::Backend::Gl => $global.$method::<$crate::backend::Gl>( $($param),+ ), + */ other => panic!("Unexpected backend {:?}", other), + } }; } @@ -274,9 +269,3 @@ type FastHashMap = std::collections::HashMap>; /// Fast hash set used internally. type FastHashSet = std::collections::HashSet>; - -#[test] -fn test_default_limits() { - let limits = wgt::Limits::default(); - assert!(limits.max_bind_groups <= MAX_BIND_GROUPS as u32); -} diff --git a/wgpu-core/src/pipeline.rs b/wgpu-core/src/pipeline.rs index 05adbcd35..53eeb652d 100644 --- a/wgpu-core/src/pipeline.rs +++ b/wgpu-core/src/pipeline.rs @@ -29,7 +29,7 @@ pub struct ShaderModuleDescriptor<'a> { } #[derive(Debug)] -pub struct ShaderModule { +pub struct ShaderModule { pub(crate) raw: B::ShaderModule, pub(crate) device_id: Stored, pub(crate) interface: Option, @@ -37,7 +37,7 @@ pub struct ShaderModule { pub(crate) label: String, } -impl Resource for ShaderModule { +impl Resource for ShaderModule { const TYPE: &'static str = "ShaderModule"; fn life_guard(&self) -> &LifeGuard { @@ -125,14 +125,14 @@ pub enum CreateComputePipelineError { } #[derive(Debug)] -pub struct ComputePipeline { +pub struct ComputePipeline { pub(crate) raw: B::ComputePipeline, pub(crate) layout_id: Stored, pub(crate) device_id: Stored, pub(crate) life_guard: LifeGuard, } -impl Resource for ComputePipeline { +impl Resource for ComputePipeline { const TYPE: &'static str = "ComputePipeline"; fn life_guard(&self) -> &LifeGuard { @@ -289,7 +289,7 @@ bitflags::bitflags! { } #[derive(Debug)] -pub struct RenderPipeline { +pub struct RenderPipeline { pub(crate) raw: B::GraphicsPipeline, pub(crate) layout_id: Stored, pub(crate) device_id: Stored, @@ -300,7 +300,7 @@ pub struct RenderPipeline { pub(crate) life_guard: LifeGuard, } -impl Resource for RenderPipeline { +impl Resource for RenderPipeline { const TYPE: &'static str = "RenderPipeline"; fn life_guard(&self) -> &LifeGuard { diff --git a/wgpu-core/src/resource.rs b/wgpu-core/src/resource.rs index 171ae4bac..20e365b0f 100644 --- a/wgpu-core/src/resource.rs +++ b/wgpu-core/src/resource.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::{ - device::{alloc::MemoryBlock, DeviceError, HostMap, MissingFeatures}, + device::{DeviceError, HostMap, MissingFeatures}, hub::Resource, id::{DeviceId, SwapChainId, TextureId}, memory_init_tracker::MemoryInitTracker, @@ -77,12 +77,11 @@ pub enum BufferMapAsyncStatus { } #[derive(Debug)] -pub(crate) enum BufferMapState { +pub(crate) enum BufferMapState { /// Mapped at creation. Init { ptr: NonNull, - stage_buffer: B::Buffer, - stage_memory: MemoryBlock, + stage_buffer: A::Buffer, needs_flush: bool, }, /// Waiting for GPU to be done before mapping @@ -90,15 +89,15 @@ pub(crate) enum BufferMapState { /// Mapped Active { ptr: NonNull, - sub_range: hal::buffer::SubRange, + range: hal::MemoryRange, host: HostMap, }, /// Not mapped Idle, } -unsafe impl Send for BufferMapState {} -unsafe impl Sync for BufferMapState {} +unsafe impl Send for BufferMapState {} +unsafe impl Sync for BufferMapState {} pub type BufferMapCallback = unsafe extern "C" fn(status: BufferMapAsyncStatus, userdata: *mut u8); @@ -170,15 +169,16 @@ pub(crate) struct BufferPendingMapping { pub type BufferDescriptor<'a> = wgt::BufferDescriptor>; #[derive(Debug)] -pub struct Buffer { - pub(crate) raw: Option<(B::Buffer, MemoryBlock)>, +pub struct Buffer { + pub(crate) raw: Option, pub(crate) device_id: Stored, + pub(crate) is_coherent: bool, pub(crate) usage: wgt::BufferUsage, pub(crate) size: wgt::BufferAddress, pub(crate) initialization_status: MemoryInitTracker, - pub(crate) sync_mapped_writes: Option, + pub(crate) sync_mapped_writes: Option, pub(crate) life_guard: LifeGuard, - pub(crate) map_state: BufferMapState, + pub(crate) map_state: BufferMapState, } #[derive(Clone, Debug, Error)] @@ -195,7 +195,7 @@ pub enum CreateBufferError { UsageMismatch(wgt::BufferUsage), } -impl Resource for Buffer { +impl Resource for Buffer { const TYPE: &'static str = "Buffer"; fn life_guard(&self) -> &LifeGuard { @@ -203,7 +203,7 @@ impl Resource for Buffer { } } -impl Borrow<()> for Buffer { +impl Borrow<()> for Buffer { fn borrow(&self) -> &() { &DUMMY_SELECTOR } @@ -212,16 +212,11 @@ impl Borrow<()> for Buffer { pub type TextureDescriptor<'a> = wgt::TextureDescriptor>; #[derive(Debug)] -pub struct Texture { - pub(crate) raw: Option<(B::Image, MemoryBlock)>, +pub struct Texture { + pub(crate) raw: Option, pub(crate) device_id: Stored, - pub(crate) usage: wgt::TextureUsage, - pub(crate) aspects: hal::format::Aspects, - pub(crate) dimension: wgt::TextureDimension, - pub(crate) kind: hal::image::Kind, - pub(crate) format: wgt::TextureFormat, + pub(crate) desc: wgt::TextureDescriptor<()>, pub(crate) format_features: wgt::TextureFormatFeatures, - pub(crate) framebuffer_attachment: hal::image::FramebufferAttachment, pub(crate) full_range: TextureSelector, pub(crate) life_guard: LifeGuard, } @@ -265,7 +260,7 @@ pub enum CreateTextureError { MissingFeatures(wgt::TextureFormat, #[source] MissingFeatures), } -impl Resource for Texture { +impl Resource for Texture { const TYPE: &'static str = "Texture"; fn life_guard(&self) -> &LifeGuard { @@ -273,7 +268,7 @@ impl Resource for Texture { } } -impl Borrow for Texture { +impl Borrow for Texture { fn borrow(&self) -> &TextureSelector { &self.full_range } @@ -297,28 +292,25 @@ pub struct TextureViewDescriptor<'a> { } #[derive(Debug)] -pub(crate) enum TextureViewInner { +pub(crate) enum TextureViewInner { Native { - raw: B::ImageView, + raw: A::ImageView, source_id: Stored, }, SwapChain { - image: >::SwapchainImage, + raw: A::SwapChainTexture, source_id: Stored, }, } #[derive(Debug)] -pub struct TextureView { - pub(crate) inner: TextureViewInner, +pub struct TextureView { + pub(crate) inner: TextureViewInner, //TODO: store device_id for quick access? - pub(crate) aspects: hal::format::Aspects, - pub(crate) format: wgt::TextureFormat, + pub(crate) desc: hal::TextureViewDescriptor<()>, pub(crate) format_features: wgt::TextureFormatFeatures, - pub(crate) dimension: wgt::TextureViewDimension, pub(crate) extent: wgt::Extent3d, - pub(crate) samples: hal::image::NumSamples, - pub(crate) framebuffer_attachment: hal::image::FramebufferAttachment, + pub(crate) samples: u32, /// Internal use of this texture view when used as `BindingType::Texture`. pub(crate) sampled_internal_use: TextureUse, pub(crate) selector: TextureSelector, @@ -353,8 +345,8 @@ pub enum CreateTextureViewError { }, #[error("Aspect {requested:?} is not in the source texture ({total:?})")] InvalidAspect { - requested: hal::format::Aspects, - total: hal::format::Aspects, + requested: hal::FormatAspect, + total: hal::FormatAspect, }, } @@ -364,7 +356,7 @@ pub enum TextureViewDestroyError { SwapChainImage, } -impl Resource for TextureView { +impl Resource for TextureView { const TYPE: &'static str = "TextureView"; fn life_guard(&self) -> &LifeGuard { @@ -372,7 +364,7 @@ impl Resource for TextureView { } } -impl Borrow<()> for TextureView { +impl Borrow<()> for TextureView { fn borrow(&self) -> &() { &DUMMY_SELECTOR } @@ -423,8 +415,8 @@ impl Default for SamplerDescriptor<'_> { } #[derive(Debug)] -pub struct Sampler { - pub(crate) raw: B::Sampler, +pub struct Sampler { + pub(crate) raw: A::Sampler, pub(crate) device_id: Stored, pub(crate) life_guard: LifeGuard, /// `true` if this is a comparison sampler @@ -446,7 +438,7 @@ pub enum CreateSamplerError { MissingFeatures(#[from] MissingFeatures), } -impl Resource for Sampler { +impl Resource for Sampler { const TYPE: &'static str = "Sampler"; fn life_guard(&self) -> &LifeGuard { @@ -454,7 +446,7 @@ impl Resource for Sampler { } } -impl Borrow<()> for Sampler { +impl Borrow<()> for Sampler { fn borrow(&self) -> &() { &DUMMY_SELECTOR } @@ -472,8 +464,8 @@ pub enum CreateQuerySetError { } #[derive(Debug)] -pub struct QuerySet { - pub(crate) raw: B::QueryPool, +pub struct QuerySet { + pub(crate) raw: A::QuerySet, pub(crate) device_id: Stored, pub(crate) life_guard: LifeGuard, /// Amount of queries in the query set. @@ -482,7 +474,7 @@ pub struct QuerySet { pub(crate) elements: u32, } -impl Resource for QuerySet { +impl Resource for QuerySet { const TYPE: &'static str = "QuerySet"; fn life_guard(&self) -> &LifeGuard { @@ -490,7 +482,7 @@ impl Resource for QuerySet { } } -impl Borrow<()> for QuerySet { +impl Borrow<()> for QuerySet { fn borrow(&self) -> &() { &DUMMY_SELECTOR } diff --git a/wgpu-core/src/swap_chain.rs b/wgpu-core/src/swap_chain.rs index 8156efd5a..43cffca6d 100644 --- a/wgpu-core/src/swap_chain.rs +++ b/wgpu-core/src/swap_chain.rs @@ -37,14 +37,14 @@ use crate::device::trace::Action; use crate::{ conv, device::DeviceError, - hub::{GfxBackend, Global, GlobalIdentityHandlerFactory, Input, Token}, + hub::{Global, GlobalIdentityHandlerFactory, HalApi, Input, Token}, id::{DeviceId, SwapChainId, TextureViewId, Valid}, resource, track::TextureSelector, - LifeGuard, PrivateFeatures, Stored, SubmissionIndex, + LifeGuard, Stored, SubmissionIndex, }; -use hal::{queue::Queue as _, window::PresentationSurface as _}; +use hal::{Queue as _, Surface as _}; use thiserror::Error; use wgt::{SwapChainDescriptor, SwapChainStatus}; @@ -52,7 +52,7 @@ const FRAME_TIMEOUT_MS: u64 = 1000; pub const DESIRED_NUM_FRAMES: u32 = 3; #[derive(Debug)] -pub struct SwapChain { +pub struct SwapChain { pub(crate) life_guard: LifeGuard, pub(crate) device_id: Stored, pub(crate) desc: SwapChainDescriptor, @@ -63,7 +63,7 @@ pub struct SwapChain { pub(crate) framebuffer_attachment: hal::image::FramebufferAttachment, } -impl crate::hub::Resource for SwapChain { +impl crate::hub::Resource for SwapChain { const TYPE: &'static str = "SwapChain"; fn life_guard(&self) -> &LifeGuard { @@ -116,7 +116,7 @@ pub(crate) fn swap_chain_descriptor_to_hal( num_frames, ); //TODO: check for supported - config.image_usage = conv::map_texture_usage(desc.usage, hal::format::Aspects::COLOR); + config.image_usage = conv::map_texture_usage(desc.usage, hal::FormatAspect::COLOR); config.composite_alpha_mode = hal::window::CompositeAlphaMode::OPAQUE; config.present_mode = match desc.present_mode { wgt::PresentMode::Immediate => hal::window::PresentMode::IMMEDIATE, @@ -134,14 +134,14 @@ pub struct SwapChainOutput { } impl Global { - pub fn swap_chain_get_current_texture_view( + pub fn swap_chain_get_current_texture_view( &self, swap_chain_id: SwapChainId, view_id_in: Input, ) -> Result { profiling::scope!("get_next_texture", "SwapChain"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let fid = hub.texture_views.prepare(view_id_in); @@ -195,7 +195,7 @@ impl Global { ref_count: sc.life_guard.add_ref(), }, }, - aspects: hal::format::Aspects::COLOR, + aspects: hal::FormatAspect::COLOR, format: sc.desc.format, format_features: wgt::TextureFormatFeatures { allowed_usages: wgt::TextureUsage::RENDER_ATTACHMENT, @@ -238,13 +238,13 @@ impl Global { Ok(SwapChainOutput { status, view_id }) } - pub fn swap_chain_present( + pub fn swap_chain_present( &self, swap_chain_id: SwapChainId, ) -> Result { profiling::scope!("present", "SwapChain"); - let hub = B::hub(self); + let hub = A::hub(self); let mut token = Token::root(); let (mut surface_guard, mut token) = self.surfaces.write(&mut token); diff --git a/wgpu-core/src/track/mod.rs b/wgpu-core/src/track/mod.rs index e61765969..a314ddf24 100644 --- a/wgpu-core/src/track/mod.rs +++ b/wgpu-core/src/track/mod.rs @@ -126,9 +126,9 @@ pub(crate) struct PendingTransition { impl PendingTransition { /// Produce the gfx-hal barrier corresponding to the transition. - pub fn into_hal<'a, B: hal::Backend>( + pub fn into_hal<'a, A: hal::Api>( self, - buf: &'a resource::Buffer, + buf: &'a resource::Buffer, ) -> hal::memory::Barrier<'a, B> { log::trace!("\tbuffer -> {:?}", self); let &(ref target, _) = buf.raw.as_ref().expect("Buffer is destroyed"); @@ -153,9 +153,9 @@ impl From> for UsageConflict { impl PendingTransition { /// Produce the gfx-hal barrier corresponding to the transition. - pub fn into_hal<'a, B: hal::Backend>( + pub fn into_hal<'a, A: hal::Api>( self, - tex: &'a resource::Texture, + tex: &'a resource::Texture, ) -> hal::memory::Barrier<'a, B> { log::trace!("\ttexture -> {:?}", self); let &(ref target, _) = tex.raw.as_ref().expect("Texture is destroyed"); diff --git a/wgpu-core/src/track/texture.rs b/wgpu-core/src/track/texture.rs index 6d1d4a593..635d7017d 100644 --- a/wgpu-core/src/track/texture.rs +++ b/wgpu-core/src/track/texture.rs @@ -13,14 +13,13 @@ use arrayvec::ArrayVec; use std::{iter, ops::Range}; -//TODO: store `hal::image::State` here to avoid extra conversions -type PlaneStates = RangedStates>; +type PlaneStates = RangedStates>; #[derive(Clone, Debug, PartialEq, Eq)] pub struct TextureSelector { - //pub aspects: hal::format::Aspects, - pub levels: Range, - pub layers: Range, + //pub aspects: hal::FormatAspect, + pub levels: Range, + pub layers: Range, } #[derive(Clone, Debug, Default, PartialEq)] @@ -44,7 +43,7 @@ impl PendingTransition { } impl TextureState { - pub fn new(mip_level_count: hal::image::Level, array_layer_count: hal::image::Layer) -> Self { + pub fn new(mip_level_count: hal::MipLevel, array_layer_count: hal::ArrayLayer) -> Self { Self { mips: iter::repeat_with(|| { PlaneStates::from_range(0..array_layer_count, Unit::new(TextureUse::UNINITIALIZED)) @@ -104,7 +103,7 @@ impl ResourceState for TextureState { .iter_mut() .enumerate() { - let level = selector.levels.start + mip_id as hal::image::Level; + let level = selector.levels.start + mip_id as hal::MipLevel; let layers = mip.isolate(&selector.layers, Unit::new(usage)); for &mut (ref range, ref mut unit) in layers { if unit.last == usage && TextureUse::ORDERED.contains(usage) { @@ -154,7 +153,7 @@ impl ResourceState for TextureState { .iter_mut() .enumerate() { - let level = selector.levels.start + mip_id as hal::image::Level; + let level = selector.levels.start + mip_id as hal::MipLevel; let layers = mip.isolate(&selector.layers, Unit::new(usage)); for &mut (ref range, ref mut unit) in layers { match unit.first { @@ -193,7 +192,7 @@ impl ResourceState for TextureState { } for (mip_id, (mip_self, mip_other)) in self.mips.iter_mut().zip(&other.mips).enumerate() { - let level = mip_id as hal::image::Level; + let level = mip_id as hal::MipLevel; temp.extend(mip_self.merge(mip_other, 0)); mip_self.clear(); diff --git a/wgpu-hal/Cargo.toml b/wgpu-hal/Cargo.toml new file mode 100644 index 000000000..1874bc9cb --- /dev/null +++ b/wgpu-hal/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "wgpu-hal" +version = "0.1.0" +authors = ["wgpu developers"] +edition = "2018" +description = "WebGPU hardware abstraction layer" +homepage = "https://github.com/gfx-rs/wgpu" +repository = "https://github.com/gfx-rs/wgpu" +keywords = ["graphics"] +license = "MPL-2.0" + +[lib] + +[features] + +[dependencies] +bitflags = "1.0" +wgt = { package = "wgpu-types", path = "../wgpu-types" } diff --git a/wgpu-hal/src/empty.rs b/wgpu-hal/src/empty.rs new file mode 100644 index 000000000..65a8f11c4 --- /dev/null +++ b/wgpu-hal/src/empty.rs @@ -0,0 +1,130 @@ +pub struct Api; +pub struct Surface; +pub struct Adapter; +pub struct Queue; +pub struct Device; +pub struct CommandBuffer; +pub struct RenderPass; +pub struct ComputePass; +pub struct Resource; + +impl crate::Surface for Surface {} + +impl crate::Adapter for Adapter { + unsafe fn open( + &self, + _features: wgt::Features, + ) -> Result, crate::Error> { + Err(crate::Error::DeviceLost) + } + unsafe fn close(&self, _device: Device) {} + unsafe fn texture_format_capabilities( + &self, + _format: wgt::TextureFormat, + ) -> crate::TextureFormatCapability { + crate::TextureFormatCapability::empty() + } + unsafe fn surface_formats(&self, _surface: &Surface) -> Vec { + Vec::new() + } +} + +impl crate::Queue for Queue { + unsafe fn submit>(&mut self, _command_buffers: I) {} +} + +impl crate::Device for Device { + unsafe fn create_buffer( + &self, + _desc: &wgt::BufferDescriptor, + ) -> Result { + Ok(Resource) + } + unsafe fn destroy_buffer(&self, _buffer: Resource) {} + unsafe fn map_buffer( + &self, + _buffer: &Resource, + _range: crate::MemoryRange, + ) -> Result, crate::Error> { + Err(crate::Error::DeviceLost) + } + unsafe fn unmap_buffer(&self, _buffer: &Resource) {} + unsafe fn flush_mapped_ranges>( + &self, + _buffer: &Resource, + _ranges: I, + ) { + } + unsafe fn invalidate_mapped_ranges>( + &self, + _buffer: &Resource, + _ranges: I, + ) { + } + + unsafe fn create_texture( + &self, + _desc: &wgt::TextureDescriptor, + ) -> Result { + Ok(Resource) + } + unsafe fn destroy_texture(&self, _texture: Resource) {} + unsafe fn create_texture_view( + &self, + _texture: &Resource, + _desc: &crate::TextureViewDescriptor, + ) -> Result { + Ok(Resource) + } + unsafe fn destroy_texture_view(&self, _view: Resource) {} + unsafe fn create_sampler( + &self, + desc: &crate::SamplerDescriptor, + ) -> Result { + Ok(Resource) + } + unsafe fn destroy_sampler(&self, _sampler: Resource) {} + + unsafe fn create_command_buffer(&self) -> Result { + Ok(CommandBuffer) + } +} + +impl crate::CommandBuffer for CommandBuffer { + unsafe fn begin(&mut self) {} + unsafe fn end(&mut self) {} + + unsafe fn begin_render_pass(&mut self) -> RenderPass { + RenderPass + } + unsafe fn end_render_pass(&mut self, _pass: RenderPass) {} + unsafe fn begin_compute_pass(&mut self) -> ComputePass { + ComputePass + } + unsafe fn end_compute_pass(&mut self, _pass: ComputePass) {} +} + +impl crate::RenderPass for RenderPass {} +impl crate::ComputePass for ComputePass {} + +impl crate::Api for Api { + type Surface = Surface; + type Adapter = Adapter; + type Queue = Queue; + type Device = Device; + + type CommandBuffer = CommandBuffer; + type RenderPass = RenderPass; + type ComputePass = ComputePass; + + type Buffer = Resource; + type QuerySet = Resource; + type Texture = Resource; + type SwapChainTexture = Resource; + type TextureView = Resource; + type Sampler = Resource; + + unsafe fn enumerate_adapters(&self) -> Vec> { + Vec::new() + } +} diff --git a/wgpu-hal/src/lib.rs b/wgpu-hal/src/lib.rs new file mode 100644 index 000000000..715900bab --- /dev/null +++ b/wgpu-hal/src/lib.rs @@ -0,0 +1,248 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/*! This library describes the internal unsafe graphics abstraction API. + */ + +pub mod empty; + +use std::{fmt, num::NonZeroU8, ops::Range, ptr::NonNull}; + +use bitflags::bitflags; + +pub const MAX_ANISOTROPY: u8 = 16; +pub const MAX_BIND_GROUPS: usize = 8; + +pub type Label<'a> = Option<&'a str>; +pub type MemoryRange = Range; +pub type MipLevel = u8; +pub type ArrayLayer = u16; + +#[derive(Debug)] +pub enum Error { + OutOfMemory, + DeviceLost, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::OutOfMemory => write!(f, "out of memory"), + Self::DeviceLost => write!(f, "device is lost"), + } + } +} +impl std::error::Error for Error {} + +pub trait Api: Sized { + type Surface: Surface; + type Adapter: Adapter; + type Device: Device; + type Queue: Queue; + + type CommandBuffer: CommandBuffer; + type RenderPass: RenderPass; + type ComputePass: ComputePass; + + type Buffer; + type QuerySet; + type Texture; + type SwapChainTexture; + type TextureView; + type Sampler; + + unsafe fn enumerate_adapters(&self) -> Vec>; +} + +pub trait Surface {} + +pub trait Adapter { + unsafe fn open(&self, features: wgt::Features) -> Result, Error>; + unsafe fn close(&self, device: A::Device); + + /// Return the set of supported capabilities for a texture format. + unsafe fn texture_format_capabilities( + &self, + format: wgt::TextureFormat, + ) -> TextureFormatCapability; + /// Returns the list of surface formats supported for presentation, if any. + unsafe fn surface_formats(&self, surface: &A::Surface) -> Vec; +} + +pub trait Device { + unsafe fn create_buffer(&self, desc: &wgt::BufferDescriptor