From e46eda2e4f065dadda55bf5863ec651f976386a5 Mon Sep 17 00:00:00 2001 From: Inner Daemons <85136135+inner-daemons@users.noreply.github.com> Date: Thu, 2 Apr 2026 00:33:42 -0500 Subject: [PATCH] Full `per_vertex` implementation (#9219) * Some stuff worked on * Works on MSL * Ready for test 2 * Fix for a thing lol * Fixed 2 errors * Fixed DXC * Add changelog * Updated CI to hopefully pass on macOS * Various fixes * Some final fixes * CHanged CI * Update naga/src/front/wgsl/parse/directive/enable_extension.rs Co-authored-by: atlv * Thing --------- Co-authored-by: atlv Co-authored-by: Connor Fitzgerald --- .github/workflows/shaders.yml | 2 +- CHANGELOG.md | 1 + naga/src/back/hlsl/conv.rs | 2 +- naga/src/back/hlsl/mod.rs | 2 +- naga/src/back/hlsl/writer.rs | 17 +++++ naga/src/back/msl/mod.rs | 7 +- naga/src/back/msl/writer.rs | 73 +++++++++++++++++-- naga/src/back/wgsl/writer.rs | 11 +++ naga/src/front/wgsl/parse/conv.rs | 11 ++- .../wgsl/parse/directive/enable_extension.rs | 11 +++ naga/src/front/wgsl/parse/mod.rs | 6 +- naga/src/valid/interface.rs | 5 ++ naga/src/valid/mod.rs | 1 + naga/tests/in/wgsl/per-vertex.toml | 8 +- naga/tests/in/wgsl/per-vertex.wgsl | 2 + naga/tests/naga/validation.rs | 10 ++- naga/tests/naga/wgsl_errors.rs | 34 +++++++++ naga/tests/out/hlsl/wgsl-per-vertex.hlsl | 9 +++ naga/tests/out/hlsl/wgsl-per-vertex.ron | 16 ++++ naga/tests/out/msl/wgsl-per-vertex.metal | 22 ++++++ naga/tests/out/wgsl/spv-per-vertex.wgsl | 2 + naga/tests/out/wgsl/wgsl-per-vertex.wgsl | 2 + tests/src/image.rs | 15 +++- tests/tests/wgpu-gpu/per_vertex/mod.rs | 2 +- .../tests/wgpu-gpu/per_vertex/per_vertex.wgsl | 2 + wgpu-core/src/device/resource.rs | 5 ++ wgpu-core/src/validation.rs | 26 ++++++- wgpu-hal/src/dx12/adapter.rs | 2 +- wgpu-hal/src/metal/adapter.rs | 7 +- wgpu-hal/src/metal/device.rs | 3 +- wgpu-hal/src/metal/mod.rs | 1 + 31 files changed, 295 insertions(+), 22 deletions(-) create mode 100644 naga/tests/out/hlsl/wgsl-per-vertex.hlsl create mode 100644 naga/tests/out/hlsl/wgsl-per-vertex.ron create mode 100644 naga/tests/out/msl/wgsl-per-vertex.metal diff --git a/.github/workflows/shaders.yml b/.github/workflows/shaders.yml index 5e58acc91..9aeba9205 100644 --- a/.github/workflows/shaders.yml +++ b/.github/workflows/shaders.yml @@ -67,7 +67,7 @@ jobs: naga-validate-macos: name: "Validate: MSL" - runs-on: macos-15 + runs-on: macos-26 steps: - uses: actions/checkout@v6 diff --git a/CHANGELOG.md b/CHANGELOG.md index 924b96aef..e69c0fb75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,7 @@ Bottom level categories: - BLAS support for procedural AABB geometry (`BlasGeometrySizeDescriptors::AABBs`, `BlasAabbGeometry`, and related descriptors). By @dylanblokhuis in [#9290](https://github.com/gfx-rs/wgpu/pull/9290) - Added "limit bucketing" functionality which can adjust adapter limits and features to match one of several pre-defined buckets. This is controlled by the new `apply_limit_buckets` member in `RequestAdapterOptions`, which is `false` by default. By @andyleiserson in [#9119](https://github.com/gfx-rs/wgpu/pull/9119). - Make `wgpu_types::texture::format::TextureChannel` accessible as `wgpu::TextureChannel`. By @TornaxO7 in [#9394](https://github.com/gfx-rs/wgpu/pull/9349). +- Add support for `per_vertex` in Metal and DX12, as well as some validation for `per_vertex`, and a new enable extension, `wgpu_per_vertex`. By @inner-daemons in [#9219](https://github.com/gfx-rs/wgpu/pull/9219). #### Metal diff --git a/naga/src/back/hlsl/conv.rs b/naga/src/back/hlsl/conv.rs index 46b7ea4fe..4d9ca7c5c 100644 --- a/naga/src/back/hlsl/conv.rs +++ b/naga/src/back/hlsl/conv.rs @@ -222,7 +222,7 @@ impl crate::Interpolation { Self::Perspective => None, Self::Linear => Some("noperspective"), Self::Flat => Some("nointerpolation"), - Self::PerVertex => unreachable!(), + Self::PerVertex => Some("nointerpolation"), } } } diff --git a/naga/src/back/hlsl/mod.rs b/naga/src/back/hlsl/mod.rs index f2c1d6db0..6918ac113 100644 --- a/naga/src/back/hlsl/mod.rs +++ b/naga/src/back/hlsl/mod.rs @@ -821,7 +821,7 @@ pub fn supported_capabilities() -> crate::valid::Capabilities { | Caps::STORAGE_TEXTURE_BINDING_ARRAY_NON_UNIFORM_INDEXING | Caps::STORAGE_BUFFER_BINDING_ARRAY_NON_UNIFORM_INDEXING // No COOPERATIVE_MATRIX - // No PER_VERTEX + | Caps::PER_VERTEX // No RAY_TRACING_PIPELINE // No DRAW_INDEX // No MEMORY_DECORATION_VOLATILE diff --git a/naga/src/back/hlsl/writer.rs b/naga/src/back/hlsl/writer.rs index c00026248..18f85b04e 100644 --- a/naga/src/back/hlsl/writer.rs +++ b/naga/src/back/hlsl/writer.rs @@ -921,6 +921,23 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> { ep_input.local_invocation_index_name.as_ref().unwrap() )?; } + Some(crate::Binding::Location { + interpolation: Some(crate::Interpolation::PerVertex), + .. + }) => { + if self.options.shader_model < ShaderModel::V6_1 { + return Err(Error::ShaderModelTooLow( + "per_vertex fragment inputs".to_string(), + ShaderModel::V6_1, + )); + } + write!( + self.out, + "{{ GetAttributeAtVertex({0}.{1}, 0), GetAttributeAtVertex({0}.{1}, 1), GetAttributeAtVertex({0}.{1}, 2) }}", + ep_input.arg_name, + fake_member.name, + )?; + } _ => { write!(self.out, "{}.{}", ep_input.arg_name, fake_member.name)?; } diff --git a/naga/src/back/msl/mod.rs b/naga/src/back/msl/mod.rs index ff54b07ca..9541f4800 100644 --- a/naga/src/back/msl/mod.rs +++ b/naga/src/back/msl/mod.rs @@ -189,6 +189,7 @@ enum ResolvedInterpolation { SamplePerspective, SampleNoPerspective, Flat, + PerVertex, } // Note: some of these should be removed in favor of proper IR validation. @@ -239,6 +240,8 @@ pub enum Error { ResolveArraySizeError(#[from] crate::proc::ResolveArraySizeError), #[error("entry point with stage {0:?} and name '{1}' not found")] EntryPointNotFound(ir::ShaderStage, String), + #[error("Per vertex fragment inputs are not supported prior to MSL 4.0")] + PerVertexNotSupported, } #[derive(Clone, Debug, PartialEq, thiserror::Error)] @@ -792,6 +795,7 @@ impl ResolvedInterpolation { (I::Linear, S::Centroid) => Self::CentroidNoPerspective, (I::Linear, S::Sample) => Self::SampleNoPerspective, (I::Flat, _) => Self::Flat, + (I::PerVertex, S::Center) => Self::PerVertex, _ => unreachable!(), } } @@ -805,6 +809,7 @@ impl ResolvedInterpolation { Self::SamplePerspective => "sample_perspective", Self::SampleNoPerspective => "sample_no_perspective", Self::Flat => "flat", + Self::PerVertex => unreachable!(), }; out.write_str(identifier)?; Ok(()) @@ -871,7 +876,7 @@ pub fn supported_capabilities() -> crate::valid::Capabilities { | Caps::STORAGE_TEXTURE_BINDING_ARRAY_NON_UNIFORM_INDEXING | Caps::STORAGE_BUFFER_BINDING_ARRAY_NON_UNIFORM_INDEXING | Caps::COOPERATIVE_MATRIX - // No PER_VERTEX + | Caps::PER_VERTEX // No RAY_TRACING_PIPELINE // No DRAW_INDEX // No MEMORY_DECORATION_VOLATILE diff --git a/naga/src/back/msl/writer.rs b/naga/src/back/msl/writer.rs index a012e5fd9..183f38add 100644 --- a/naga/src/back/msl/writer.rs +++ b/naga/src/back/msl/writer.rs @@ -216,6 +216,16 @@ impl TypeContext<'_> { _ => None, } } + + fn unwrap_array(self) -> Self { + match self.gctx.types[self.handle].inner { + crate::TypeInner::Array { base, .. } => Self { + handle: base, + ..self + }, + _ => self, + } + } } impl Display for TypeContext<'_> { @@ -7088,6 +7098,7 @@ template let stage_in_name = self.namer.call(&format!("{fun_name}Input")); let varyings_member_name = self.namer.call("varyings"); let mut has_varyings = false; + if !flattened_arguments.is_empty() { if !do_vertex_pulling { writeln!(self.out, "struct {stage_in_name} {{")?; @@ -7129,8 +7140,25 @@ template ); } else { has_varyings = true; - write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?; - resolved.try_fmt(&mut self.out)?; + if let super::ResolvedBinding::User { + prefix, + index, + interpolation: Some(super::ResolvedInterpolation::PerVertex), + } = resolved + { + if options.lang_version < (4, 0) { + return Err(Error::PerVertexNotSupported); + } + write!( + self.out, + "{}{NAMESPACE}::vertex_value<{}> {name} [[user({prefix}{index})]]", + back::INDENT, + ty_name.unwrap_array() + )?; + } else { + write!(self.out, "{}{} {}", back::INDENT, ty_name, name)?; + resolved.try_fmt(&mut self.out)?; + } writeln!(self.out, ";")?; } } @@ -7856,16 +7884,51 @@ template { write!(self.out, "{{}}, ")?; } - if let Some(crate::Binding::Location { .. }) = member.binding { - if has_varyings { - write!(self.out, "{varyings_member_name}.")?; + match member.binding { + Some(crate::Binding::Location { + interpolation: Some(crate::Interpolation::PerVertex), + .. + }) => { + writeln!( + self.out, + "{0}{{ {1}.{2}.get({NAMESPACE}::vertex_index::first), {1}.{2}.get({NAMESPACE}::vertex_index::second), {1}.{2}.get({NAMESPACE}::vertex_index::third) }}", + back::INDENT, + varyings_member_name, + arg_name, + )?; + continue; } + Some(crate::Binding::Location { .. }) => { + if has_varyings { + write!(self.out, "{varyings_member_name}.")?; + } + } + _ => (), } write!(self.out, "{name}")?; } writeln!(self.out, " }};")?; } _ => match arg.binding { + Some(crate::Binding::Location { + interpolation: Some(crate::Interpolation::PerVertex), + .. + }) => { + let ty_name = TypeContext { + handle: arg.ty, + gctx: module.to_ctx(), + names: &self.names, + access: crate::StorageAccess::empty(), + first_time: false, + }; + writeln!( + self.out, + "{0}const {ty_name} {arg_name} = {{ {1}.{2}.get({NAMESPACE}::vertex_index::first), {1}.{2}.get({NAMESPACE}::vertex_index::second), {1}.{2}.get({NAMESPACE}::vertex_index::third) }};", + back::INDENT, + varyings_member_name, + arg_name, + )?; + } Some(crate::Binding::Location { .. }) | Some(crate::Binding::BuiltIn(crate::BuiltIn::Barycentric { .. })) => { if has_varyings { diff --git a/naga/src/back/wgsl/writer.rs b/naga/src/back/wgsl/writer.rs index bc6971d55..17d8a7e85 100644 --- a/naga/src/back/wgsl/writer.rs +++ b/naga/src/back/wgsl/writer.rs @@ -296,6 +296,7 @@ impl Writer { cooperative_matrix: bool, draw_index: bool, ray_tracing_pipeline: bool, + per_vertex: bool, } let mut needed = RequiredEnabled { mesh_shaders: module.uses_mesh_shaders(), @@ -321,6 +322,12 @@ impl Writer { } => { needed.mesh_shaders = true; } + crate::Binding::Location { + interpolation: Some(crate::Interpolation::PerVertex), + .. + } => { + needed.per_vertex = true; + } crate::Binding::BuiltIn(crate::BuiltIn::DrawIndex) => needed.draw_index = true, crate::Binding::BuiltIn( crate::BuiltIn::RayInvocationId @@ -450,6 +457,10 @@ impl Writer { writeln!(self.out, "enable wgpu_ray_tracing_pipeline;")?; any_written = true; } + if needed.per_vertex { + writeln!(self.out, "enable wgpu_per_vertex;")?; + any_written = true; + } if any_written { // Empty line for readability writeln!(self.out)?; diff --git a/naga/src/front/wgsl/parse/conv.rs b/naga/src/front/wgsl/parse/conv.rs index 3a292a81b..6270d4b96 100644 --- a/naga/src/front/wgsl/parse/conv.rs +++ b/naga/src/front/wgsl/parse/conv.rs @@ -172,12 +172,19 @@ pub fn map_built_in( Ok(built_in) } -pub fn map_interpolation(word: &str, span: Span) -> Result<'_, crate::Interpolation> { +pub fn map_interpolation( + enable_extensions: &EnableExtensions, + word: &str, + span: Span, +) -> Result<'static, crate::Interpolation> { match word { "linear" => Ok(crate::Interpolation::Linear), "flat" => Ok(crate::Interpolation::Flat), "perspective" => Ok(crate::Interpolation::Perspective), - "per_vertex" => Ok(crate::Interpolation::PerVertex), + "per_vertex" => { + enable_extensions.require(ImplementedEnableExtension::PerVertex, span)?; + Ok(crate::Interpolation::PerVertex) + } _ => Err(Box::new(Error::UnknownAttribute(span))), } } diff --git a/naga/src/front/wgsl/parse/directive/enable_extension.rs b/naga/src/front/wgsl/parse/directive/enable_extension.rs index e93b304e3..a6d728551 100644 --- a/naga/src/front/wgsl/parse/directive/enable_extension.rs +++ b/naga/src/front/wgsl/parse/directive/enable_extension.rs @@ -21,6 +21,7 @@ pub(crate) struct EnableExtensions { wgpu_cooperative_matrix: bool, draw_index: bool, primitive_index: bool, + per_vertex: bool, } impl EnableExtensions { @@ -36,6 +37,7 @@ impl EnableExtensions { wgpu_cooperative_matrix: false, draw_index: false, primitive_index: false, + per_vertex: false, } } @@ -56,6 +58,7 @@ impl EnableExtensions { ImplementedEnableExtension::WgpuCooperativeMatrix => &mut self.wgpu_cooperative_matrix, ImplementedEnableExtension::DrawIndex => &mut self.draw_index, ImplementedEnableExtension::PrimitiveIndex => &mut self.primitive_index, + ImplementedEnableExtension::PerVertex => &mut self.per_vertex, }; *field = true; } @@ -75,6 +78,7 @@ impl EnableExtensions { ImplementedEnableExtension::WgpuCooperativeMatrix => self.wgpu_cooperative_matrix, ImplementedEnableExtension::DrawIndex => self.draw_index, ImplementedEnableExtension::PrimitiveIndex => self.primitive_index, + ImplementedEnableExtension::PerVertex => self.per_vertex, } } @@ -127,6 +131,7 @@ impl EnableExtension { const SUBGROUPS: &'static str = "subgroups"; const PRIMITIVE_INDEX: &'static str = "primitive_index"; const DRAW_INDEX: &'static str = "draw_index"; + const PER_VERTEX: &'static str = "wgpu_per_vertex"; /// Convert from a sentinel word in WGSL into its associated [`EnableExtension`], if possible. pub(crate) fn from_ident(word: &str, span: Span) -> Result<'_, Self> { @@ -150,6 +155,7 @@ impl EnableExtension { Self::SUBGROUPS => Self::Unimplemented(UnimplementedEnableExtension::Subgroups), Self::DRAW_INDEX => Self::Implemented(ImplementedEnableExtension::DrawIndex), Self::PRIMITIVE_INDEX => Self::Implemented(ImplementedEnableExtension::PrimitiveIndex), + Self::PER_VERTEX => Self::Implemented(ImplementedEnableExtension::PerVertex), _ => return Err(Box::new(Error::UnknownEnableExtension(span, word))), }) } @@ -170,6 +176,7 @@ impl EnableExtension { ImplementedEnableExtension::DrawIndex => Self::DRAW_INDEX, ImplementedEnableExtension::PrimitiveIndex => Self::PRIMITIVE_INDEX, ImplementedEnableExtension::WgpuRayTracingPipeline => Self::RAY_TRACING_PIPELINE, + ImplementedEnableExtension::PerVertex => Self::PER_VERTEX, }, Self::Unimplemented(kind) => match kind { UnimplementedEnableExtension::Subgroups => Self::SUBGROUPS, @@ -218,6 +225,8 @@ pub enum ImplementedEnableExtension { /// /// [`enable primitive-index;`]: https://www.w3.org/TR/WGSL/#extension-primitive_index PrimitiveIndex, + /// Enables the `wgpu_per_vertex` extension, allows using `@interpolate(per_vertex)` attribute in WGSL, native only. + PerVertex, } impl ImplementedEnableExtension { @@ -233,6 +242,7 @@ impl ImplementedEnableExtension { Self::WgpuCooperativeMatrix, Self::DrawIndex, Self::PrimitiveIndex, + Self::PerVertex, ]; /// Returns slice of all variants of [`ImplementedEnableExtension`]. @@ -254,6 +264,7 @@ impl ImplementedEnableExtension { Self::WgpuRayTracingPipeline => C::RAY_TRACING_PIPELINE, Self::DrawIndex => C::DRAW_INDEX, Self::PrimitiveIndex => C::PRIMITIVE_INDEX, + Self::PerVertex => C::PER_VERTEX, } } } diff --git a/naga/src/front/wgsl/parse/mod.rs b/naga/src/front/wgsl/parse/mod.rs index 7da8f4db1..f390c4b95 100644 --- a/naga/src/front/wgsl/parse/mod.rs +++ b/naga/src/front/wgsl/parse/mod.rs @@ -199,8 +199,10 @@ impl<'a> BindingParser<'a> { "interpolate" => { lexer.expect(Token::Paren('('))?; let (raw, span) = lexer.next_ident_with_span()?; - self.interpolation - .set(conv::map_interpolation(raw, span)?, name_span)?; + self.interpolation.set( + conv::map_interpolation(&lexer.enable_extensions, raw, span)?, + name_span, + )?; if lexer.next_if(Token::Separator(',')) { let (raw, span) = lexer.next_ident_with_span()?; self.sampling diff --git a/naga/src/valid/interface.rs b/naga/src/valid/interface.rs index 60a930150..e81360396 100644 --- a/naga/src/valid/interface.rs +++ b/naga/src/valid/interface.rs @@ -121,6 +121,8 @@ pub enum VaryingError { MissingPerPrimitive, #[error("Per vertex fragment inputs must be an array of length 3.")] PerVertexNotArrayOfThree, + #[error("Per vertex can only have Center sampling or no sampling modifier")] + InvalidPerVertexSampling, } #[derive(Clone, Debug, thiserror::Error)] @@ -693,6 +695,9 @@ impl VaryingContext<'_> { Capabilities::PER_VERTEX, )); } + if sampling.is_some_and(|e| e != crate::Sampling::Center) { + return Err(VaryingError::InvalidPerVertexSampling); + } } // If this is per-vertex, we change the type we validate to the inner type, otherwise we leave it be. // This lets all validation be done on the inner type once we've ensured the per-vertex is array diff --git a/naga/src/valid/mod.rs b/naga/src/valid/mod.rs index 6cdc47306..87e0ef531 100644 --- a/naga/src/valid/mod.rs +++ b/naga/src/valid/mod.rs @@ -235,6 +235,7 @@ impl Capabilities { Self::RAY_HIT_VERTEX_POSITION => Some(Ext::WgpuRayQueryVertexReturn), Self::COOPERATIVE_MATRIX => Some(Ext::WgpuCooperativeMatrix), Self::RAY_TRACING_PIPELINE => Some(Ext::WgpuRayTracingPipeline), + Self::PER_VERTEX => Some(Ext::PerVertex), _ => None, } } diff --git a/naga/tests/in/wgsl/per-vertex.toml b/naga/tests/in/wgsl/per-vertex.toml index ca0449904..6f8a9fc65 100644 --- a/naga/tests/in/wgsl/per-vertex.toml +++ b/naga/tests/in/wgsl/per-vertex.toml @@ -1,2 +1,8 @@ capabilities = "PER_VERTEX" -targets = "WGSL | SPIRV" +targets = "WGSL | SPIRV | METAL | HLSL" + +[msl] +lang_version = [4, 0] + +[hlsl] +shader_model = "V6_1" diff --git a/naga/tests/in/wgsl/per-vertex.wgsl b/naga/tests/in/wgsl/per-vertex.wgsl index 6a7c09ba8..247a7ca6c 100644 --- a/naga/tests/in/wgsl/per-vertex.wgsl +++ b/naga/tests/in/wgsl/per-vertex.wgsl @@ -1,3 +1,5 @@ +enable wgpu_per_vertex; + @fragment fn fs_main(@location(0) @interpolate(per_vertex) v: array) -> @location(0) vec4 { return vec4(v[0], v[1], v[2], 1.0); diff --git a/naga/tests/naga/validation.rs b/naga/tests/naga/validation.rs index 8b4852a08..b3e41e2e0 100644 --- a/naga/tests/naga/validation.rs +++ b/naga/tests/naga/validation.rs @@ -435,6 +435,7 @@ fn incompatible_interpolation_and_sampling_types() { naga::Interpolation::Flat, Some(naga::Sampling::First | naga::Sampling::Either) ) + | (naga::Interpolation::PerVertex, Some(naga::Sampling::Center)) ); if valid { @@ -456,11 +457,12 @@ fn incompatible_interpolation_and_sampling_types() { } }; + // Note: `PerVertex` is excluded here because its invalid sampling combinations produce + // `VaryingError::InvalidPerVertexSampling` rather than `InvalidInterpolationSamplingCombination`. let invalid_cases = [ naga::Interpolation::Flat, naga::Interpolation::Linear, naga::Interpolation::Perspective, - naga::Interpolation::PerVertex, ] .into_iter() .cartesian_product( @@ -571,9 +573,15 @@ mod dummy_interpolation_shader { naga::Interpolation::PerVertex => "array", }; + let enable_extension = if interpolation == naga::Interpolation::PerVertex { + "enable wgpu_per_vertex;\n\n" + } else { + "" + }; let interpolate_attr = format!("@interpolate({interpolation_str}{sampling_str})"); let source = format!( "\ + {enable_extension} struct VertexOutput {{ @location(0) {interpolate_attr} member: {member_type}, }} diff --git a/naga/tests/naga/wgsl_errors.rs b/naga/tests/naga/wgsl_errors.rs index ea90e5df1..cf22c5984 100644 --- a/naga/tests/naga/wgsl_errors.rs +++ b/naga/tests/naga/wgsl_errors.rs @@ -1233,6 +1233,8 @@ fn int64_capability() { fn per_vertex_capability() { check_validation! { r#" + enable wgpu_per_vertex; + @fragment fn fs_main(@location(0) @interpolate(per_vertex) v: array) -> @location(0) vec4 { return vec4(v[0], v[1], v[2], 1.0); @@ -4958,6 +4960,38 @@ fn mesh_shader_enable_extension() { ); } +#[test] +fn per_vertex_enable_extension() { + // `task_payload` address space + check_extension_validation!( + Capabilities::PER_VERTEX, + r#"@fragment +fn fs_main(@location(0) @interpolate(per_vertex) v: array) -> @location(0) vec4 { + return vec4(v[0], v[1], v[2], 1.0); +} + + "#, + r#"error: the `wgpu_per_vertex` enable extension is not enabled + ┌─ wgsl:2:38 + │ +2 │ fn fs_main(@location(0) @interpolate(per_vertex) v: array) -> @location(0) vec4 { + │ ^^^^^^^^^^ the `wgpu_per_vertex` "Enable Extension" is needed for this functionality, but it is not currently enabled. + │ + = note: You can enable this extension by adding `enable wgpu_per_vertex;` at the top of the shader, before any other items. + +"#, + Err(naga::valid::ValidationError::EntryPoint { + source: naga::valid::EntryPointError::Argument( + 0, + naga::valid::VaryingError::UnsupportedCapability( + naga::valid::Capabilities::PER_VERTEX + ) + ), + .. + }) + ); +} + /// Checks that every ray tracing pipeline binding in naga is invalid in other stages. #[test] fn check_ray_tracing_pipeline_bindings() { diff --git a/naga/tests/out/hlsl/wgsl-per-vertex.hlsl b/naga/tests/out/hlsl/wgsl-per-vertex.hlsl new file mode 100644 index 000000000..8374a67ed --- /dev/null +++ b/naga/tests/out/hlsl/wgsl-per-vertex.hlsl @@ -0,0 +1,9 @@ +struct FragmentInput_fs_main { + nointerpolation float v_1 : LOC0; +}; + +float4 fs_main(FragmentInput_fs_main fragmentinput_fs_main) : SV_Target0 +{ + float v[3] = { GetAttributeAtVertex(fragmentinput_fs_main.v_1, 0), GetAttributeAtVertex(fragmentinput_fs_main.v_1, 1), GetAttributeAtVertex(fragmentinput_fs_main.v_1, 2) }; + return float4(v[0], v[1], v[2], 1.0); +} diff --git a/naga/tests/out/hlsl/wgsl-per-vertex.ron b/naga/tests/out/hlsl/wgsl-per-vertex.ron new file mode 100644 index 000000000..5e303e721 --- /dev/null +++ b/naga/tests/out/hlsl/wgsl-per-vertex.ron @@ -0,0 +1,16 @@ +( + vertex:[ + ], + fragment:[ + ( + entry_point:"fs_main", + target_profile:"ps_6_1", + ), + ], + compute:[ + ], + task:[ + ], + mesh:[ + ], +) diff --git a/naga/tests/out/msl/wgsl-per-vertex.metal b/naga/tests/out/msl/wgsl-per-vertex.metal new file mode 100644 index 000000000..f29955f3f --- /dev/null +++ b/naga/tests/out/msl/wgsl-per-vertex.metal @@ -0,0 +1,22 @@ +// language: metal4.0 +#include +#include + +using metal::uint; + +struct type_1 { + float inner[3]; +}; + +struct fs_mainInput { + metal::vertex_value v [[user(loc0)]]; +}; +struct fs_mainOutput { + metal::float4 member [[color(0)]]; +}; +fragment fs_mainOutput fs_main( + fs_mainInput varyings [[stage_in]] +) { + const type_1 v = { varyings.v.get(metal::vertex_index::first), varyings.v.get(metal::vertex_index::second), varyings.v.get(metal::vertex_index::third) }; + return fs_mainOutput { metal::float4(v.inner[0], v.inner[1], v.inner[2], 1.0) }; +} diff --git a/naga/tests/out/wgsl/spv-per-vertex.wgsl b/naga/tests/out/wgsl/spv-per-vertex.wgsl index 47eaf9f63..4145447c1 100644 --- a/naga/tests/out/wgsl/spv-per-vertex.wgsl +++ b/naga/tests/out/wgsl/spv-per-vertex.wgsl @@ -1,3 +1,5 @@ +enable wgpu_per_vertex; + var global: array; var global_1: vec4; diff --git a/naga/tests/out/wgsl/wgsl-per-vertex.wgsl b/naga/tests/out/wgsl/wgsl-per-vertex.wgsl index dd45184d7..de06c9d59 100644 --- a/naga/tests/out/wgsl/wgsl-per-vertex.wgsl +++ b/naga/tests/out/wgsl/wgsl-per-vertex.wgsl @@ -1,3 +1,5 @@ +enable wgpu_per_vertex; + @fragment fn fs_main(@location(0) @interpolate(per_vertex) v: array) -> @location(0) vec4 { return vec4(v[0], v[1], v[2], 1f); diff --git a/tests/src/image.rs b/tests/src/image.rs index a9875f618..8813bbae2 100644 --- a/tests/src/image.rs +++ b/tests/src/image.rs @@ -633,6 +633,16 @@ impl ReadbackBuffers { } pub async fn assert_buffer_contents(&self, ctx: &TestingContext, expected_data: &[u8]) { + self.assert_buffer_contents_imprecise(ctx, expected_data, 0) + .await; + } + + pub async fn assert_buffer_contents_imprecise( + &self, + ctx: &TestingContext, + expected_data: &[u8], + max_diff: u8, + ) { let result_buffer = self .retrieve_buffer(ctx, &self.buffer, self.buffer_aspect()) .await; @@ -643,7 +653,10 @@ impl ReadbackBuffers { expected_data.len() ); let result_buffer = &result_buffer[..expected_data.len()]; - assert_eq!(result_buffer, expected_data); + assert!(result_buffer + .iter() + .zip(expected_data) + .all(|(a, b)| a.abs_diff(*b) <= max_diff)); self.buffer.unmap(); } } diff --git a/tests/tests/wgpu-gpu/per_vertex/mod.rs b/tests/tests/wgpu-gpu/per_vertex/mod.rs index 3a3253c54..c0eb1e4ef 100644 --- a/tests/tests/wgpu-gpu/per_vertex/mod.rs +++ b/tests/tests/wgpu-gpu/per_vertex/mod.rs @@ -180,6 +180,6 @@ async fn per_vertex(ctx: TestingContext) { 64, 191, 127, 255, // bottom right ]; readback_buffer - .assert_buffer_contents(&ctx, &expected) + .assert_buffer_contents_imprecise(&ctx, &expected, 1) .await; } diff --git a/tests/tests/wgpu-gpu/per_vertex/per_vertex.wgsl b/tests/tests/wgpu-gpu/per_vertex/per_vertex.wgsl index c0b4f2448..b55caa37e 100644 --- a/tests/tests/wgpu-gpu/per_vertex/per_vertex.wgsl +++ b/tests/tests/wgpu-gpu/per_vertex/per_vertex.wgsl @@ -1,3 +1,5 @@ +enable wgpu_per_vertex; + struct VertexOutput { @builtin(position) clip: vec4, @interpolate(flat) @location(0) z: f32, diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index 0bbb16bbc..3988faea0 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -3876,6 +3876,7 @@ impl Device { &final_entry_point_name, stage, io, + None, )?; } } @@ -4406,6 +4407,7 @@ impl Device { &_vertex_entry_point_name, stage, io, + Some(desc.primitive.topology), ) .map_err(stage_err)?; validated_stages |= stage_bit; @@ -4449,6 +4451,7 @@ impl Device { &_task_entry_point_name, stage, io, + Some(desc.primitive.topology), ) .map_err(stage_err)?; validated_stages |= stage_bit; @@ -4490,6 +4493,7 @@ impl Device { &_mesh_entry_point_name, stage, io, + Some(desc.primitive.topology), ) .map_err(stage_err)?; validated_stages |= stage_bit; @@ -4541,6 +4545,7 @@ impl Device { &fragment_entry_point_name, stage, io, + Some(desc.primitive.topology), ) .map_err(stage_err)?; validated_stages |= stage_bit; diff --git a/wgpu-core/src/validation.rs b/wgpu-core/src/validation.rs index 93b5f7de7..22c4c2407 100644 --- a/wgpu-core/src/validation.rs +++ b/wgpu-core/src/validation.rs @@ -278,6 +278,7 @@ struct SpecializationConstant { struct EntryPointMeshInfo { max_vertices: u32, max_primitives: u32, + primitive_topology: wgt::PrimitiveTopology, } #[derive(Debug, Default)] @@ -496,12 +497,16 @@ pub enum StageError { InvalidPrimitiveIndex, #[error("If a mesh shader writes to primitive index, it must be read by the fragment shader.")] MissingPrimitiveIndex, - #[error("DrawId cannot be used in the same pipeline as a task shader")] + #[error("DrawId cannot be used in a mesh shader in a pipeline with a task shader")] DrawIdError, #[error("Pipeline uses dual-source blending, but the shader does not support it")] InvalidDualSourceBlending, #[error("Fragment shader writes depth, but pipeline does not have a depth attachment")] MissingFragDepthAttachment, + #[error("Per vertex fragment inputs can only be used in triangle primitive pipelines")] + PerVertexNotTriangles, + #[error("Mesh shader pipelines must have primitive topology of TriangleList, LineList or PointList, and this must match with what the mesh shader declares.")] + MeshTopologyMismatch, } impl WebGpuError for StageError { @@ -536,7 +541,9 @@ impl WebGpuError for StageError { | Self::MissingPrimitiveIndex | Self::DrawIdError | Self::InvalidDualSourceBlending - | Self::MissingFragDepthAttachment => ErrorType::Validation, + | Self::MissingFragDepthAttachment + | Self::PerVertexNotTriangles + | Self::MeshTopologyMismatch => ErrorType::Validation, } } } @@ -1266,6 +1273,11 @@ impl Interface { ep.mesh_info = Some(EntryPointMeshInfo { max_vertices: mesh_info.max_vertices, max_primitives: mesh_info.max_primitives, + primitive_topology: match mesh_info.topology { + naga::MeshOutputTopology::Triangles => wgt::PrimitiveTopology::TriangleList, + naga::MeshOutputTopology::Lines => wgt::PrimitiveTopology::LineList, + naga::MeshOutputTopology::Points => wgt::PrimitiveTopology::PointList, + }, }); Self::populate( &mut ep.outputs, @@ -1321,6 +1333,7 @@ impl Interface { entry_point_name: &str, shader_stage: ShaderStageForValidation, inputs: StageIo, + primitive_topology: Option, ) -> 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. @@ -1500,6 +1513,7 @@ impl Interface { let mut this_stage_primitive_index = false; let mut has_draw_id = false; + let mut has_per_vertex = false; // check inputs compatibility for input in entry_point.inputs.iter() { @@ -1564,6 +1578,7 @@ impl Interface { error, }); } + has_per_vertex |= iv.interpolation == Some(naga::Interpolation::PerVertex); } Varying::BuiltIn(BuiltIn::PrimitiveIndex) => { this_stage_primitive_index = true; @@ -1776,6 +1791,9 @@ impl Interface { value: mesh_info.max_primitives, }); } + if primitive_topology != Some(mesh_info.primitive_topology) { + return Err(StageError::MeshTopologyMismatch); + } } if let Some(task_payload_size) = entry_point.task_payload_size { if task_payload_size > self.limits.max_task_payload_size { @@ -1813,6 +1831,10 @@ impl Interface { return Err(StageError::DrawIdError); } + if primitive_topology.is_none_or(|e| !e.is_triangles()) && has_per_vertex { + return Err(StageError::PerVertexNotTriangles); + } + let outputs = entry_point .outputs .iter() diff --git a/wgpu-hal/src/dx12/adapter.rs b/wgpu-hal/src/dx12/adapter.rs index fd839a075..7d0858c52 100644 --- a/wgpu-hal/src/dx12/adapter.rs +++ b/wgpu-hal/src/dx12/adapter.rs @@ -710,7 +710,7 @@ impl super::Adapter { && shader_model >= naga::back::hlsl::ShaderModel::V6_1 }; features.set( - wgt::Features::SHADER_BARYCENTRICS, + wgt::Features::SHADER_BARYCENTRICS | wgt::Features::SHADER_PER_VERTEX, shader_barycentrics_supported, ); diff --git a/wgpu-hal/src/metal/adapter.rs b/wgpu-hal/src/metal/adapter.rs index c8b165e82..def1f2acb 100644 --- a/wgpu-hal/src/metal/adapter.rs +++ b/wgpu-hal/src/metal/adapter.rs @@ -668,7 +668,9 @@ impl super::CapabilitiesQuery { // Mesh shaders don't work on virtual devices even if they should be supported. CI thing && !is_virtual; - let msl_version = if available!(macos = 15.0, ios = 18.0, tvos = 18.0, visionos = 2.0) { + let msl_version = if available!(macos = 26.0, ios = 26.0, tvos = 26.0, visionos = 26.0) { + MTLLanguageVersion::Version4_0 + } else if available!(macos = 15.0, ios = 18.0, tvos = 18.0, visionos = 2.0) { MTLLanguageVersion::Version3_2 } else if available!(macos = 14.0, ios = 17.0, tvos = 17.0, visionos = 1.0) { MTLLanguageVersion::Version3_1 @@ -1081,6 +1083,7 @@ impl super::CapabilitiesQuery { } else { false }, + shader_per_vertex: family_check && device.supportsFamily(MTLGPUFamily::Apple10), } } @@ -1189,6 +1192,8 @@ impl super::CapabilitiesQuery { self.shader_barycentrics && self.msl_version >= MTLLanguageVersion::Version2_2, ); + features.set(F::SHADER_PER_VERTEX, self.shader_per_vertex); + if self.supports_simd_scoped_operations { features.insert(F::SUBGROUP | F::SUBGROUP_BARRIER); } diff --git a/wgpu-hal/src/metal/device.rs b/wgpu-hal/src/metal/device.rs index 542258151..586143ea3 100644 --- a/wgpu-hal/src/metal/device.rs +++ b/wgpu-hal/src/metal/device.rs @@ -178,8 +178,9 @@ impl super::Device { MTLLanguageVersion::Version3_0 => (3, 0), MTLLanguageVersion::Version3_1 => (3, 1), MTLLanguageVersion::Version3_2 => (3, 2), + MTLLanguageVersion::Version4_0 => (4, 0), // Newer version, fall back to 3.2 - _ => (3, 2), + _ => (4, 0), }, inline_samplers: Default::default(), spirv_cross_compatibility: false, diff --git a/wgpu-hal/src/metal/mod.rs b/wgpu-hal/src/metal/mod.rs index fbad5b49b..bec4cae6c 100644 --- a/wgpu-hal/src/metal/mod.rs +++ b/wgpu-hal/src/metal/mod.rs @@ -316,6 +316,7 @@ struct CapabilitiesQuery { shader_barycentrics: bool, supports_memoryless_storage: bool, supports_raytracing: bool, + shader_per_vertex: bool, } #[derive(Debug)]