From 3c86a2a45f2f4c5c3e8dc7c9b0584e2b9e8a0429 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 23 Nov 2026 00:13:45 -0800 Subject: [PATCH] Translator: a vertex function's slice and viewport index are stored as it writes them Metal requires the same [[render_target_array_index]] and [[viewport_array_index]] at every vertex of a primitive ("If values differ, the behavior and value passed to the fragment function are undefined.", the Metal Shading Language specification), and Vulkan asks the same of Layer and ViewportIndex (VUID-VkPipelineShaderStageCreateInfo-stage-02596 and -02597). The translator stored an index only where the function's structure showed it the same among a primitive's vertices (uniform_varyings over the raw index varyings) and refused every other one, NotImplemented(LayeredRendering), on every device. A program that keeps Metal's rule keeps Vulkan's with the index stored as written, and one that breaks it has no Metal answer to match, so plan::index_store now stores the index to its builtin wherever the device stores it from a vertex function (shaderOutputLayer, shaderOutputViewportIndex, both in the floor), whatever the structure shows; a device without the output is refused needing it, as before. The store keeps index < count ? index : 0 against the pushed length and viewport count, and an index never written is still stored as 0. uniform_varyings now lists user varyings alone (the raw index keys decided nothing else), and uniform_index is gone. Where a program breaks Metal's rule the layer or viewport is the device's choice: the runtime README's layered line and docs/API.md (section 4 and section 10's accepted differences) say so in one sentence, the viewport paragraph and set_viewports no longer name a geometry stage, and docs/REFUSALS.md is regenerated (LayeredRendering is now a device refusal alone). The runtime's layered device test draws rt6_per_primitive's three triangles into slices 1, 1 and 2 through viewports 0, 1 and 1 of a 2D array, checking every texel, in place of the refusal it asserted. SEMANTICS_VERSION 2283: modules for such functions instead of the refusal, and uniform outputs without the raw index keys. --- crates/metal2vulkan-runtime/README.md | 22 +-- .../src/render_encoder.rs | 6 +- .../metal2vulkan-runtime/src/tests/layered.rs | 139 ++++++++++++++---- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/src/lower/select.rs | 5 +- crates/metal2vulkan/src/lower/stage_io/mod.rs | 34 ++--- .../metal2vulkan/src/lower/stage_io/plan.rs | 68 +++------ crates/metal2vulkan/src/pipeline/stage_io.rs | 11 +- .../src/tests/engine_amplification.rs | 15 +- .../src/tests/engine_render_target_slice.rs | 2 +- docs/API.md | 31 ++-- docs/REFUSALS.md | 6 +- 12 files changed, 185 insertions(+), 156 deletions(-) diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index d5046eb0b..af91b13ba 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -4139,9 +4139,8 @@ cache is answered compile-required on both. the encoder's count, which a draw pushes, as Metal draws it through viewport 0. A draw of any other function draws through viewport 0. Vulkan takes as many scissors as viewports: each viewport's is the rectangle of its index, the one rectangle where one is set, and none past - the rectangles set where several are, each cut to the pixels its viewport covers. An index - that is not one value across a primitive is the translator's refusal at creation, as a layer - index is: its form is a geometry stage, which device creation does not enable. + the rectangles set where several are, each cut to the pixels its viewport covers. The index is + stored as the function writes it, as a layer index is (Layered rendering, below). - A draw may read an attachment of its own pass through a texture, as Metal reads a render target, where the device reads attachments (Floor, Attachment reads): through the attachment feedback loop where the device has it, else through a copy. The texture reaches the @@ -4440,18 +4439,11 @@ cache is answered compile-required on both. depth planes, which are no attachment's layers (`Gap::RenderPass`, `TextureType`, as for any 3D attachment), and a draw that reads one of its pass's attachments through a texture on a device without the attachment feedback loop (`Gap::Draw`, `AttachmentRead`: an attachment's shadow - holds one layer); and, at creation on every device, whatever pass it would draw in, a vertex - function whose `[[render_target_array_index]]` the translator cannot show the same at every - vertex of a primitive, an `Error::Translation` naming `LayeredRendering` as not implemented. - Vulkan requires one `Layer` at every vertex of a primitive - (`VUID-VkPipelineShaderStageCreateInfo-stage-02596`), so such a function cannot store its index - as written, and Metal documents a differing index as undefined (the Metal Shading Language - specification). The translator shows an index - the same where it is computed from constants, `constant` memory, the draw's instance, base - vertex and base instance, and attributes fetched per instance, never from `[[vertex_id]]` or - another per-vertex input (`StageIo::uniform_outputs`): `constant uint *layers` read at - `[[instance_id]]` is, a `device` buffer read at `[[vertex_id]]` is not. An index the function - declares and never writes, which Metal gives no value, is stored as 0, the same at every vertex. + holds one layer). A vertex function's `[[render_target_array_index]]` and + `[[viewport_array_index]]` are stored as the function writes them. Metal requires the same value + at every vertex of a primitive; where a program breaks that, the layer or viewport is the + device's choice. An index the function declares and never writes, which Metal gives no value, + is stored as 0, the same at every vertex. - A `Clear` pass of one layer that encodes no draw clears Metal's render area rounded up to 32 pixels a side, where a Mac clears the whole level and slice of a texture it keeps losslessly compressed, which no Vulkan query tells. A pass whose attachments differ in size reaches the diff --git a/crates/metal2vulkan-runtime/src/render_encoder.rs b/crates/metal2vulkan-runtime/src/render_encoder.rs index b0fb8e331..d761ed9ce 100644 --- a/crates/metal2vulkan-runtime/src/render_encoder.rs +++ b/crates/metal2vulkan-runtime/src/render_encoder.rs @@ -1573,9 +1573,9 @@ impl RenderCommandEncoder { /// floor's `multiViewport` and `shaderOutputViewportIndex`), viewport 0 for an index at or past /// the count, as Metal draws it; a draw of any other function takes viewport 0. Each viewport's /// scissor is the rectangle of its index, the one rectangle where one is set, and none past the - /// rectangles set where several are, each cut to the pixels its viewport covers. An index that - /// is not one value across a primitive is the translator's refusal at the state's creation (a - /// geometry stage, which device creation does not enable). + /// rectangles set where several are, each cut to the pixels its viewport covers. Metal requires + /// one index at every vertex of a primitive; where a function writes several, the viewport is + /// the device's choice. /// /// Err: as [`set_viewport`](Self::set_viewport) for any of them, the encoder's viewports /// unchanged; [`Gap::Draw`] of [`DrawKind::Viewports`] for none or more than 16. diff --git a/crates/metal2vulkan-runtime/src/tests/layered.rs b/crates/metal2vulkan-runtime/src/tests/layered.rs index f44659d6d..63dada19d 100644 --- a/crates/metal2vulkan-runtime/src/tests/layered.rs +++ b/crates/metal2vulkan-runtime/src/tests/layered.rs @@ -4,12 +4,15 @@ //! past the pass's length renders its first slice, the pass's clear covers every layer, a pass of //! one layer renders its slice whatever index the vertex function writes, and the fragment //! function reads the index as written, in each, over a 2D array, a cube and a cube array (its -//! faces counted across its cubes). A vertex function whose index may differ among a -//! primitive's vertices is refused at creation, naming `LayeredRendering`. +//! faces counted across its cubes). A vertex function that reads its slice and viewport per +//! triangle from a device buffer renders each triangle into the slice and through the viewport it +//! reads, the index stored as the function writes it. //! //! `rt6_layered_vertex` (engine `rt6_layered`) draws the fullscreen triangle once per instance, //! instance `i` writing index `layers[i]`; `rt6_layered_fragment` writes `(i + 1) << 8 | index`. -//! `rt6_first_vertex` writes each vertex's own index (`indices[vid]`). +//! `rt6_per_primitive` (engine `rt6_per_primitive`) writes triangle `t`'s slice and viewport from +//! `indices[t]` (`vertex_id / 3`); `rt6_per_primitive_read` writes +//! `index << 16 | viewport << 8 | slice`. //! //! `llvm-as` assembles the functions; without it the test skips visibly. @@ -21,10 +24,9 @@ mod on_device { ClearColor, ColorAttachmentDescriptor, Device, Error, FunctionDescriptor, HostBytes, LoadAction, PixelFormat, PrimitiveType, Region, RenderPassDescriptor, RenderPipelineDescriptor, RenderPipelineState, StageSource, StorageMode, Texture, - TextureDescriptor, TextureType, TextureUsage, + TextureDescriptor, TextureType, TextureUsage, Viewport, }; use metal2vulkan::device::VkFeature; - use metal2vulkan::error::Feature; use metal2vulkan_devtools::engine_dir; /// What priming leaves in every slice before a pass: no fragment's word and not the clear. @@ -202,14 +204,106 @@ mod on_device { pass.expect.len() as u32 * SIDE * SIDE } - /// Every device renders Metal's layers, from one form of the vertex function, and refuses a - /// vertex function whose index may differ among a primitive's vertices. + /// The index each of `rt6_per_primitive`'s triangles reads: slice 1 through viewport 0, slice 1 + /// through viewport 1, and slice 2 through viewport 1. + const PER_PRIMITIVE: [u32; 3] = [0x0001, 0x0101, 0x0102]; + + /// The word `rt6_per_primitive_read` writes for a triangle that read `index`. + const fn per_primitive_word(index: u32) -> u32 { + index << 16 | index + } + + /// The viewport over columns `[x, x + width)` of the target, every row, depth `[0, 1]`. + fn columns(x: u32, width: u32) -> Viewport { + Viewport { + origin_x: f64::from(x), + origin_y: 0.0, + width: f64::from(width), + height: f64::from(SIDE), + znear: 0.0, + zfar: 1.0, + } + } + + /// Draws [`PER_PRIMITIVE`]'s three fullscreen triangles with `state` into slices 0 to 2 of a + /// 2D array, through two viewports, its left and right halves, and checks every texel: slice + /// 0 keeps the clear, slice 1 holds triangle 0's word on the left and triangle 1's on the + /// right, and slice 2 triangle 2's on the right, the clear on the left. + fn draw_per_primitive(name: &str, device: &Device, state: &RenderPipelineState) -> u32 { + let what = "per-triangle slices and viewports"; + let ok = |result: Result<(), Error>| { + result.unwrap_or_else(|error| panic!("{name}: {what}: {error}")) + }; + let slices = 3; + let texture = target(device, TextureType::Type2DArray, slices); + let mut d = RenderPassDescriptor::default(); + let c = &mut d.color_attachments[0]; + c.texture = Some(texture.clone()); + c.load_action = LoadAction::Clear; + c.clear_color = ClearColor { + red: f64::from(CLEAR), + green: 0.0, + blue: 0.0, + alpha: 1.0, + }; + d.render_target_array_length = slices; + let mut buffers = Buffers::new(device); + let triangle = [ + [-1.0f32, -1.0, 0.0, 1.0], + [3.0, -1.0, 0.0, 1.0], + [-1.0, 3.0, 0.0, 1.0], + ]; + let positions: Vec = (PER_PRIMITIVE.iter()) + .flat_map(|_| triangle.iter().flatten()) + .flat_map(|v| v.to_le_bytes()) + .collect(); + let positions = buffers.of(device, &positions); + let indices: Vec = (PER_PRIMITIVE.iter()) + .flat_map(|i| i.to_le_bytes()) + .collect(); + let indices = buffers.of(device, &indices); + let queue = device.new_command_queue(4).expect("a queue"); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer.render_command_encoder(&d)) + .unwrap_or_else(|error| panic!("{name}: {what}: {error}")); + let half = SIDE / 2; + ok(encoder.set_render_pipeline_state(state)); + ok(encoder.set_vertex_buffer(Some(&positions), 0, 0)); + ok(encoder.set_vertex_buffer(Some(&indices), 0, 1)); + ok(encoder.set_viewports(&[columns(0, half), columns(half, half)])); + let vertices = 3 * PER_PRIMITIVE.len() as u32; + ok(encoder.draw_primitives(PrimitiveType::Triangle, 0, vertices, 1, 0)); + encoder.end_encoding(); + run(name, &command_buffer); + let [left_1, right_1, right_2] = PER_PRIMITIVE.map(per_primitive_word); + for slice in 0..slices { + let got = words(&texture, slice); + let want: Vec = (0..SIDE * SIDE) + .map(|at| match (slice, at % SIDE < half) { + (1, true) => left_1, + (1, false) => right_1, + (2, false) => right_2, + _ => CLEAR, + }) + .collect(); + assert!( + got == want, + "{name}: {what}: slice {slice} holds {:x?}, Metal's {want:x?}", + got + ); + } + slices * SIDE * SIDE + } + + /// Every device renders Metal's layers, from one form of the vertex function, for a vertex + /// function that writes its slice per instance and one that reads its slice and viewport per + /// triangle from a device buffer. #[test] fn every_device_renders_metal_s_layers() { let Some(layered) = library(&engine_dir().join("rt6_layered.ll")) else { return; }; - let Some(first_vertex) = library(&engine_dir().join("rt6_first_vertex.ll")) else { + let Some(per_primitive) = library(&engine_dir().join("rt6_per_primitive.ll")) else { return; }; let function = |library: &crate::Library, name| { @@ -238,27 +332,22 @@ mod on_device { let texels: u32 = (PASSES.iter()) .map(|pass| draw(name, &device, &layered_state, pass)) .sum(); - let differing = device.new_render_pipeline_state( - &descriptor(&first_vertex, "rt6_first_vertex", "rt6_first_vertex_read"), + let per_primitive_state = (device.new_render_pipeline_state( + &descriptor( + &per_primitive, + "rt6_per_primitive", + "rt6_per_primitive_read", + ), crate::tests::no_constexpr_samplers, - ); - let refused = match differing { - Err(Error::Translation { - error: metal2vulkan::error::Error::Unsupported(u), - .. - }) => { - assert_eq!(u.feature, Feature::LayeredRendering, "{name}: {u:?}"); - u - } - Err(error) => panic!("{name}: rt6_first_vertex: {error}"), - Ok(_) => panic!("{name}: rt6_first_vertex's differing index made a state"), - }; + )) + .unwrap_or_else(|error| panic!("{name}: rt6_per_primitive: {error}")); + let per_triangle = draw_per_primitive(name, &device, &per_primitive_state); println!( "layered: {name}: shaderOutputLayer enabled; {texels} texels of {} passes read \ - Metal's layers; a differing index refused: {:?} needs {:?}", + Metal's layers; {per_triangle} texels of {} triangles read the slice and \ + viewport each read", PASSES.len(), - refused.feature, - refused.needs + PER_PRIMITIVE.len() ); }); } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index ce2b2ff4f..236ab998e 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2282; +pub const SEMANTICS_VERSION: u32 = 2283; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index 3e9a316c2..b52a44b9e 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -1265,9 +1265,8 @@ fn select_entry( widest_pin: simd::WidestPin, m: &mut Meter, ) -> Result { - // The varyings a vertex function writes the same at every vertex of a primitive, which a - // fragment function of its pipeline reads flat where it interpolates them, and which decide - // where it stores the slice and viewport indices it writes. + // The user varyings a vertex function writes the same at every vertex of a primitive, which + // a fragment function of its pipeline reads flat where it interpolates them. if cx.stage == Stage::Vertex { cx.families.stage_io.interface.uniform_outputs = stage_io::uniform_varyings(cx.entry, cx.inputs, m)? diff --git a/crates/metal2vulkan/src/lower/stage_io/mod.rs b/crates/metal2vulkan/src/lower/stage_io/mod.rs index bb9a3efbe..cc5ee6c75 100644 --- a/crates/metal2vulkan/src/lower/stage_io/mod.rs +++ b/crates/metal2vulkan/src/lower/stage_io/mod.rs @@ -79,12 +79,13 @@ //! `uint` varying (`IoRole::ViewportIndex`), which a fragment function compiled under //! `LoweringInputs::viewport_index_varying` reads as its `[[viewport_array_index]]`; any other //! fragment function reads `ViewportIndex` (0 when no stage writes it). -//! - A vertex function stores `Layer` or `ViewportIndex` only where it writes the index the same at -//! every vertex of a primitive, as its structure shows (`StageIo::uniform_outputs`), and the -//! device stores the builtin from a vertex function (`shaderOutputLayer`, -//! `shaderOutputViewportIndex`). One written alike on a device without the output is refused -//! needing it; one not shown alike is refused as not implemented (`plan::index_store`). An index -//! the function declares and never writes (`undef` or `poison` at every return, +//! - A vertex function stores `Layer` or `ViewportIndex` as it writes the index, where the device +//! stores the builtin from a vertex function (`shaderOutputLayer`, `shaderOutputViewportIndex`); +//! on a device without the output it is refused needing it (`plan::index_store`). Metal requires +//! the same value at every vertex of a primitive, and Vulkan the same of `Layer` and +//! `ViewportIndex` (VUID-VkPipelineShaderStageCreateInfo-stage-02596 and -02597); where a +//! function breaks that, Metal gives no answer, and the slice or viewport is the device's choice. +//! An index the function declares and never writes (`undef` or `poison` at every return, //! [`returns_undefined`]) has no value in Metal; it is stored as 0, the same at every vertex //! (`PlannedOutput::unwritten`). On a device without `multiViewport` a draw has one viewport, so //! every index selects viewport 0 and no `ViewportIndex` is stored at all: the raw varying alone. @@ -750,17 +751,13 @@ fn returned_member( None } -/// The varyings vertex function `e`, compiled under `inputs`, writes the same value at every -/// vertex of a primitive (`StageIo::uniform_outputs`), sorted: its user varyings, and the raw -/// varyings of the slice and viewport indices it writes (`VaryingKey::render_target_array_index`, -/// `VaryingKey::viewport_index`), which decide where it stores those indices. At each return, in -/// a block every vertex of a primitive reaches alike, the varying's field of the returned value is -/// uniform +/// The user varyings vertex function `e`, compiled under `inputs`, writes the same value at every +/// vertex of a primitive (`StageIo::uniform_outputs`), sorted. At each return, in a block every +/// vertex of a primitive reaches alike, the varying's field of the returned value is uniform /// among those vertices (`simd::uniform::Among::Primitive`), computed only from constants, /// `constant` memory read through uniform pointers, the draw's instance, base vertex, base /// instance, amplification and patch, and the vertex attributes `inputs` fetches per instance or -/// at a constant step; or the field is an index the function never writes ([`returns_undefined`]), -/// which is stored as 0. Decided from the structure of the specialized entry alone, never from a +/// at a constant step. Decided from the structure of the specialized entry alone, never from a /// name. Empty for every other stage. pub(crate) fn uniform_varyings( e: &crate::air::Entry, @@ -782,10 +779,6 @@ pub(crate) fn uniform_varyings( .iter() .filter_map(|o| match &o.role { OutputRole::VertexOutput(key) => Some((o.field, VaryingKey::user(&key.0))), - OutputRole::RenderTargetArrayIndex => { - Some((o.field, VaryingKey::render_target_array_index())) - } - OutputRole::ViewportArrayIndex => Some((o.field, VaryingKey::viewport_index())), _ => None, }) .collect(); @@ -881,14 +874,9 @@ pub(crate) fn uniform_varyings( false }; for (field, key) in fields { - // An index the function never writes is stored as 0 at every return - // (`PlannedOutput::unwritten`). - let index = - key == VaryingKey::render_target_array_index() || key == VaryingKey::viewport_index(); if returns .iter() .all(|&(b, v)| u.is_uniform(b) && member(v, field)) - || (index && returns_undefined(e, field)) { out.insert(key); } diff --git a/crates/metal2vulkan/src/lower/stage_io/plan.rs b/crates/metal2vulkan/src/lower/stage_io/plan.rs index 5215db2d5..f0c20f1a1 100644 --- a/crates/metal2vulkan/src/lower/stage_io/plan.rs +++ b/crates/metal2vulkan/src/lower/stage_io/plan.rs @@ -1112,7 +1112,7 @@ fn amplified_output(cx: &mut SelectCx<'_>, index: AmplifiedIndex) -> Result<(), PushField::ViewportCount, ), }; - let store = index_store(cx, raw, true, true)?; + let store = index_store(cx, raw, true)?; if store == IndexStore::Nowhere { return Ok(()); } @@ -1397,28 +1397,24 @@ enum IndexStore { Nowhere, } -/// Where a vertex function on `cx`'s profile stores index `index`, which it writes the same at -/// every vertex of a primitive where `uniform` ([`uniform_index`]): to its builtin where the -/// profile enables `shaderOutputLayer` (`shaderOutputViewportIndex` for a viewport index) and -/// the function writes the index alike, and nowhere, a viewport index on a profile without -/// `multiViewport`. Otherwise refused, as `VertexAmplification` for an index the function stores -/// from the amplification's offset alone (`amplification`), else as `LayeredRendering`: one -/// written alike needing the output feature, one not shown alike as not implemented on any -/// device. +/// Where a vertex function on `cx`'s profile stores index `index`: to its builtin, as the function +/// writes it, where the profile enables `shaderOutputLayer` (`shaderOutputViewportIndex` for a +/// viewport index), and nowhere, a viewport index on a profile without `multiViewport`. Otherwise +/// refused as needing the output feature, as `VertexAmplification` for an index the function +/// stores from the amplification's offset alone (`amplification`), else as `LayeredRendering`. /// -/// An index not shown alike is refused because Metal gives it no answer to match: "You must -/// return the same value of `[[render_target_array_index]]` for every vertex in a primitive. If -/// values differ, the behavior and value passed to the fragment function are undefined." (the -/// Metal Shading Language specification, and the same of `[[viewport_array_index]]`). It is not -/// stored to its builtin as written because Vulkan asks a stage that writes `Layer` to "write the -/// same value to Layer for all vertices of a given primitive" +/// Metal and Vulkan ask the same of the value: "You must return the same value of +/// `[[render_target_array_index]]` for every vertex in a primitive. If values differ, the behavior +/// and value passed to the fragment function are undefined." (the Metal Shading Language +/// specification, and the same of `[[viewport_array_index]]`); a stage that writes `Layer` must +/// "write the same value to Layer for all vertices of a given primitive" /// (VUID-VkPipelineShaderStageCreateInfo-stage-02596), and the same of `ViewportIndex` -/// (VUID-VkPipelineShaderStageCreateInfo-stage-02597), which the function's structure does not -/// show of it. +/// (VUID-VkPipelineShaderStageCreateInfo-stage-02597). A function that keeps Metal's rule keeps +/// Vulkan's with the index stored as written; where it breaks it, Metal gives no answer, and the +/// slice or viewport is the device's choice. fn index_store( cx: &SelectCx<'_>, index: RawIndex, - uniform: bool, amplification: bool, ) -> Result { let f = cx.profile.fields(); @@ -1429,7 +1425,7 @@ fn index_store( VkFeature::ShaderOutputViewportIndex, ), }; - if native && uniform { + if native { return Ok(IndexStore::Builtin); } if matches!(index, RawIndex::Viewport) @@ -1437,31 +1433,13 @@ fn index_store( { return Ok(IndexStore::Nowhere); } - // An index stored from the amplification's offset alone is the same at every vertex. - if amplification { - return Err( - Unsupported::needs(Feature::VertexAmplification, Capability::Feature(output)).into(), - ); - } - Err(match uniform { - true => Unsupported::needs(Feature::LayeredRendering, Capability::Feature(output)), - false => Unsupported::not_implemented(Feature::LayeredRendering), + Err(match amplification { + true => Unsupported::needs(Feature::VertexAmplification, Capability::Feature(output)), + false => Unsupported::needs(Feature::LayeredRendering, Capability::Feature(output)), } .into()) } -/// Whether vertex function `cx` writes index `index` the same at every vertex of a primitive -/// (its raw varying is among `StageIo::uniform_outputs`). -fn uniform_index(cx: &SelectCx<'_>, index: RawIndex) -> bool { - let key = match index { - RawIndex::Layer => VaryingKey::render_target_array_index(), - RawIndex::Viewport => VaryingKey::viewport_index(), - }; - (cx.families.stage_io.interface.uniform_outputs) - .binary_search(&key) - .is_ok() -} - /// Whether the profile can declare fragment input builtin `b`: one of its enabling /// capabilities' features ([`builtin_enablers`]) is enabled. fn declarable(cx: &SelectCx<'_>, b: crate::spv::BuiltIn) -> bool { @@ -2180,12 +2158,7 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { // time, it holds the index plus the amplification's offset. if matches!(o.role, OutputRole::ViewportArrayIndex) && cx.stage == Stage::Vertex - && index_store( - cx, - RawIndex::Viewport, - uniform_index(cx, RawIndex::Viewport), - false, - )? == IndexStore::Nowhere + && index_store(cx, RawIndex::Viewport, false)? == IndexStore::Nowhere { let f = io_form(cx, ty)?; int_scalar(f)?; @@ -2750,8 +2723,7 @@ fn output(cx: &mut SelectCx<'_>, o: &OutputBinding, ty: AirTypeId) -> Result, - /// The varyings a vertex function writes the same value at every vertex of a primitive, + /// The user varyings a vertex function writes the same value at every vertex of a primitive, /// sorted: computed only from constants, `constant` memory read through uniform pointers, the /// draw's instance, base vertex, base instance, amplification and patch, and the attributes /// it fetches per instance or at a constant step, never from `[[vertex_id]]` or another - /// per-vertex input. A fragment function of its pipeline reads those of its user varyings it - /// interpolates flat ([`uniform_inputs`](StageIo::uniform_inputs)). The raw varyings of the - /// slice and viewport indices it writes are among them so - /// (`VaryingKey::render_target_array_index`, `VaryingKey::viewport_index`): Vulkan takes - /// `Layer` and `ViewportIndex` from a vertex function only where every vertex of a primitive - /// stores the same, so an index that is not among them is refused. Empty for every other - /// function. + /// per-vertex input. A fragment function of its pipeline reads those it interpolates flat + /// ([`uniform_inputs`](StageIo::uniform_inputs)). Empty for every other function. #[cfg_attr(feature = "serde", serde(default))] pub uniform_outputs: Vec, /// The `float` and `half` varyings the fragment function reads flat although it states an diff --git a/crates/metal2vulkan/src/tests/engine_amplification.rs b/crates/metal2vulkan/src/tests/engine_amplification.rs index 5ccbb943b..df49a2e1c 100644 --- a/crates/metal2vulkan/src/tests/engine_amplification.rs +++ b/crates/metal2vulkan/src/tests/engine_amplification.rs @@ -41,7 +41,7 @@ use crate::pipeline::link::{link, LinkInputs}; use crate::pipeline::lower_inputs::LoweringInputs; use crate::pipeline::relocate::relocate; use crate::pipeline::stage_io::StageBuiltin; -use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, SpecKey, Stage, VaryingKey}; +use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, SpecKey, Stage}; use crate::pipeline::testing::{ compile, engine_dir, fixtures_dir, llvm_assemble, moltenvk_msl_compile, profile, typed_module, typed_module_with, AssembleError, @@ -191,8 +191,8 @@ fn amplification_id_needs_multiview() { /// 0, not `ViewIndex`: SPIRV-Cross gives a vertex function that reads `ViewIndex` a second /// `[[render_target_array_index]]` output, which Metal refuses (authored case 013406ac failed /// MoltenVK pipeline creation so). Without `ViewIndex` it needs neither `MultiView` nor -/// `multiview`. Each fixture's slice is the same at every vertex of a primitive, so it is stored -/// to `Layer`, and its `moltenvk-m3` module compiles as MoltenVK's MSL. +/// `multiview`. Each fixture's slice is stored to `Layer`, and its `moltenvk-m3` module compiles +/// as MoltenVK's MSL. #[test] fn a_vertex_function_writing_its_slice_reads_amplification_id_zero() { let Some(bc) = fixture() else { return }; @@ -225,15 +225,6 @@ fn a_vertex_function_writing_its_slice_reads_amplification_id_zero() { "{entry}: {:?}", a.interface.io.builtins ); - // Each slice (`slices[iid & 1]`, and the other's) is the same at every vertex of a - // primitive, and is stored to `Layer`. - assert!( - a.interface - .io - .uniform_outputs - .contains(&VaryingKey::render_target_array_index()), - "{entry}" - ); assert!( a.interface.io.builtins.contains(&StageBuiltin::Layer), "{entry}" diff --git a/crates/metal2vulkan/src/tests/engine_render_target_slice.rs b/crates/metal2vulkan/src/tests/engine_render_target_slice.rs index 418777477..ca89d37c7 100644 --- a/crates/metal2vulkan/src/tests/engine_render_target_slice.rs +++ b/crates/metal2vulkan/src/tests/engine_render_target_slice.rs @@ -123,7 +123,7 @@ fn a_fragment_reads_the_slice_index_its_vertex_function_wrote() { VaryingKey::render_target_array_index(), "{what}" ); - // Its slice is the same at every vertex of a primitive: the function stores it as `Layer`. + // The function stores its slice as `Layer`. assert!(io.builtins.contains(&StageBuiltin::Layer), "{what}"); let keys = dev diff --git a/docs/API.md b/docs/API.md index 003c6e6a3..24f202b95 100644 --- a/docs/API.md +++ b/docs/API.md @@ -908,20 +908,17 @@ Where Metal's rules differ from Vulkan's, the pipeline gives Metal's answer: first two weights and computes the third as `1 - (x + y)` in `float`, as Metal does, not the device's own third lane. On a device without `fragmentShaderBarycentric` the function is refused, `Unsupported{Barycentrics}` needing the feature. -- A vertex function stores `Layer` or `ViewportIndex` only where it writes the index the same at - every vertex of a primitive, decided from its structure (computed from constants, `constant` - memory, the instance, the amplification and per-instance attributes, as - `StageIo::uniform_outputs` lists), on a device with `shaderOutputLayer` or - `shaderOutputViewportIndex`. Metal leaves a primitive whose vertices write different indices - undefined ("If values differ, the behavior and value passed to the fragment function are - undefined.", the Metal Shading Language specification), and Vulkan asks every vertex of a - primitive to write the same `Layer` and `ViewportIndex` - (VUID-VkPipelineShaderStageCreateInfo-stage-02596 and -02597), so a vertex function whose index - is not shown the same is refused, `NotImplemented(LayeredRendering)`. One shown the same on a - device without the output is refused needing it, as `Unsupported(LayeredRendering)`, or as - `Unsupported(VertexAmplification)` for an index the amplification's offset alone sets. An index - the function declares and never writes (`undef` in every value it returns), which Metal gives no - value, is stored as 0, the same at every vertex. The stored `Layer` is 0 at or past the pass's +- A vertex function stores `Layer` or `ViewportIndex` as it writes the index, on a device with + `shaderOutputLayer` or `shaderOutputViewportIndex`; on a device without the output it is + refused needing it, as `Unsupported(LayeredRendering)`, or as + `Unsupported(VertexAmplification)` for an index the amplification's offset alone sets. Metal + requires the same value at every vertex of a primitive ("If values differ, the behavior and + value passed to the fragment function are undefined.", the Metal Shading Language + specification), and Vulkan the same of `Layer` and `ViewportIndex` + (VUID-VkPipelineShaderStageCreateInfo-stage-02596 and -02597); where a program breaks that, the + layer or viewport is the device's choice (section 10). An index the function declares and never + writes (`undef` in every value it returns), which Metal gives no value, is stored as 0, the same + at every vertex. The stored `Layer` is 0 at or past the pass's length, which each draw pushes, so in a pass of one layer every index renders slice 0, as Metal's does. A device without `multiViewport` draws through one viewport, so there the vertex function stores no viewport index at all; a draw that selects among more than one viewport @@ -2389,6 +2386,12 @@ named states the rule in full. **Draws** +- **A vertex function's `[[render_target_array_index]]` and `[[viewport_array_index]]` are stored + as the function writes them.** Metal requires the same value at every vertex of a primitive; + where a program breaks that, the layer or viewport is the device's choice. Metal leaves such a + primitive undefined (the Metal Shading Language specification), and Vulkan asks the same value + of `Layer` and `ViewportIndex` at every vertex of a primitive + (VUID-VkPipelineShaderStageCreateInfo-stage-02596 and -02597). - **A point near the viewport's edge or the clip volume is clipped or culled by the device's own rule**: its `pointClippingBehavior` and the driver's handling of the viewport. Metal states no clipping rule for a point (`MTLPrimitiveType.point`; the MSL specification's `[[point_size]]`). diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index a8afe98a2..f28b9da63 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -39,7 +39,7 @@ Columns: | Kind | `metal-measured` | `metal-documented` | `metal-takes` | `device` | `ours` | `unknown` | `delegated` | `-` | |---|---|---|---|---|---|---|---|---| -| Translator and front-end refusals | 0 | 0 | 0 | 44 | 70 | 0 | 0 | 5 | +| Translator and front-end refusals | 0 | 0 | 0 | 45 | 69 | 0 | 0 | 5 | | Translation caps | 0 | 0 | 0 | 0 | 14 | 0 | 0 | 0 | | Rate maps the compile layer does not compile | 0 | 0 | 0 | 0 | 5 | 0 | 0 | 0 | | The translation deadline | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | @@ -112,7 +112,7 @@ Columns: | `PrimitiveId` | `[[primitive_id]]` in a fragment function | devices without a capability the site computes; every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/lower/stage_io/plan.rs (finish)`, `crates/metal2vulkan/src/pipeline/link/varyings.rs (check_primitive_id)` | `rare`: primitive_id on a device without geometry or tessellation shaders, in an indexed draw or behind a mesh function | | `PrivatePrimitives` | One of Metal's private primitive types (a line loop, a triangle fan, quads, a quad strip) drawn in the pulled list form... | devices without buffer device addresses (`addressed_needs`); every device (not implemented) | `ours` | via a helper: 1: `crates/metal2vulkan/src/lower/stage_io/plan.rs (indices_feature)` | `rare`: a private primitive type drawn in the pulled list form (a vertex function that writes memory or the primitive_id varying, a vertex start past 2^31) on a device without device addresses | | `VertexAmplification` | Vertex amplification | devices short of a Vulkan feature the site names; devices without VkFeature::Multiview; devices without VkFeature::MultiviewTessellationShader; every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store)`, `crates/metal2vulkan/src/lower/tessellation/mod.rs (select_param)` (+2) | `rare`: vertex amplification | -| `LayeredRendering` | Layered rendering (`render_target_array_index`, `viewport_array_index`) | devices short of a Vulkan feature the site names; devices without VkFeature::ShaderOutputLayer; devices without VkFeature::ShaderOutputViewportIndex; every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/lower/mesh/mod.rs (target_index, 2 sites)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store, 2 sites)` | `rare`: layered rendering on a device without its features | +| `LayeredRendering` | Layered rendering (`render_target_array_index`, `viewport_array_index`) | devices short of a Vulkan feature the site names; devices without VkFeature::ShaderOutputLayer; devices without VkFeature::ShaderOutputViewportIndex | `device` | 3: `crates/metal2vulkan/src/lower/mesh/mod.rs (target_index, 2 sites)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store)` | `rare`: layered rendering on a device without its features | | `ClipDistance` | Clip or cull distances | devices without VkFeature::ShaderClipDistance; devices without VkLimit::MaxClipDistances | `device` | 2: `crates/metal2vulkan/src/lower/mesh/mod.rs (select, 2 sites)` | `rare`: clip distances on a device without them | | `DualSourceBlending` | Dual-source blending | devices without VkFeature::DualSrcBlend; devices without VkLimit::MaxFragmentDualSrcAttachments | `device` | 3: `crates/metal2vulkan/src/metal/state.rs (blend_factor)`, `crates/metal2vulkan/src/pipeline/link/graphics.rs (check_outputs)` (+1) | `rare`: dual-source blending on a device without it | | `Barycentrics` | Barycentric coordinates | devices without VkFeature::FragmentShaderBarycentric | `device` | 2: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`, `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)` | `rare`: barycentric coordinates | @@ -430,7 +430,7 @@ Each refusal's sites, with the function that builds it. - `feature::PrimitiveId`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (finish)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs (check_primitive_id)` - `feature::PrivatePrimitives`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (indices_feature)` - `feature::VertexAmplification`: `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs (select_param)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (vertex_amplification)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs (control_plan)` -- `feature::LayeredRendering`: `crates/metal2vulkan/src/lower/mesh/mod.rs (target_index, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store, 2 sites)` +- `feature::LayeredRendering`: `crates/metal2vulkan/src/lower/mesh/mod.rs (target_index, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (index_store)` - `feature::ClipDistance`: `crates/metal2vulkan/src/lower/mesh/mod.rs (select, 2 sites)` - `feature::DualSourceBlending`: `crates/metal2vulkan/src/metal/state.rs (blend_factor)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (check_outputs)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs (rotated_blend)` - `feature::Barycentrics`: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (param)`