From 749f737c89870ca6f3bfaad8d90f4fd983c62a9f Mon Sep 17 00:00:00 2001 From: Dzmitry Malyshau Date: Thu, 3 Dec 2020 00:30:38 -0500 Subject: [PATCH] Add pervasive Naga support to shader module loading The purpose of the PR is to support Naga modules everywhere. As a requirement, it updates the gfx-rs version used. Most of the logic is dedicated towards building a shader interface, where previously we just used naga's IR. Now we have our own mini-IR. --- Cargo.lock | 30 +- Cargo.toml | 12 + player/src/lib.rs | 27 +- player/tests/test.rs | 7 + wgpu-core/Cargo.toml | 40 +- wgpu-core/build.rs | 4 +- wgpu-core/src/command/bundle.rs | 3 +- wgpu-core/src/device/descriptor.rs | 19 +- wgpu-core/src/device/mod.rs | 307 ++++--- wgpu-core/src/pipeline.rs | 24 +- wgpu-core/src/swap_chain.rs | 7 +- wgpu-core/src/validation.rs | 1233 +++++++++++++--------------- 12 files changed, 826 insertions(+), 887 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 581d27072..d9a089222 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -441,7 +441,7 @@ dependencies = [ [[package]] name = "gfx-auxil" version = "0.5.0" -source = "git+https://github.com/gfx-rs/gfx?rev=1d14789011cb892f4c1a205d3f8a87d479c2e354#1d14789011cb892f4c1a205d3f8a87d479c2e354" +source = "git+https://github.com/gfx-rs/gfx?rev=654ad48ee39ce2a341407ae2857ddf4db639ea54#654ad48ee39ce2a341407ae2857ddf4db639ea54" dependencies = [ "fxhash", "gfx-hal", @@ -451,7 +451,7 @@ dependencies = [ [[package]] name = "gfx-backend-dx11" version = "0.6.0" -source = "git+https://github.com/gfx-rs/gfx?rev=1d14789011cb892f4c1a205d3f8a87d479c2e354#1d14789011cb892f4c1a205d3f8a87d479c2e354" +source = "git+https://github.com/gfx-rs/gfx?rev=654ad48ee39ce2a341407ae2857ddf4db639ea54#654ad48ee39ce2a341407ae2857ddf4db639ea54" dependencies = [ "arrayvec", "bitflags", @@ -472,7 +472,7 @@ dependencies = [ [[package]] name = "gfx-backend-dx12" version = "0.6.2" -source = "git+https://github.com/gfx-rs/gfx?rev=1d14789011cb892f4c1a205d3f8a87d479c2e354#1d14789011cb892f4c1a205d3f8a87d479c2e354" +source = "git+https://github.com/gfx-rs/gfx?rev=654ad48ee39ce2a341407ae2857ddf4db639ea54#654ad48ee39ce2a341407ae2857ddf4db639ea54" dependencies = [ "arrayvec", "bit-set", @@ -492,7 +492,7 @@ dependencies = [ [[package]] name = "gfx-backend-empty" version = "0.6.0" -source = "git+https://github.com/gfx-rs/gfx?rev=1d14789011cb892f4c1a205d3f8a87d479c2e354#1d14789011cb892f4c1a205d3f8a87d479c2e354" +source = "git+https://github.com/gfx-rs/gfx?rev=654ad48ee39ce2a341407ae2857ddf4db639ea54#654ad48ee39ce2a341407ae2857ddf4db639ea54" dependencies = [ "gfx-hal", "log", @@ -502,7 +502,7 @@ dependencies = [ [[package]] name = "gfx-backend-gl" version = "0.6.0" -source = "git+https://github.com/gfx-rs/gfx?rev=1d14789011cb892f4c1a205d3f8a87d479c2e354#1d14789011cb892f4c1a205d3f8a87d479c2e354" +source = "git+https://github.com/gfx-rs/gfx?rev=654ad48ee39ce2a341407ae2857ddf4db639ea54#654ad48ee39ce2a341407ae2857ddf4db639ea54" dependencies = [ "arrayvec", "bitflags", @@ -524,7 +524,7 @@ dependencies = [ [[package]] name = "gfx-backend-metal" version = "0.6.0" -source = "git+https://github.com/gfx-rs/gfx?rev=1d14789011cb892f4c1a205d3f8a87d479c2e354#1d14789011cb892f4c1a205d3f8a87d479c2e354" +source = "git+https://github.com/gfx-rs/gfx?rev=654ad48ee39ce2a341407ae2857ddf4db639ea54#654ad48ee39ce2a341407ae2857ddf4db639ea54" dependencies = [ "arrayvec", "bitflags", @@ -537,6 +537,7 @@ dependencies = [ "lazy_static", "log", "metal", + "naga", "objc", "parking_lot 0.11.0", "range-alloc", @@ -548,7 +549,7 @@ dependencies = [ [[package]] name = "gfx-backend-vulkan" version = "0.6.5" -source = "git+https://github.com/gfx-rs/gfx?rev=1d14789011cb892f4c1a205d3f8a87d479c2e354#1d14789011cb892f4c1a205d3f8a87d479c2e354" +source = "git+https://github.com/gfx-rs/gfx?rev=654ad48ee39ce2a341407ae2857ddf4db639ea54#654ad48ee39ce2a341407ae2857ddf4db639ea54" dependencies = [ "arrayvec", "ash", @@ -567,10 +568,12 @@ dependencies = [ [[package]] name = "gfx-hal" version = "0.6.0" -source = "git+https://github.com/gfx-rs/gfx?rev=1d14789011cb892f4c1a205d3f8a87d479c2e354#1d14789011cb892f4c1a205d3f8a87d479c2e354" +source = "git+https://github.com/gfx-rs/gfx?rev=654ad48ee39ce2a341407ae2857ddf4db639ea54#654ad48ee39ce2a341407ae2857ddf4db639ea54" dependencies = [ "bitflags", + "naga", "raw-window-handle", + "thiserror", ] [[package]] @@ -605,7 +608,7 @@ dependencies = [ [[package]] name = "gpu-descriptor" version = "0.1.0" -source = "git+https://github.com/zakarumych/gpu-descriptor?rev=831460c4b5120d9a74744d542f39a95b9816b5ab#831460c4b5120d9a74744d542f39a95b9816b5ab" +source = "git+https://github.com/zakarumych/gpu-descriptor?rev=df74fd8c7bea03149058a41aab0e4fe04077b266#df74fd8c7bea03149058a41aab0e4fe04077b266" dependencies = [ "bitflags", "gpu-descriptor-types", @@ -615,7 +618,7 @@ dependencies = [ [[package]] name = "gpu-descriptor-types" version = "0.1.0" -source = "git+https://github.com/zakarumych/gpu-descriptor?rev=831460c4b5120d9a74744d542f39a95b9816b5ab#831460c4b5120d9a74744d542f39a95b9816b5ab" +source = "git+https://github.com/zakarumych/gpu-descriptor?rev=df74fd8c7bea03149058a41aab0e4fe04077b266#df74fd8c7bea03149058a41aab0e4fe04077b266" dependencies = [ "bitflags", ] @@ -830,7 +833,7 @@ version = "0.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" dependencies = [ - "libc 0.2.80", + "libc 0.1.12", ] [[package]] @@ -924,13 +927,14 @@ dependencies = [ [[package]] name = "naga" version = "0.2.0" -source = "git+https://github.com/gfx-rs/naga?rev=96c80738650822de35f77ab6a589f309460c8f39#96c80738650822de35f77ab6a589f309460c8f39" +source = "git+https://github.com/gfx-rs/naga?tag=gfx-2#0d81b1f78c763a2f564194ec108bcb8ead10ea2e" dependencies = [ "bitflags", "fxhash", "log", "num-traits", "petgraph", + "serde", "spirv_headers", "thiserror", ] @@ -1213,7 +1217,7 @@ dependencies = [ [[package]] name = "range-alloc" version = "0.1.1" -source = "git+https://github.com/gfx-rs/gfx?rev=1d14789011cb892f4c1a205d3f8a87d479c2e354#1d14789011cb892f4c1a205d3f8a87d479c2e354" +source = "git+https://github.com/gfx-rs/gfx?rev=654ad48ee39ce2a341407ae2857ddf4db639ea54#654ad48ee39ce2a341407ae2857ddf4db639ea54" [[package]] name = "raw-window-handle" diff --git a/Cargo.toml b/Cargo.toml index 0c0dfcc41..e56687ffb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,3 +5,15 @@ members = [ "wgpu-core", "wgpu-types", ] + +#[patch."https://github.com/gfx-rs/gfx"] +#hal = { package = "gfx-hal", path = "../gfx/src/hal" } +#gfx-backend-vulkan = { path = "../gfx/src/backend/vulkan" } +#gfx-backend-metal = { path = "../gfx/src/backend/metal", features = ["naga"] } +#gfx-backend-gl = { path = "../gfx/src/backend/gl" } +#gfx-backend-dx12 = { path = "../gfx/src/backend/dx12" } +#gfx-backend-dx11 = { path = "../gfx/src/backend/dx11" } +#gfx-backend-empty = { path = "../gfx/src/backend/empty" } + +#[patch."https://github.com/gfx-rs/naga"] +#naga = { path = "../naga" } diff --git a/player/src/lib.rs b/player/src/lib.rs index 140ff7050..33dfc494f 100644 --- a/player/src/lib.rs +++ b/player/src/lib.rs @@ -209,22 +209,23 @@ impl GlobalPlay for wgc::hub::Global { A::DestroyBindGroup(id) => { self.bind_group_drop::(id); } - A::CreateShaderModule { id, data, label } => { + A::CreateShaderModule { id, label, data } => { let desc = wgc::pipeline::ShaderModuleDescriptor { - source: if data.ends_with(".wgsl") { - let code = fs::read_to_string(dir.join(data)).unwrap(); - wgc::pipeline::ShaderModuleSource::Wgsl(Cow::Owned(code)) - } else { - let byte_vec = fs::read(dir.join(data)).unwrap(); - let spv = byte_vec - .chunks(4) - .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect::>(); - wgc::pipeline::ShaderModuleSource::SpirV(Cow::Owned(spv)) - }, label, + experimental_translation: false, }; - let (_, error) = self.device_create_shader_module::(device, &desc, id); + let source = if data.ends_with(".wgsl") { + let code = fs::read_to_string(dir.join(data)).unwrap(); + wgc::pipeline::ShaderModuleSource::Wgsl(Cow::Owned(code)) + } else { + let byte_vec = fs::read(dir.join(data)).unwrap(); + let spv = byte_vec + .chunks(4) + .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect::>(); + wgc::pipeline::ShaderModuleSource::SpirV(Cow::Owned(spv)) + }; + let (_, error) = self.device_create_shader_module::(device, &desc, source, id); if let Some(e) = error { panic!("{:?}", e); } diff --git a/player/tests/test.rs b/player/tests/test.rs index 1b33fff58..a79ed3a5c 100644 --- a/player/tests/test.rs +++ b/player/tests/test.rs @@ -213,5 +213,12 @@ impl Corpus { #[test] fn test_api() { + wgpu_subscriber::initialize_default_subscriber( + std::env::var("WGPU_CHROME_TRACE") + .as_ref() + .map(Path::new) + .ok(), + ); + Corpus::run_from(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/all.ron")) } diff --git a/wgpu-core/Cargo.toml b/wgpu-core/Cargo.toml index 7aad0a8ec..cee96fdde 100644 --- a/wgpu-core/Cargo.toml +++ b/wgpu-core/Cargo.toml @@ -14,9 +14,9 @@ license = "MPL-2.0" [features] default = [] # Enable API tracing -trace = ["ron", "serde", "wgt/trace"] +trace = ["ron", "serde", "wgt/trace", "naga/serialize"] # Enable API replaying -replay = ["serde", "wgt/replay"] +replay = ["serde", "wgt/replay", "naga/deserialize"] # Enable serializable compute/render passes, and bundle encoders. serial-pass = ["serde", "wgt/serde", "arrayvec/serde"] @@ -25,8 +25,6 @@ arrayvec = "0.5" bitflags = "1.0" copyless = "0.1" fxhash = "0.2" -hal = { package = "gfx-hal", git = "https://github.com/gfx-rs/gfx", rev = "1d14789011cb892f4c1a205d3f8a87d479c2e354" } -gfx-backend-empty = { git = "https://github.com/gfx-rs/gfx", rev = "1d14789011cb892f4c1a205d3f8a87d479c2e354" } parking_lot = "0.11" raw-window-handle = { version = "0.3", optional = true } ron = { version = "0.6", optional = true } @@ -35,12 +33,27 @@ smallvec = "1" tracing = { version = "0.1", default-features = false, features = ["std"] } thiserror = "1" gpu-alloc = { git = "https://github.com/zakarumych/gpu-alloc", rev = "d07be73f9439a37c89f5b72f2500cbf0eb4ff613" } -gpu-descriptor = { git = "https://github.com/zakarumych/gpu-descriptor", rev = "831460c4b5120d9a74744d542f39a95b9816b5ab"} +gpu-descriptor = { git = "https://github.com/zakarumych/gpu-descriptor", rev = "df74fd8c7bea03149058a41aab0e4fe04077b266"} + +hal = { package = "gfx-hal", git = "https://github.com/gfx-rs/gfx", rev = "654ad48ee39ce2a341407ae2857ddf4db639ea54" } +gfx-backend-empty = { git = "https://github.com/gfx-rs/gfx", rev = "654ad48ee39ce2a341407ae2857ddf4db639ea54" } + +[target.'cfg(all(unix, not(target_os = "ios"), not(target_os = "macos")))'.dependencies] +gfx-backend-vulkan = { git = "https://github.com/gfx-rs/gfx", rev = "654ad48ee39ce2a341407ae2857ddf4db639ea54" } +gfx-backend-gl = { git = "https://github.com/gfx-rs/gfx", rev = "654ad48ee39ce2a341407ae2857ddf4db639ea54" } + +[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies] +gfx-backend-metal = { git = "https://github.com/gfx-rs/gfx", rev = "654ad48ee39ce2a341407ae2857ddf4db639ea54", features = ["naga"] } +gfx-backend-vulkan = { git = "https://github.com/gfx-rs/gfx", rev = "654ad48ee39ce2a341407ae2857ddf4db639ea54", optional = true } + +[target.'cfg(windows)'.dependencies] +gfx-backend-dx12 = { git = "https://github.com/gfx-rs/gfx", rev = "654ad48ee39ce2a341407ae2857ddf4db639ea54" } +gfx-backend-dx11 = { git = "https://github.com/gfx-rs/gfx", rev = "654ad48ee39ce2a341407ae2857ddf4db639ea54" } +gfx-backend-vulkan = { git = "https://github.com/gfx-rs/gfx", rev = "654ad48ee39ce2a341407ae2857ddf4db639ea54" } [dependencies.naga] -version = "0.2" git = "https://github.com/gfx-rs/naga" -rev = "96c80738650822de35f77ab6a589f309460c8f39" +tag = "gfx-2" features = ["spv-in", "spv-out", "wgsl-in"] [dependencies.wgt] @@ -48,19 +61,6 @@ path = "../wgpu-types" package = "wgpu-types" version = "0.6" -[target.'cfg(all(unix, not(target_os = "ios"), not(target_os = "macos")))'.dependencies] -gfx-backend-vulkan = { git = "https://github.com/gfx-rs/gfx", rev = "1d14789011cb892f4c1a205d3f8a87d479c2e354" } -gfx-backend-gl = { git = "https://github.com/gfx-rs/gfx", rev = "1d14789011cb892f4c1a205d3f8a87d479c2e354" } - -[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies] -gfx-backend-metal = { git = "https://github.com/gfx-rs/gfx", rev = "1d14789011cb892f4c1a205d3f8a87d479c2e354" } -gfx-backend-vulkan = { git = "https://github.com/gfx-rs/gfx", rev = "1d14789011cb892f4c1a205d3f8a87d479c2e354", optional = true } - -[target.'cfg(windows)'.dependencies] -gfx-backend-dx12 = { git = "https://github.com/gfx-rs/gfx", rev = "1d14789011cb892f4c1a205d3f8a87d479c2e354" } -gfx-backend-dx11 = { git = "https://github.com/gfx-rs/gfx", rev = "1d14789011cb892f4c1a205d3f8a87d479c2e354" } -gfx-backend-vulkan = { git = "https://github.com/gfx-rs/gfx", rev = "1d14789011cb892f4c1a205d3f8a87d479c2e354" } - [dev-dependencies] loom = "0.3" diff --git a/wgpu-core/build.rs b/wgpu-core/build.rs index 69a4ba966..1a44cec6f 100644 --- a/wgpu-core/build.rs +++ b/wgpu-core/build.rs @@ -6,9 +6,7 @@ fn main() { // Setup cfg aliases cfg_aliases::cfg_aliases! { // Vendors/systems - ios: { target_os = "ios" }, - macos: { target_os = "macos" }, - apple: { any(ios, macos) }, + apple: { any(target_os = "ios", target_os = "macos") }, // Backends vulkan: { any(windows, all(unix, not(apple)), feature = "gfx-backend-vulkan") }, diff --git a/wgpu-core/src/command/bundle.rs b/wgpu-core/src/command/bundle.rs index ba48b64eb..47dcbed11 100644 --- a/wgpu-core/src/command/bundle.rs +++ b/wgpu-core/src/command/bundle.rs @@ -500,7 +500,6 @@ impl RenderBundle { use hal::command::CommandBuffer as _; let mut offsets = self.base.dynamic_offsets.as_slice(); - let mut index_type = hal::IndexType::U16; let mut pipeline_layout_id = None::>; for command in self.base.commands.iter() { @@ -531,7 +530,7 @@ impl RenderBundle { offset, size, } => { - index_type = conv::map_index_format(index_format); + let index_type = conv::map_index_format(index_format); let &(ref buffer, _) = buffer_guard .get(buffer_id) diff --git a/wgpu-core/src/device/descriptor.rs b/wgpu-core/src/device/descriptor.rs index 92b896bd3..b52630b21 100644 --- a/wgpu-core/src/device/descriptor.rs +++ b/wgpu-core/src/device/descriptor.rs @@ -17,7 +17,7 @@ struct DescriptorDevice<'a, B: hal::Backend>(&'a B::Device); impl DescriptorAllocator { pub fn new() -> Self { - DescriptorAllocator(unsafe { gpu_descriptor::DescriptorAllocator::new(0) }) + DescriptorAllocator(gpu_descriptor::DescriptorAllocator::new(0)) } pub fn allocate( @@ -27,18 +27,19 @@ impl DescriptorAllocator { layout_descriptor_count: &DescriptorTotalCount, count: u32, ) -> Result>, DeviceError> { - self.0 - .allocate( + unsafe { + self.0.allocate( &DescriptorDevice::(device), layout, gpu_descriptor::DescriptorSetLayoutCreateFlags::empty(), layout_descriptor_count, count, ) - .map_err(|err| { - tracing::warn!("Descriptor set allocation failed: {}", err); - DeviceError::OutOfMemory - }) + } + .map_err(|err| { + tracing::warn!("Descriptor set allocation failed: {}", err); + DeviceError::OutOfMemory + }) } pub fn free(&mut self, device: &B::Device, sets: impl IntoIterator>) { @@ -46,7 +47,7 @@ impl DescriptorAllocator { } pub fn cleanup(&mut self, device: &B::Device) { - self.0.cleanup(&DescriptorDevice::(device)) + unsafe { self.0.cleanup(&DescriptorDevice::(device)) } } } @@ -121,7 +122,7 @@ impl self.0, max_sets as usize, ranges, - hal::pso::DescriptorPoolCreateFlags::from_bits_truncate(flags.bits() as u32), + hal::pso::DescriptorPoolCreateFlags::from_bits_truncate(flags.bits()), ) { Ok(pool) => Ok(pool), Err(hal::device::OutOfMemory::Host) => { diff --git a/wgpu-core/src/device/mod.rs b/wgpu-core/src/device/mod.rs index b1b7105fe..69a84d05d 100644 --- a/wgpu-core/src/device/mod.rs +++ b/wgpu-core/src/device/mod.rs @@ -836,84 +836,105 @@ impl Device { fn create_shader_module<'a>( &self, self_id: id::DeviceId, - desc: &'a pipeline::ShaderModuleDescriptor<'a>, - ) -> Result<(pipeline::ShaderModule, Cow<'a, [u32]>), pipeline::CreateShaderModuleError> - { - let spv_flags = if cfg!(debug_assertions) { - naga::back::spv::WriterFlags::DEBUG - } else { - naga::back::spv::WriterFlags::empty() - }; - - let (spv, naga) = match desc.source { - pipeline::ShaderModuleSource::SpirV(ref spv) => { - let module = if self.private_features.shader_validation { - // Parse the given shader code and store its representation. - let spv_iter = spv.iter().cloned(); - naga::front::spv::Parser::new(spv_iter, &Default::default()) - .parse() - .map_err(|err| { - // TODO: eventually, when Naga gets support for all features, - // we want to convert these to a hard error, - tracing::warn!("Failed to parse shader SPIR-V code: {:?}", err); - tracing::warn!("Shader module will not be validated"); - }) - .ok() - } else { - None + desc: &pipeline::ShaderModuleDescriptor<'a>, + source: pipeline::ShaderModuleSource<'a>, + ) -> Result, pipeline::CreateShaderModuleError> { + // First, try to produce a Naga module. + let (spv, module) = match source { + pipeline::ShaderModuleSource::SpirV(spv) => { + // Parse the given shader code and store its representation. + let parser = + naga::front::spv::Parser::new(spv.iter().cloned(), &Default::default()); + let module = match parser.parse() { + Ok(module) => Some(module), + Err(err) => { + // TODO: eventually, when Naga gets support for all features, + // we want to convert these to a hard error, + tracing::warn!("Failed to parse shader SPIR-V code: {:?}", err); + tracing::warn!("Shader module will not be validated or reflected"); + None + } }; - (Cow::Borrowed(&**spv), module) + (Some(spv), module) } - pipeline::ShaderModuleSource::Wgsl(ref code) => { + pipeline::ShaderModuleSource::Wgsl(code) => { // TODO: refactor the corresponding Naga error to be owned, and then // display it instead of unwrapping - let module = naga::front::wgsl::parse_str(code).unwrap(); - let spv = naga::back::spv::Writer::new(&module.header, spv_flags).write(&module); - ( - Cow::Owned(spv), - if self.private_features.shader_validation { - Some(module) - } else { - None - }, - ) - } /* - pipeline::ShaderModuleSource::Naga(module) => { - let spv = naga::back::spv::Writer::new(&module.header, spv_flags).write(&module); - ( - Cow::Owned(spv), - if device.private_features.shader_validation { - Some(module) - } else { - None - }, - ) - }*/ + match naga::front::wgsl::parse_str(&code) { + Ok(module) => (None, Some(module)), + Err(err) => { + tracing::error!("Failed to parse WGSL code: {}", err); + return Err(pipeline::CreateShaderModuleError::Parsing); + } + } + } + pipeline::ShaderModuleSource::Naga(module) => (None, Some(module)), }; - if let Some(ref module) = naga { - naga::proc::Validator::new().validate(module)?; - } + let interface = module.as_ref().map(|m| validation::Interface::new(m)); - let raw = unsafe { - self.raw - .create_shader_module(&spv) - .map_err(|err| match err { - hal::device::ShaderError::OutOfMemory(_) => DeviceError::OutOfMemory, - _ => panic!("failed to create shader module: {}", err), - })? + let naga_result = match module { + // If succeeded, then validate it and attempt to give it to gfx-hal directly. + Some(module) => { + if self.private_features.shader_validation { + naga::proc::Validator::new().validate(&module)?; + } + if desc.experimental_translation { + match unsafe { self.raw.create_shader_module_from_naga(module) } { + Ok(raw) => Ok(raw), + Err((hal::device::ShaderError::CompilationFailed(msg), module)) => { + tracing::warn!("Shader module compilation failed: {}", msg); + Err(Some(module)) + } + Err((_, module)) => Err(Some(module)), + } + } else { + Err(Some(module)) + } + } + None => Err(None), }; - let shader = pipeline::ShaderModule { - raw, + + // Otherwise, fall back to SPIR-V. + let spv_result = match naga_result { + Ok(raw) => Ok(raw), + Err(maybe_module) => { + let spv = match spv { + Some(data) => data, + None => { + // Produce a SPIR-V from the Naga module + let module = maybe_module.unwrap(); + let mut flags = naga::back::spv::WriterFlags::empty(); + if cfg!(debug_assertions) { + flags |= naga::back::spv::WriterFlags::DEBUG; + } + let data = naga::back::spv::write_vec(&module, flags); + Cow::Owned(data) + } + }; + unsafe { self.raw.create_shader_module(&spv) } + } + }; + + Ok(pipeline::ShaderModule { + raw: match spv_result { + Ok(raw) => raw, + Err(hal::device::ShaderError::OutOfMemory(_)) => { + return Err(DeviceError::OutOfMemory.into()); + } + Err(error) => { + tracing::error!("Shader error: {}", error); + return Err(pipeline::CreateShaderModuleError::Parsing); + } + }, device_id: Stored { value: id::Valid(self_id), ref_count: self.life_guard.add_ref(), }, - module: naga, + interface, #[cfg(debug_assertions)] label: desc.label.to_string_or_default(), - }; - Ok((shader, spv)) + }) } /// Create a compatible render pass with a given key. @@ -968,14 +989,12 @@ impl Device { fn get_introspection_bind_group_layouts<'a>( pipeline_layout: &binding_model::PipelineLayout, bgl_guard: &'a Storage, id::BindGroupLayoutId>, - ) -> validation::IntrospectionBindGroupLayouts<'a> { - validation::IntrospectionBindGroupLayouts::Given( - pipeline_layout - .bind_group_layout_ids - .iter() - .map(|&id| &bgl_guard[id].entries) - .collect(), - ) + ) -> ArrayVec<[&'a binding_model::BindEntryMap; MAX_BIND_GROUPS]> { + pipeline_layout + .bind_group_layout_ids + .iter() + .map(|&id| &bgl_guard[id].entries) + .collect() } fn create_bind_group_layout( @@ -1633,7 +1652,7 @@ impl Device { let mut derived_group_layouts = ArrayVec::<[binding_model::BindEntryMap; MAX_BIND_GROUPS]>::new(); - let interface = validation::StageInterface::default(); + let io = validation::StageIo::default(); let pipeline_stage = &desc.compute_stage; let (shader_module_guard, _) = hub.shader_modules.read(&mut token); @@ -1645,24 +1664,30 @@ impl Device { })?; let flag = wgt::ShaderStage::COMPUTE; - if let Some(ref module) = shader_module.module { - let group_layouts = match desc.layout { - Some(pipeline_layout_id) => Device::get_introspection_bind_group_layouts( + if let Some(ref interface) = shader_module.interface { + let provided_layouts = match desc.layout { + Some(pipeline_layout_id) => Some(Device::get_introspection_bind_group_layouts( pipeline_layout_guard .get(pipeline_layout_id) .map_err(|_| pipeline::CreateComputePipelineError::InvalidLayout)?, &*bgl_guard, - ), + )), None => { for _ in 0..self.limits.max_bind_groups { derived_group_layouts.push(binding_model::BindEntryMap::default()); } - validation::IntrospectionBindGroupLayouts::Derived(&mut derived_group_layouts) + None } }; - let _ = - validation::check_stage(module, group_layouts, &entry_point_name, flag, interface) - .map_err(pipeline::CreateComputePipelineError::Stage)?; + let _ = interface + .check_stage( + provided_layouts.as_ref().map(|p| p.as_slice()), + &mut derived_group_layouts, + &entry_point_name, + flag, + io, + ) + .map_err(pipeline::CreateComputePipelineError::Stage)?; } else if desc.layout.is_none() { return Err(pipeline::ImplicitLayoutError::ReflectionError(flag).into()); } @@ -1768,7 +1793,7 @@ impl Device { .unwrap_or_default(); let rasterizer = conv::map_rasterization_state_descriptor(&rasterization_state); - let mut interface = validation::StageInterface::default(); + let mut io = validation::StageIo::default(); let mut validated_stages = wgt::ShaderStage::empty(); let desc_vbs = &desc.vertex_state.vertex_buffers; @@ -1814,9 +1839,9 @@ impl Device { offset: attribute.offset as u32, }, }); - interface.insert( + io.insert( attribute.shader_location, - validation::MaybeOwned::Owned(validation::map_vertex_format(attribute.format)), + validation::NumericType::from_vertex_format(attribute.format), ); } } @@ -1929,27 +1954,26 @@ impl Device { error: validation::StageError::InvalidModule, })?; - if let Some(ref module) = shader_module.module { - let group_layouts = match desc.layout { - Some(pipeline_layout_id) => Device::get_introspection_bind_group_layouts( + if let Some(ref interface) = shader_module.interface { + let provided_layouts = match desc.layout { + Some(pipeline_layout_id) => Some(Device::get_introspection_bind_group_layouts( pipeline_layout_guard .get(pipeline_layout_id) .map_err(|_| pipeline::CreateRenderPipelineError::InvalidLayout)?, &*bgl_guard, - ), - None => validation::IntrospectionBindGroupLayouts::Derived( - &mut derived_group_layouts, - ), + )), + None => None, }; - interface = validation::check_stage( - module, - group_layouts, - &entry_point_name, - flag, - interface, - ) - .map_err(|error| pipeline::CreateRenderPipelineError::Stage { flag, error })?; + io = interface + .check_stage( + provided_layouts.as_ref().map(|p| p.as_slice()), + &mut derived_group_layouts, + &entry_point_name, + flag, + io, + ) + .map_err(|error| pipeline::CreateRenderPipelineError::Stage { flag, error })?; validated_stages |= flag; } @@ -1972,30 +1996,30 @@ impl Device { } })?; - let group_layouts = match desc.layout { - Some(pipeline_layout_id) => Device::get_introspection_bind_group_layouts( + let provided_layouts = match desc.layout { + Some(pipeline_layout_id) => Some(Device::get_introspection_bind_group_layouts( pipeline_layout_guard .get(pipeline_layout_id) .map_err(|_| pipeline::CreateRenderPipelineError::InvalidLayout)?, &*bgl_guard, - ), - None => validation::IntrospectionBindGroupLayouts::Derived( - &mut derived_group_layouts, - ), + )), + None => None, }; if validated_stages == wgt::ShaderStage::VERTEX { - if let Some(ref module) = shader_module.module { - interface = validation::check_stage( - module, - group_layouts, - &entry_point_name, - flag, - interface, - ) - .map_err(|error| { - pipeline::CreateRenderPipelineError::Stage { flag, error } - })?; + if let Some(ref interface) = shader_module.interface { + io = interface + .check_stage( + provided_layouts.as_ref().map(|p| p.as_slice()), + &mut derived_group_layouts, + &entry_point_name, + flag, + io, + ) + .map_err(|error| pipeline::CreateRenderPipelineError::Stage { + flag, + error, + })?; validated_stages |= flag; } } @@ -2011,13 +2035,13 @@ impl Device { if validated_stages.contains(wgt::ShaderStage::FRAGMENT) { for (i, state) in color_states.iter().enumerate() { - match interface.get(&(i as wgt::ShaderLocation)) { + match io.get(&(i as wgt::ShaderLocation)) { Some(output) if validation::check_texture_format(state.format, output) => {} Some(output) => { tracing::warn!( "Incompatible fragment output[{}] from shader: {:?}, expected {:?}", i, - &**output, + output, state.format, ); return Err( @@ -2247,11 +2271,11 @@ pub enum DeviceError { OutOfMemory, } -impl From for DeviceError { - fn from(err: hal::device::OomOrDeviceLost) -> Self { +impl From for DeviceError { + fn from(err: hal::device::WaitError) -> Self { match err { - hal::device::OomOrDeviceLost::OutOfMemory(_) => Self::OutOfMemory, - hal::device::OomOrDeviceLost::DeviceLost(_) => Self::Lost, + hal::device::WaitError::OutOfMemory(_) => Self::OutOfMemory, + hal::device::WaitError::DeviceLost(_) => Self::Lost, } } } @@ -3238,6 +3262,7 @@ impl Global { &self, device_id: id::DeviceId, desc: &pipeline::ShaderModuleDescriptor, + source: pipeline::ShaderModuleSource, id_in: Input, ) -> ( id::ShaderModuleId, @@ -3254,20 +3279,41 @@ impl Global { Ok(device) => device, Err(_) => break DeviceError::Invalid.into(), }; - let (shader, spv) = match device.create_shader_module(device_id, desc) { - Ok(pair) => pair, - Err(e) => break e, + #[cfg(feature = "trace")] + let data = match device.trace { + Some(ref trace) => { + let mut trace = trace.lock(); + match source { + pipeline::ShaderModuleSource::SpirV(ref spv) => { + trace.make_binary("spv", unsafe { + std::slice::from_raw_parts(spv.as_ptr() as *const u8, spv.len() * 4) + }) + } + pipeline::ShaderModuleSource::Wgsl(ref code) => { + trace.make_binary("wgsl", code.as_bytes()) + } + pipeline::ShaderModuleSource::Naga(ref module) => { + let config = ron::ser::PrettyConfig::new(); + let mut ron = Vec::new(); + ron::ser::to_writer_pretty(&mut ron, &module, config).unwrap(); + trace.make_binary("ron", &ron) + } + } + } + None => String::new(), }; + let shader = match device.create_shader_module(device_id, desc, source) { + Ok(shader) => shader, + Err(e) => break e, + }; let id = hub .shader_modules .register_identity(id_in, shader, &mut token); + #[cfg(feature = "trace")] if let Some(ref trace) = device.trace { let mut trace = trace.lock(); - let data = trace.make_binary("spv", unsafe { - std::slice::from_raw_parts(spv.as_ptr() as *const u8, spv.len() * 4) - }); let label = desc.label.clone(); trace.add(trace::Action::CreateShaderModule { id: id.0, @@ -3276,7 +3322,6 @@ impl Global { }); } - let _ = spv; return (id.0, None); }; @@ -3859,8 +3904,8 @@ impl Global { B::get_surface_mut(surface) .configure_swapchain(&device.raw, config) .map_err(|err| match err { - hal::window::CreationError::OutOfMemory(_) => DeviceError::OutOfMemory, - hal::window::CreationError::DeviceLost(_) => DeviceError::Lost, + hal::window::SwapchainError::OutOfMemory(_) => DeviceError::OutOfMemory, + hal::window::SwapchainError::DeviceLost(_) => DeviceError::Lost, _ => panic!("failed to configure swap chain on creation: {}", err), })?; } diff --git a/wgpu-core/src/pipeline.rs b/wgpu-core/src/pipeline.rs index 07e5119fd..9c90df0c4 100644 --- a/wgpu-core/src/pipeline.rs +++ b/wgpu-core/src/pipeline.rs @@ -7,37 +7,33 @@ use crate::{ device::{DeviceError, RenderPassContext}, hub::Resource, id::{DeviceId, PipelineLayoutId, ShaderModuleId}, - validation::StageError, - Label, LifeGuard, Stored, + validation, Label, LifeGuard, Stored, }; use std::borrow::Cow; use thiserror::Error; use wgt::{BufferAddress, IndexFormat, InputStepMode}; #[derive(Debug)] -#[cfg_attr(feature = "trace", derive(serde::Serialize))] -#[cfg_attr(feature = "replay", derive(serde::Deserialize))] pub enum ShaderModuleSource<'a> { SpirV(Cow<'a, [u32]>), Wgsl(Cow<'a, str>), - // Unable to serialize with `naga::Module` in here: - // requires naga serialization feature. - //Naga(naga::Module), + Naga(naga::Module), } #[derive(Debug)] -#[cfg_attr(feature = "trace", derive(serde::Serialize))] -#[cfg_attr(feature = "replay", derive(serde::Deserialize))] pub struct ShaderModuleDescriptor<'a> { pub label: Label<'a>, - pub source: ShaderModuleSource<'a>, + /// If enabled, `wgpu` will attempt to operate on `Naga` representation + /// of the shader module for both validation and translation into the + /// backend shader languages, where `gfx-hal` supports this. + pub experimental_translation: bool, } #[derive(Debug)] pub struct ShaderModule { pub(crate) raw: B::ShaderModule, pub(crate) device_id: Stored, - pub(crate) module: Option, + pub(crate) interface: Option, #[cfg(debug_assertions)] pub(crate) label: String, } @@ -59,6 +55,8 @@ impl Resource for ShaderModule { #[derive(Clone, Debug, Error)] pub enum CreateShaderModuleError { + #[error("Failed to parse WGSL")] + Parsing, #[error(transparent)] Device(#[from] DeviceError), #[error(transparent)] @@ -113,7 +111,7 @@ pub enum CreateComputePipelineError { #[error("unable to derive an implicit layout")] Implicit(#[from] ImplicitLayoutError), #[error(transparent)] - Stage(StageError), + Stage(validation::StageError), } #[derive(Debug)] @@ -220,7 +218,7 @@ pub enum CreateRenderPipelineError { Stage { flag: wgt::ShaderStage, #[source] - error: StageError, + error: validation::StageError, }, } diff --git a/wgpu-core/src/swap_chain.rs b/wgpu-core/src/swap_chain.rs index 22c65495b..b6c7fa749 100644 --- a/wgpu-core/src/swap_chain.rs +++ b/wgpu-core/src/swap_chain.rs @@ -160,9 +160,8 @@ impl Global { None, match err { hal::window::AcquireError::OutOfMemory(_) => Err(DeviceError::OutOfMemory)?, - hal::window::AcquireError::NotReady => unreachable!(), // we always set a timeout - hal::window::AcquireError::Timeout => SwapChainStatus::Timeout, - hal::window::AcquireError::OutOfDate => SwapChainStatus::Outdated, + hal::window::AcquireError::NotReady { .. } => SwapChainStatus::Timeout, + hal::window::AcquireError::OutOfDate(_) => SwapChainStatus::Outdated, hal::window::AcquireError::SurfaceLost(_) => SwapChainStatus::Lost, hal::window::AcquireError::DeviceLost(_) => Err(DeviceError::Lost)?, }, @@ -283,7 +282,7 @@ impl Global { hal::window::PresentError::OutOfMemory(_) => { Err(SwapChainError::Device(DeviceError::OutOfMemory)) } - hal::window::PresentError::OutOfDate => Ok(SwapChainStatus::Outdated), + hal::window::PresentError::OutOfDate(_) => Ok(SwapChainStatus::Outdated), hal::window::PresentError::SurfaceLost(_) => Ok(SwapChainStatus::Lost), hal::window::PresentError::DeviceLost(_) => { Err(SwapChainError::Device(DeviceError::Lost)) diff --git a/wgpu-core/src/validation.rs b/wgpu-core/src/validation.rs index 6cfe12d53..b2c5e82ec 100644 --- a/wgpu-core/src/validation.rs +++ b/wgpu-core/src/validation.rs @@ -2,12 +2,74 @@ * 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::{binding_model::BindEntryMap, FastHashMap, MAX_BIND_GROUPS}; -use arrayvec::ArrayVec; +use crate::{binding_model::BindEntryMap, FastHashMap}; use std::collections::hash_map::Entry; use thiserror::Error; use wgt::{BindGroupLayoutEntry, BindingType}; +#[derive(Debug)] +enum ResourceType { + Buffer { + size: wgt::BufferSize, + }, + Texture { + dim: naga::ImageDimension, + arrayed: bool, + class: naga::ImageClass, + }, + Sampler { + comparison: bool, + }, +} + +#[derive(Debug)] +struct Resource { + group: u32, + binding: u32, + ty: ResourceType, + class: naga::StorageClass, +} + +#[derive(Clone, Copy, Debug)] +enum NumericDimension { + Scalar, + Vector(naga::VectorSize), + Matrix(naga::VectorSize, naga::VectorSize), +} + +#[derive(Clone, Copy, Debug)] +pub struct NumericType { + dim: NumericDimension, + kind: naga::ScalarKind, + width: naga::Bytes, +} + +#[derive(Debug)] +enum Varying { + Local { location: u32, ty: NumericType }, + BuiltIn(naga::BuiltIn), +} + +#[derive(Debug)] +struct SpecializationConstant { + id: u32, + ty: NumericType, +} + +#[derive(Debug, Default)] +struct EntryPoint { + inputs: Vec, + outputs: Vec, + resources: Vec<(naga::Handle, naga::GlobalUse)>, + spec_constants: Vec, +} + +#[derive(Debug)] +pub struct Interface { + resources: naga::Arena, + entry_points: FastHashMap<(naga::ShaderStage, String), EntryPoint>, +} + #[derive(Clone, Debug, Error)] #[error("buffer usage is {actual:?} which does not contain required usage {expected:?}")] pub struct MissingBufferUsageError { @@ -59,7 +121,7 @@ pub enum BindingError { #[error("type on the shader side does not match the pipeline binding")] WrongType, #[error("buffer structure size {0}, added to one element of an unbound array, if it's the last field, ended up greater than the given `min_binding_size`")] - WrongBufferSize(wgt::BufferAddress), + WrongBufferSize(wgt::BufferSize), #[error("view dimension {dim:?} (is array: {is_array}) doesn't match the shader")] WrongTextureViewDimension { dim: naga::ImageDimension, @@ -232,723 +294,527 @@ fn map_storage_format_from_naga(format: naga::StorageFormat) -> wgt::TextureForm } } -fn check_binding_use( - module: &naga::Module, - var: &naga::GlobalVariable, - entry: &BindGroupLayoutEntry, -) -> Result { - match module.types[var.ty].inner { - naga::TypeInner::Struct { ref members } => { - let (allowed_usage, min_size) = match entry.ty { - BindingType::Buffer { - ty, - has_dynamic_offset: _, - min_binding_size, +impl Resource { + fn check_binding_use( + &self, + entry: &BindGroupLayoutEntry, + shader_usage: naga::GlobalUse, + ) -> Result<(), BindingError> { + let allowed_usage = match self.ty { + ResourceType::Buffer { size } => { + let (allowed_usage, min_size) = match entry.ty { + BindingType::Buffer { + ty, + has_dynamic_offset: _, + min_binding_size, + } => { + let global_use = match ty { + wgt::BufferBindingType::Uniform + | wgt::BufferBindingType::Storage { read_only: true } => { + naga::GlobalUse::LOAD + } + wgt::BufferBindingType::Storage { read_only: _ } => { + naga::GlobalUse::all() + } + }; + (global_use, min_binding_size) + } + _ => return Err(BindingError::WrongType), + }; + match min_size { + Some(non_zero) if non_zero < size => { + return Err(BindingError::WrongBufferSize(size)) + } + _ => (), + } + allowed_usage + } + ResourceType::Sampler { comparison } => match entry.ty { + BindingType::Sampler { + filtering: _, + comparison: cmp, } => { - let global_use = match ty { - wgt::BufferBindingType::Uniform - | wgt::BufferBindingType::Storage { read_only: true } => { - naga::GlobalUse::LOAD - } - wgt::BufferBindingType::Storage { read_only: _ } => naga::GlobalUse::all(), - }; - (global_use, min_binding_size) + if cmp == comparison { + naga::GlobalUse::LOAD + } else { + return Err(BindingError::WrongSamplerComparison); + } } _ => return Err(BindingError::WrongType), - }; - let mut actual_size = 0; - for (i, member) in members.iter().enumerate() { - actual_size += get_aligned_type_size(module, member.ty, i + 1 == members.len()); - } - match min_size { - Some(non_zero) if non_zero.get() < actual_size => { - return Err(BindingError::WrongBufferSize(actual_size)) - } - _ => (), - } - Ok(allowed_usage) - } - naga::TypeInner::Sampler { comparison } => match entry.ty { - BindingType::Sampler { - filtering: _, - comparison: cmp, + }, + ResourceType::Texture { + dim, + arrayed, + class, } => { - if cmp == comparison { - Ok(naga::GlobalUse::LOAD) - } else { - Err(BindingError::WrongSamplerComparison) - } - } - _ => Err(BindingError::WrongType), - }, - naga::TypeInner::Image { - dim, - arrayed, - class, - } => { - let view_dimension = match entry.ty { - BindingType::Texture { view_dimension, .. } - | BindingType::StorageTexture { view_dimension, .. } => view_dimension, - _ => { - return Err(BindingError::WrongTextureViewDimension { - dim, - is_array: true, - }) - } - }; - if arrayed { - match (dim, view_dimension) { - (naga::ImageDimension::D2, wgt::TextureViewDimension::D2Array) => (), - (naga::ImageDimension::Cube, wgt::TextureViewDimension::CubeArray) => (), + let view_dimension = match entry.ty { + BindingType::Texture { view_dimension, .. } + | BindingType::StorageTexture { view_dimension, .. } => view_dimension, _ => { return Err(BindingError::WrongTextureViewDimension { dim, is_array: true, }) } - } - } else { - match (dim, view_dimension) { - (naga::ImageDimension::D1, wgt::TextureViewDimension::D1) => (), - (naga::ImageDimension::D2, wgt::TextureViewDimension::D2) => (), - (naga::ImageDimension::D3, wgt::TextureViewDimension::D3) => (), - (naga::ImageDimension::Cube, wgt::TextureViewDimension::Cube) => (), - _ => { - return Err(BindingError::WrongTextureViewDimension { - dim, - is_array: false, - }) + }; + if arrayed { + match (dim, view_dimension) { + (naga::ImageDimension::D2, wgt::TextureViewDimension::D2Array) => (), + (naga::ImageDimension::Cube, wgt::TextureViewDimension::CubeArray) => (), + _ => { + return Err(BindingError::WrongTextureViewDimension { + dim, + is_array: true, + }) + } + } + } else { + match (dim, view_dimension) { + (naga::ImageDimension::D1, wgt::TextureViewDimension::D1) => (), + (naga::ImageDimension::D2, wgt::TextureViewDimension::D2) => (), + (naga::ImageDimension::D3, wgt::TextureViewDimension::D3) => (), + (naga::ImageDimension::Cube, wgt::TextureViewDimension::Cube) => (), + _ => { + return Err(BindingError::WrongTextureViewDimension { + dim, + is_array: false, + }) + } } } - } - let (expected_class, usage) = match entry.ty { - BindingType::Texture { - sample_type, - view_dimension: _, - multisampled: multi, - } => { - let class = match sample_type { - wgt::TextureSampleType::Float { .. } => naga::ImageClass::Sampled { - kind: naga::ScalarKind::Float, - multi, - }, - wgt::TextureSampleType::Sint => naga::ImageClass::Sampled { - kind: naga::ScalarKind::Sint, - multi, - }, - wgt::TextureSampleType::Uint => naga::ImageClass::Sampled { - kind: naga::ScalarKind::Uint, - multi, - }, - wgt::TextureSampleType::Depth => naga::ImageClass::Depth, - }; - (class, naga::GlobalUse::LOAD) + let (expected_class, usage) = match entry.ty { + BindingType::Texture { + sample_type, + view_dimension: _, + multisampled: multi, + } => { + let class = match sample_type { + wgt::TextureSampleType::Float { .. } => naga::ImageClass::Sampled { + kind: naga::ScalarKind::Float, + multi, + }, + wgt::TextureSampleType::Sint => naga::ImageClass::Sampled { + kind: naga::ScalarKind::Sint, + multi, + }, + wgt::TextureSampleType::Uint => naga::ImageClass::Sampled { + kind: naga::ScalarKind::Uint, + multi, + }, + wgt::TextureSampleType::Depth => naga::ImageClass::Depth, + }; + (class, naga::GlobalUse::LOAD) + } + BindingType::StorageTexture { + access, + format, + view_dimension: _, + } => { + let naga_format = map_storage_format_to_naga(format) + .ok_or(BindingError::BadStorageFormat(format))?; + let usage = match access { + wgt::StorageTextureAccess::ReadOnly => naga::GlobalUse::LOAD, + wgt::StorageTextureAccess::WriteOnly => naga::GlobalUse::STORE, + }; + (naga::ImageClass::Storage(naga_format), usage) + } + _ => return Err(BindingError::WrongType), + }; + if class != expected_class { + return Err(BindingError::WrongTextureClass { + binding: expected_class, + shader: class, + }); } - BindingType::StorageTexture { - access, - format, - view_dimension: _, - } => { - let naga_format = map_storage_format_to_naga(format) - .ok_or(BindingError::BadStorageFormat(format))?; - let usage = match access { - wgt::StorageTextureAccess::ReadOnly => naga::GlobalUse::LOAD, - wgt::StorageTextureAccess::WriteOnly => naga::GlobalUse::STORE, - }; - (naga::ImageClass::Storage(naga_format), usage) - } - _ => return Err(BindingError::WrongType), - }; - if class != expected_class { - return Err(BindingError::WrongTextureClass { - binding: expected_class, - shader: class, - }); + usage } - Ok(usage) - } - _ => Err(BindingError::WrongType), - } -} + }; -fn is_sub_type(sub: &naga::TypeInner, provided: &naga::TypeInner) -> bool { - use naga::TypeInner as Ti; - - match (sub, provided) { - ( - &Ti::Scalar { - kind: k0, - width: w0, - }, - &Ti::Scalar { - kind: k1, - width: w1, - }, - ) => k0 == k1 && w0 <= w1, - ( - &Ti::Scalar { - kind: k0, - width: w0, - }, - &Ti::Vector { - size: _, - kind: k1, - width: w1, - }, - ) => k0 == k1 && w0 <= w1, - ( - &Ti::Vector { - size: s0, - kind: k0, - width: w0, - }, - &Ti::Vector { - size: s1, - kind: k1, - width: w1, - }, - ) => s0 as u8 <= s1 as u8 && k0 == k1 && w0 <= w1, - ( - &Ti::Matrix { - columns: c0, - rows: r0, - width: w0, - }, - &Ti::Matrix { - columns: c1, - rows: r1, - width: w1, - }, - ) => c0 == c1 && r0 == r1 && w0 <= w1, - (&Ti::Struct { members: ref m0 }, &Ti::Struct { members: ref m1 }) => m0 == m1, - _ => false, - } -} - -pub enum MaybeOwned<'a, T> { - Owned(T), - Borrowed(&'a T), -} - -impl<'a, T> std::ops::Deref for MaybeOwned<'a, T> { - type Target = T; - fn deref(&self) -> &T { - match *self { - MaybeOwned::Owned(ref value) => value, - MaybeOwned::Borrowed(value) => value, + if allowed_usage.contains(shader_usage) { + Ok(()) + } else { + Err(BindingError::WrongUsage(shader_usage)) } } -} -pub fn map_vertex_format(format: wgt::VertexFormat) -> naga::TypeInner { - use naga::TypeInner as Ti; - use wgt::VertexFormat as Vf; - - //Note: Shader always sees data as int, uint, or float. - // It doesn't know if the original is normalized in a tighter form. - let width = 4; - match format { - Vf::Uchar2 => Ti::Vector { - size: naga::VectorSize::Bi, - kind: naga::ScalarKind::Uint, - width, - }, - Vf::Uchar4 => Ti::Vector { - size: naga::VectorSize::Quad, - kind: naga::ScalarKind::Uint, - width, - }, - Vf::Char2 => Ti::Vector { - size: naga::VectorSize::Bi, - kind: naga::ScalarKind::Sint, - width, - }, - Vf::Char4 => Ti::Vector { - size: naga::VectorSize::Quad, - kind: naga::ScalarKind::Sint, - width, - }, - Vf::Uchar2Norm => Ti::Vector { - size: naga::VectorSize::Bi, - kind: naga::ScalarKind::Float, - width, - }, - Vf::Uchar4Norm => Ti::Vector { - size: naga::VectorSize::Quad, - kind: naga::ScalarKind::Float, - width, - }, - Vf::Char2Norm => Ti::Vector { - size: naga::VectorSize::Bi, - kind: naga::ScalarKind::Float, - width, - }, - Vf::Char4Norm => Ti::Vector { - size: naga::VectorSize::Quad, - kind: naga::ScalarKind::Float, - width, - }, - Vf::Ushort2 => Ti::Vector { - size: naga::VectorSize::Bi, - kind: naga::ScalarKind::Uint, - width, - }, - Vf::Ushort4 => Ti::Vector { - size: naga::VectorSize::Quad, - kind: naga::ScalarKind::Uint, - width, - }, - Vf::Short2 => Ti::Vector { - size: naga::VectorSize::Bi, - kind: naga::ScalarKind::Sint, - width, - }, - Vf::Short4 => Ti::Vector { - size: naga::VectorSize::Quad, - kind: naga::ScalarKind::Sint, - width, - }, - Vf::Ushort2Norm | Vf::Short2Norm | Vf::Half2 => Ti::Vector { - size: naga::VectorSize::Bi, - kind: naga::ScalarKind::Float, - width, - }, - Vf::Ushort4Norm | Vf::Short4Norm | Vf::Half4 => Ti::Vector { - size: naga::VectorSize::Quad, - kind: naga::ScalarKind::Float, - width, - }, - Vf::Float => Ti::Scalar { - kind: naga::ScalarKind::Float, - width, - }, - Vf::Float2 => Ti::Vector { - size: naga::VectorSize::Bi, - kind: naga::ScalarKind::Float, - width, - }, - Vf::Float3 => Ti::Vector { - size: naga::VectorSize::Tri, - kind: naga::ScalarKind::Float, - width, - }, - Vf::Float4 => Ti::Vector { - size: naga::VectorSize::Quad, - kind: naga::ScalarKind::Float, - width, - }, - Vf::Uint => Ti::Scalar { - kind: naga::ScalarKind::Uint, - width, - }, - Vf::Uint2 => Ti::Vector { - size: naga::VectorSize::Bi, - kind: naga::ScalarKind::Uint, - width, - }, - Vf::Uint3 => Ti::Vector { - size: naga::VectorSize::Tri, - kind: naga::ScalarKind::Uint, - width, - }, - Vf::Uint4 => Ti::Vector { - size: naga::VectorSize::Quad, - kind: naga::ScalarKind::Uint, - width, - }, - Vf::Int => Ti::Scalar { - kind: naga::ScalarKind::Sint, - width, - }, - Vf::Int2 => Ti::Vector { - size: naga::VectorSize::Bi, - kind: naga::ScalarKind::Sint, - width, - }, - Vf::Int3 => Ti::Vector { - size: naga::VectorSize::Tri, - kind: naga::ScalarKind::Sint, - width, - }, - Vf::Int4 => Ti::Vector { - size: naga::VectorSize::Quad, - kind: naga::ScalarKind::Sint, - width, - }, + fn derive_binding_type( + &self, + shader_usage: naga::GlobalUse, + ) -> Result { + Ok(match self.ty { + ResourceType::Buffer { size } => BindingType::Buffer { + ty: match self.class { + naga::StorageClass::Uniform => wgt::BufferBindingType::Uniform, + naga::StorageClass::Storage => wgt::BufferBindingType::Storage { + read_only: !shader_usage.contains(naga::GlobalUse::STORE), + }, + _ => return Err(BindingError::WrongType), + }, + has_dynamic_offset: false, + min_binding_size: Some(size), + }, + ResourceType::Sampler { comparison } => BindingType::Sampler { + filtering: true, + comparison, + }, + ResourceType::Texture { + dim, + arrayed, + class, + } => { + let view_dimension = match dim { + naga::ImageDimension::D1 => wgt::TextureViewDimension::D1, + naga::ImageDimension::D2 if arrayed => wgt::TextureViewDimension::D2Array, + naga::ImageDimension::D2 => wgt::TextureViewDimension::D2, + naga::ImageDimension::D3 => wgt::TextureViewDimension::D3, + naga::ImageDimension::Cube if arrayed => wgt::TextureViewDimension::CubeArray, + naga::ImageDimension::Cube => wgt::TextureViewDimension::Cube, + }; + match class { + naga::ImageClass::Sampled { multi, kind } => BindingType::Texture { + sample_type: match kind { + naga::ScalarKind::Float => { + wgt::TextureSampleType::Float { filterable: true } + } + naga::ScalarKind::Sint => wgt::TextureSampleType::Sint, + naga::ScalarKind::Uint => wgt::TextureSampleType::Uint, + naga::ScalarKind::Bool => unreachable!(), + }, + view_dimension, + multisampled: multi, + }, + naga::ImageClass::Depth => BindingType::Texture { + sample_type: wgt::TextureSampleType::Depth, + view_dimension, + multisampled: false, + }, + naga::ImageClass::Storage(format) => BindingType::StorageTexture { + access: if shader_usage.contains(naga::GlobalUse::STORE) { + wgt::StorageTextureAccess::WriteOnly + } else { + wgt::StorageTextureAccess::ReadOnly + }, + view_dimension, + format: { + let f = map_storage_format_from_naga(format); + let original = map_storage_format_to_naga(f) + .ok_or(BindingError::BadStorageFormat(f))?; + debug_assert_eq!(format, original); + f + }, + }, + } + } + }) } } -fn map_texture_format(format: wgt::TextureFormat) -> naga::TypeInner { - use naga::{ScalarKind as Sk, TypeInner as Ti, VectorSize as Vs}; - use wgt::TextureFormat as Tf; +impl NumericType { + pub fn from_vertex_format(format: wgt::VertexFormat) -> Self { + use naga::{ScalarKind as Sk, VectorSize as Vs}; + use wgt::VertexFormat as Vf; - //Note: Shader always sees data as int, uint, or float. - // It doesn't know if the original is normalized in a tighter form. - let width = 4; - match format { - Tf::R8Unorm | Tf::R8Snorm => Ti::Scalar { - kind: Sk::Float, - width, - }, - Tf::R8Uint => Ti::Scalar { - kind: Sk::Uint, - width, - }, - Tf::R8Sint => Ti::Scalar { - kind: Sk::Sint, - width, - }, - Tf::R16Uint => Ti::Scalar { - kind: Sk::Uint, - width, - }, - Tf::R16Sint => Ti::Scalar { - kind: Sk::Sint, - width, - }, - Tf::R16Float => Ti::Scalar { - kind: Sk::Float, - width, - }, - Tf::Rg8Unorm | Tf::Rg8Snorm => Ti::Vector { - size: Vs::Bi, - kind: Sk::Float, - width, - }, - Tf::Rg8Uint => Ti::Vector { - size: Vs::Bi, - kind: Sk::Uint, - width, - }, - Tf::Rg8Sint => Ti::Vector { - size: Vs::Bi, - kind: Sk::Sint, - width, - }, - Tf::R32Uint => Ti::Scalar { - kind: Sk::Uint, - width, - }, - Tf::R32Sint => Ti::Scalar { - kind: Sk::Sint, - width, - }, - Tf::R32Float => Ti::Scalar { - kind: Sk::Float, - width, - }, - Tf::Rg16Uint => Ti::Vector { - size: Vs::Bi, - kind: Sk::Uint, - width, - }, - Tf::Rg16Sint => Ti::Vector { - size: Vs::Bi, - kind: Sk::Sint, - width, - }, - Tf::Rg16Float => Ti::Vector { - size: Vs::Bi, - kind: Sk::Float, - width, - }, - Tf::Rgba8Unorm - | Tf::Rgba8UnormSrgb - | Tf::Rgba8Snorm - | Tf::Bgra8Unorm - | Tf::Bgra8UnormSrgb => Ti::Vector { - size: Vs::Quad, - kind: Sk::Float, - width, - }, - Tf::Rgba8Uint => Ti::Vector { - size: Vs::Quad, - kind: Sk::Uint, - width, - }, - Tf::Rgba8Sint => Ti::Vector { - size: Vs::Quad, - kind: Sk::Sint, - width, - }, - Tf::Rgb10a2Unorm => Ti::Vector { - size: Vs::Quad, - kind: Sk::Float, - width, - }, - Tf::Rg11b10Float => Ti::Vector { - size: Vs::Tri, - kind: Sk::Float, - width, - }, - Tf::Rg32Uint => Ti::Vector { - size: Vs::Bi, - kind: Sk::Uint, - width, - }, - Tf::Rg32Sint => Ti::Vector { - size: Vs::Bi, - kind: Sk::Sint, - width, - }, - Tf::Rg32Float => Ti::Vector { - size: Vs::Bi, - kind: Sk::Float, - width, - }, - Tf::Rgba16Uint => Ti::Vector { - size: Vs::Quad, - kind: Sk::Uint, - width, - }, - Tf::Rgba16Sint => Ti::Vector { - size: Vs::Quad, - kind: Sk::Sint, - width, - }, - Tf::Rgba16Float => Ti::Vector { - size: Vs::Quad, - kind: Sk::Float, - width, - }, - Tf::Rgba32Uint => Ti::Vector { - size: Vs::Quad, - kind: Sk::Uint, - width, - }, - Tf::Rgba32Sint => Ti::Vector { - size: Vs::Quad, - kind: Sk::Sint, - width, - }, - Tf::Rgba32Float => Ti::Vector { - size: Vs::Quad, - kind: Sk::Float, - width, - }, - Tf::Depth32Float | Tf::Depth24Plus | Tf::Depth24PlusStencil8 => { - panic!("Unexpected depth format") + let (dim, kind) = match format { + Vf::Uchar2 | Vf::Ushort2 => (NumericDimension::Vector(Vs::Bi), Sk::Uint), + Vf::Uchar4 | Vf::Ushort4 => (NumericDimension::Vector(Vs::Quad), Sk::Uint), + Vf::Char2 | Vf::Short2 => (NumericDimension::Vector(Vs::Bi), Sk::Sint), + Vf::Char4 | Vf::Short4 => (NumericDimension::Vector(Vs::Quad), Sk::Sint), + Vf::Uchar2Norm | Vf::Char2Norm | Vf::Ushort2Norm | Vf::Short2Norm | Vf::Half2 => { + (NumericDimension::Vector(Vs::Bi), Sk::Float) + } + Vf::Uchar4Norm | Vf::Char4Norm | Vf::Ushort4Norm | Vf::Short4Norm | Vf::Half4 => { + (NumericDimension::Vector(Vs::Quad), Sk::Float) + } + Vf::Float => (NumericDimension::Scalar, Sk::Float), + Vf::Float2 => (NumericDimension::Vector(Vs::Bi), Sk::Float), + Vf::Float3 => (NumericDimension::Vector(Vs::Tri), Sk::Float), + Vf::Float4 => (NumericDimension::Vector(Vs::Quad), Sk::Float), + Vf::Uint => (NumericDimension::Scalar, Sk::Uint), + Vf::Uint2 => (NumericDimension::Vector(Vs::Bi), Sk::Uint), + Vf::Uint3 => (NumericDimension::Vector(Vs::Tri), Sk::Uint), + Vf::Uint4 => (NumericDimension::Vector(Vs::Quad), Sk::Uint), + Vf::Int => (NumericDimension::Scalar, Sk::Sint), + Vf::Int2 => (NumericDimension::Vector(Vs::Bi), Sk::Sint), + Vf::Int3 => (NumericDimension::Vector(Vs::Tri), Sk::Sint), + Vf::Int4 => (NumericDimension::Vector(Vs::Quad), Sk::Sint), + }; + + NumericType { + dim, + kind, + //Note: Shader always sees data as int, uint, or float. + // It doesn't know if the original is normalized in a tighter form. + width: 4, + } + } + + fn from_texture_format(format: wgt::TextureFormat) -> Self { + use naga::{ScalarKind as Sk, VectorSize as Vs}; + use wgt::TextureFormat as Tf; + + let (dim, kind) = match format { + Tf::R8Unorm | Tf::R8Snorm | Tf::R16Float | Tf::R32Float => { + (NumericDimension::Scalar, Sk::Float) + } + Tf::R8Uint | Tf::R16Uint | Tf::R32Uint => (NumericDimension::Scalar, Sk::Uint), + Tf::R8Sint | Tf::R16Sint | Tf::R32Sint => (NumericDimension::Scalar, Sk::Sint), + Tf::Rg8Unorm | Tf::Rg8Snorm | Tf::Rg16Float | Tf::Rg32Float => { + (NumericDimension::Vector(Vs::Bi), Sk::Float) + } + Tf::Rg8Uint | Tf::Rg16Uint | Tf::Rg32Uint => { + (NumericDimension::Vector(Vs::Bi), Sk::Uint) + } + Tf::Rg8Sint | Tf::Rg16Sint | Tf::Rg32Sint => { + (NumericDimension::Vector(Vs::Bi), Sk::Sint) + } + Tf::Rgba8Unorm + | Tf::Rgba8UnormSrgb + | Tf::Rgba8Snorm + | Tf::Bgra8Unorm + | Tf::Bgra8UnormSrgb + | Tf::Rgb10a2Unorm + | Tf::Rgba16Float + | Tf::Rgba32Float => (NumericDimension::Vector(Vs::Quad), Sk::Float), + Tf::Rgba8Uint | Tf::Rgba16Uint | Tf::Rgba32Uint => { + (NumericDimension::Vector(Vs::Quad), Sk::Uint) + } + Tf::Rgba8Sint | Tf::Rgba16Sint | Tf::Rgba32Sint => { + (NumericDimension::Vector(Vs::Quad), Sk::Sint) + } + Tf::Rg11b10Float => (NumericDimension::Vector(Vs::Tri), Sk::Float), + Tf::Depth32Float | Tf::Depth24Plus | Tf::Depth24PlusStencil8 => { + panic!("Unexpected depth format") + } + Tf::Bc1RgbaUnorm + | Tf::Bc1RgbaUnormSrgb + | Tf::Bc2RgbaUnorm + | Tf::Bc2RgbaUnormSrgb + | Tf::Bc3RgbaUnorm + | Tf::Bc3RgbaUnormSrgb + | Tf::Bc7RgbaUnorm + | Tf::Bc7RgbaUnormSrgb => (NumericDimension::Vector(Vs::Quad), Sk::Float), + Tf::Bc4RUnorm | Tf::Bc4RSnorm => (NumericDimension::Scalar, Sk::Float), + Tf::Bc5RgUnorm | Tf::Bc5RgSnorm => (NumericDimension::Vector(Vs::Bi), Sk::Float), + Tf::Bc6hRgbUfloat | Tf::Bc6hRgbSfloat => (NumericDimension::Vector(Vs::Tri), Sk::Float), + }; + + NumericType { + dim, + kind, + //Note: Shader always sees data as int, uint, or float. + // It doesn't know if the original is normalized in a tighter form. + width: 4, + } + } + + fn is_subtype_of(&self, other: &NumericType) -> bool { + if self.width > other.width { + return false; + } + if self.kind != other.kind { + return false; + } + match (self.dim, other.dim) { + (NumericDimension::Scalar, NumericDimension::Scalar) => true, + (NumericDimension::Scalar, NumericDimension::Vector(_)) => true, + (NumericDimension::Vector(s0), NumericDimension::Vector(s1)) => s0 <= s1, + (NumericDimension::Matrix(c0, r0), NumericDimension::Matrix(c1, r1)) => { + c0 == c1 && r0 == r1 + } + _ => false, } - Tf::Bc1RgbaUnorm - | Tf::Bc1RgbaUnormSrgb - | Tf::Bc2RgbaUnorm - | Tf::Bc2RgbaUnormSrgb - | Tf::Bc3RgbaUnorm - | Tf::Bc3RgbaUnormSrgb - | Tf::Bc7RgbaUnorm - | Tf::Bc7RgbaUnormSrgb => Ti::Vector { - size: Vs::Quad, - kind: Sk::Float, - width, - }, - Tf::Bc4RUnorm | Tf::Bc4RSnorm => Ti::Scalar { - kind: Sk::Float, - width, - }, - Tf::Bc5RgUnorm | Tf::Bc5RgSnorm => Ti::Vector { - size: Vs::Bi, - kind: Sk::Float, - width, - }, - Tf::Bc6hRgbUfloat | Tf::Bc6hRgbSfloat => Ti::Vector { - size: Vs::Tri, - kind: Sk::Float, - width, - }, } } /// Return true if the fragment `format` is covered by the provided `output`. -pub fn check_texture_format(format: wgt::TextureFormat, output: &naga::TypeInner) -> bool { - let required = map_texture_format(format); - is_sub_type(&required, output) +pub fn check_texture_format(format: wgt::TextureFormat, output: &NumericType) -> bool { + NumericType::from_texture_format(format).is_subtype_of(output) } -pub type StageInterface<'a> = FastHashMap>; +pub type StageIo = FastHashMap; -pub enum IntrospectionBindGroupLayouts<'a> { - Given(ArrayVec<[&'a BindEntryMap; MAX_BIND_GROUPS]>), - Derived(&'a mut [BindEntryMap]), -} - -fn derive_binding_type( - module: &naga::Module, - var: &naga::GlobalVariable, - usage: naga::GlobalUse, -) -> Result { - let ty = &module.types[var.ty]; - Ok(match ty.inner { - naga::TypeInner::Struct { ref members } => { - let has_dynamic_offset = false; - let mut actual_size = 0; - for (i, member) in members.iter().enumerate() { - actual_size += get_aligned_type_size(module, member.ty, i + 1 == members.len()); - } - match var.class { - naga::StorageClass::Uniform => BindingType::Buffer { - ty: wgt::BufferBindingType::Uniform, - has_dynamic_offset, - min_binding_size: wgt::BufferSize::new(actual_size), - }, - naga::StorageClass::Storage => BindingType::Buffer { - ty: wgt::BufferBindingType::Storage { - read_only: !usage.contains(naga::GlobalUse::STORE), - }, - has_dynamic_offset, - min_binding_size: wgt::BufferSize::new(actual_size), - }, - _ => return Err(BindingError::WrongType), - } - } - naga::TypeInner::Sampler { comparison } => BindingType::Sampler { - filtering: true, - comparison, - }, - naga::TypeInner::Image { - dim, - arrayed, - class, - } => { - let view_dimension = match dim { - naga::ImageDimension::D1 => wgt::TextureViewDimension::D1, - naga::ImageDimension::D2 if arrayed => wgt::TextureViewDimension::D2Array, - naga::ImageDimension::D2 => wgt::TextureViewDimension::D2, - naga::ImageDimension::D3 => wgt::TextureViewDimension::D3, - naga::ImageDimension::Cube if arrayed => wgt::TextureViewDimension::CubeArray, - naga::ImageDimension::Cube => wgt::TextureViewDimension::Cube, +impl Interface { + pub fn new(module: &naga::Module) -> Self { + let mut resources = naga::Arena::new(); + let mut resource_mapping = FastHashMap::default(); + for (var_handle, var) in module.global_variables.iter() { + let (group, binding) = match var.binding { + Some(naga::Binding::Resource { group, binding }) => (group, binding), + _ => continue, }; - match class { - naga::ImageClass::Sampled { multi, kind } => BindingType::Texture { - sample_type: match kind { - naga::ScalarKind::Float => { - wgt::TextureSampleType::Float { filterable: true } - } - naga::ScalarKind::Sint => wgt::TextureSampleType::Sint, - naga::ScalarKind::Uint => wgt::TextureSampleType::Uint, - naga::ScalarKind::Bool => unreachable!(), - }, - view_dimension, - multisampled: multi, + let ty = match module.types[var.ty].inner { + naga::TypeInner::Struct { ref members } => { + let mut actual_size = 0; + for (i, member) in members.iter().enumerate() { + actual_size += + get_aligned_type_size(module, member.ty, i + 1 == members.len()); + } + ResourceType::Buffer { + size: wgt::BufferSize::new(actual_size).unwrap(), + } + } + naga::TypeInner::Image { + dim, + arrayed, + class, + } => ResourceType::Texture { + dim, + arrayed, + class, }, - naga::ImageClass::Depth => BindingType::Texture { - sample_type: wgt::TextureSampleType::Depth, - view_dimension, - multisampled: false, - }, - naga::ImageClass::Storage(format) => BindingType::StorageTexture { - access: if usage.contains(naga::GlobalUse::STORE) { - wgt::StorageTextureAccess::WriteOnly - } else { - wgt::StorageTextureAccess::ReadOnly - }, - view_dimension, - format: { - let f = map_storage_format_from_naga(format); - let original = map_storage_format_to_naga(f) - .ok_or(BindingError::BadStorageFormat(f))?; - debug_assert_eq!(format, original); - f - }, - }, - } + naga::TypeInner::Sampler { comparison } => ResourceType::Sampler { comparison }, + ref other => panic!("Unexpected resource type: {:?}", other), + }; + let handle = resources.append(Resource { + group, + binding, + ty, + class: var.class, + }); + resource_mapping.insert(var_handle, handle); } - _ => return Err(BindingError::WrongType), - }) -} -pub fn check_stage<'a>( - module: &'a naga::Module, - mut group_layouts: IntrospectionBindGroupLayouts, - entry_point_name: &str, - stage_bit: wgt::ShaderStage, - inputs: StageInterface<'a>, -) -> Result, StageError> { - // Since a shader module can have multiple entry points with the same name, - // we need to look for one with the right execution model. - let shader_stage = match stage_bit { - wgt::ShaderStage::VERTEX => naga::ShaderStage::Vertex, - wgt::ShaderStage::FRAGMENT => naga::ShaderStage::Fragment, - wgt::ShaderStage::COMPUTE => naga::ShaderStage::Compute, - _ => unreachable!(), - }; - let entry_point = module - .entry_points - .get(&(shader_stage, entry_point_name.to_string())) - .ok_or(StageError::MissingEntryPoint(stage_bit))?; + let mut entry_points = FastHashMap::default(); + entry_points.reserve(module.entry_points.len()); + for (&(stage, ref ep_name), entry_point) in module.entry_points.iter() { + let mut ep = EntryPoint::default(); + for ((var_handle, var), &usage) in module + .global_variables + .iter() + .zip(&entry_point.function.global_usage) + { + if usage.is_empty() { + continue; + } - let mut outputs = StageInterface::default(); - for ((_, var), &usage) in module - .global_variables - .iter() - .zip(&entry_point.function.global_usage) - { - if usage.is_empty() { - continue; - } - match var.binding { - Some(naga::Binding::Resource { group, binding }) => { - let result = match group_layouts { - IntrospectionBindGroupLayouts::Given(ref layouts) => layouts - .get(group as usize) - .and_then(|map| map.get(&binding)) - .ok_or(BindingError::Missing) - .and_then(|entry| { - if entry.visibility.contains(stage_bit) { - Ok(entry) - } else { - Err(BindingError::Invisible) - } - }) - .and_then(|entry| check_binding_use(module, var, entry)) - .and_then(|allowed_usage| { - if allowed_usage.contains(usage) { - Ok(()) - } else { - Err(BindingError::WrongUsage(usage)) - } - }), - IntrospectionBindGroupLayouts::Derived(ref mut layouts) => layouts - .get_mut(group as usize) - .ok_or(BindingError::Missing) - .and_then(|set| { - let ty = derive_binding_type(module, var, usage)?; - Ok(match set.entry(binding) { - Entry::Occupied(e) if e.get().ty != ty => { - return Err(BindingError::InconsistentlyDerivedType) - } - Entry::Occupied(e) => { - e.into_mut().visibility |= stage_bit; - } - Entry::Vacant(e) => { - e.insert(BindGroupLayoutEntry { - binding, - ty, - visibility: stage_bit, - count: None, - }); - } - }) - }), + let varying = match var.binding { + Some(naga::Binding::Resource { .. }) => { + ep.resources.push((resource_mapping[&var_handle], usage)); + None + } + Some(naga::Binding::Location(location)) => { + let ty = match module.types[var.ty].inner { + naga::TypeInner::Scalar { kind, width } => NumericType { + dim: NumericDimension::Scalar, + kind, + width, + }, + naga::TypeInner::Vector { size, kind, width } => NumericType { + dim: NumericDimension::Vector(size), + kind, + width, + }, + naga::TypeInner::Matrix { + columns, + rows, + width, + } => NumericType { + dim: NumericDimension::Matrix(columns, rows), + kind: naga::ScalarKind::Float, + width, + }, + ref other => panic!("Unexpected varying type: {:?}", other), + }; + Some(Varying::Local { location, ty }) + } + Some(naga::Binding::BuiltIn(built_in)) => Some(Varying::BuiltIn(built_in)), + _ => None, }; - if let Err(error) = result { - return Err(StageError::Binding { - group, - binding, - error, - }); + + if let Some(varying) = varying { + match var.class { + naga::StorageClass::Input => ep.inputs.push(varying), + naga::StorageClass::Output => ep.outputs.push(varying), + _ => (), + } } } - Some(naga::Binding::Location(location)) => { - let ty = &module.types[var.ty].inner; - if usage.contains(naga::GlobalUse::STORE) { - outputs.insert(location, MaybeOwned::Borrowed(ty)); - } else { + entry_points.insert((stage, ep_name.clone()), ep); + } + + Interface { + resources, + entry_points, + } + } + + pub fn check_stage( + &self, + given_layouts: Option<&[&BindEntryMap]>, + derived_layouts: &mut [BindEntryMap], + entry_point_name: &str, + stage_bit: wgt::ShaderStage, + inputs: StageIo, + ) -> Result { + // Since a shader module can have multiple entry points with the same name, + // we need to look for one with the right execution model. + let shader_stage = match stage_bit { + wgt::ShaderStage::VERTEX => naga::ShaderStage::Vertex, + wgt::ShaderStage::FRAGMENT => naga::ShaderStage::Fragment, + wgt::ShaderStage::COMPUTE => naga::ShaderStage::Compute, + _ => unreachable!(), + }; + let entry_point = self + .entry_points + .get(&(shader_stage, entry_point_name.to_string())) + .ok_or(StageError::MissingEntryPoint(stage_bit))?; + + for &(handle, usage) in entry_point.resources.iter() { + let res = &self.resources[handle]; + let result = match given_layouts { + Some(layouts) => layouts + .get(res.group as usize) + .and_then(|map| map.get(&res.binding)) + .ok_or(BindingError::Missing) + .and_then(|entry| { + if entry.visibility.contains(stage_bit) { + Ok(entry) + } else { + Err(BindingError::Invisible) + } + }) + .and_then(|entry| res.check_binding_use(entry, usage)), + None => derived_layouts + .get_mut(res.group as usize) + .ok_or(BindingError::Missing) + .and_then(|set| { + let ty = res.derive_binding_type(usage)?; + Ok(match set.entry(res.binding) { + Entry::Occupied(e) if e.get().ty != ty => { + return Err(BindingError::InconsistentlyDerivedType) + } + Entry::Occupied(e) => { + e.into_mut().visibility |= stage_bit; + } + Entry::Vacant(e) => { + e.insert(BindGroupLayoutEntry { + binding: res.binding, + ty, + visibility: stage_bit, + count: None, + }); + } + }) + }), + }; + if let Err(error) = result { + return Err(StageError::Binding { + group: res.group, + binding: res.binding, + error, + }); + } + } + + for input in entry_point.inputs.iter() { + match *input { + Varying::Local { location, ty } => { let result = inputs .get(&location) .ok_or(InputError::Missing) .and_then(|provided| { - if is_sub_type(ty, provided) { + if ty.is_subtype_of(provided) { Ok(()) } else { Err(InputError::WrongType) @@ -958,9 +824,18 @@ pub fn check_stage<'a>( return Err(StageError::Input { location, error }); } } + Varying::BuiltIn(_) => {} } - _ => {} } + + let outputs = entry_point + .outputs + .iter() + .filter_map(|output| match *output { + Varying::Local { location, ty } => Some((location, ty)), + Varying::BuiltIn(_) => None, + }) + .collect(); + Ok(outputs) } - Ok(outputs) }