From 80ecfdab4acfec5ff74061e0ee3f1bd923dd6335 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 26 Nov 2026 20:25:14 -0800 Subject: [PATCH] Runtime: draw a state whose colours past the pass's last attachment the pass lacks A pipeline state that names colours past its pass's last colour attachment, its formats up to that attachment, its depth and stencil formats and its raster sample count all the pass's, was refused at the draw as DrawKind::AttachmentFormats. Plain Metal draws it (pass-pipeline-color-unattached, the Apple M3 Max, job m3-max-75903): the attachments it has hold the fragment's values, and its validation alone stops it. set_render_pipeline_state now binds, for such a pass, the state of the descriptor without those colours (RenderPipelineState::without_colors): a content of its own in the device's map of contents, lowered on the calling thread where the device holds none, its fragment function storing those colours nowhere as for any descriptor that leaves them unset, its samplers numbered at the state's indices, and its pipeline made by its first draw (a first-use wait). That content renders into the pass under the exact match draws already take, so no new attachment rule enters a pipeline's make. A state that renders into its pass takes the same path as before: one renders_into and the lend. Each state now keeps the descriptor it was made of. A colour the state names before the pass's last colour attachment that the pass leaves unset stays refused: plain Metal writes the next colour's value into the attachment after it (pass-pipeline-color-unattached-between, job m3-max-75934). So do another format, a depth or stencil format the pass lacks and another sample count. Test: tests/unattached_colors.rs. Verified: formatted only; the device runs follow. --- crates/metal2vulkan-runtime/src/error.rs | 13 +- crates/metal2vulkan-runtime/src/render.rs | 87 +++++- .../src/render_encoder.rs | 34 ++- crates/metal2vulkan-runtime/src/tests/mod.rs | 1 + .../src/tests/unattached_colors.rs | 261 ++++++++++++++++++ 5 files changed, 387 insertions(+), 9 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/unattached_colors.rs diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 9bb609310..395368f9b 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1794,10 +1794,15 @@ pub enum DrawKind { /// A viewport Vulkan's is not: a negative width (Metal mirrors the draw), a depth range past /// `[0, 1]`, or bounds past the device's viewport limits. Viewport, - /// A pipeline state whose colour or stencil formats are not its pass's attachments', or - /// whose `rasterSampleCount` is not their sample count: Metal's validation stops most such - /// draws, and plain Metal zeroes or drops the colours. Vulkan draws no other count - /// (VUID-vkCmdDraw-multisampledRenderToSingleSampled-07285). + /// A pipeline state whose colour, depth or stencil formats are not its pass's attachments', + /// or whose `rasterSampleCount` is not their sample count: Metal's validation stops such + /// draws. A colour the state names between two its pass attaches, the pass leaving it unset, + /// is among them: plain Metal writes the next colour's value into the attachment after it + /// (`pass-pipeline-color-unattached-between`, an Apple M3 Max under macOS 27.0.1, job + /// m3-max-75934). Vulkan draws no other sample count + /// (VUID-vkCmdDraw-multisampledRenderToSingleSampled-07285). A state whose colours past the + /// pass's last colour attachment are the only difference is drawn, as plain Metal draws it + /// ([`RenderCommandEncoder::set_render_pipeline_state`](crate::RenderCommandEncoder::set_render_pipeline_state)). AttachmentFormats, /// A draw that binds a texture whose image the pass renders, where neither the attachment /// feedback loop nor a copy into the image's shadow reads it: on a device without the diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index ff7cfbaff..8d9480c8f 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -116,6 +116,10 @@ pub(crate) struct RenderInner { pub(crate) compiled: Arc, /// The samplers the state numbers and the indices the consumer gave them. pub(crate) numbered: Numbered, + /// The descriptor the state was made of, whose functions keep their library: the content of + /// a pass that lacks colours past its last colour attachment is made of it + /// ([`RenderPipelineState::without_colors`]). + descriptor: RenderPipelineDescriptor, } /// The vertex function's index in a draw's tables, and the fragment function's. @@ -583,7 +587,11 @@ impl crate::Device { draw_input, )?; Ok(RenderPipelineState { - inner: Arc::new(RenderInner { compiled, numbered }), + inner: Arc::new(RenderInner { + compiled, + numbered, + descriptor: descriptor.clone(), + }), }) } } @@ -1409,6 +1417,32 @@ impl RenderCompiled { && fixed.samples == pass.samples } + /// The colours of the content `pass` has no attachment for, one bit an index, where the + /// content renders into the pass but for them and each lies past the pass's last colour + /// attachment: its colour formats up to the pass's last colour attachment are the pass's, its + /// depth and stencil formats and its raster sample count too, and it names a colour past + /// them. `None` otherwise, a colour it names before the pass's last colour attachment that the + /// pass leaves unset among them: there plain Metal writes the next colour's value into the + /// attachment after the unset one (`pass-pipeline-color-unattached-between`, an Apple M3 Max + /// under macOS 27.0.1, job m3-max-75934), a draw [`DrawKind::AttachmentFormats`] refuses. + /// + /// [`DrawKind::AttachmentFormats`]: crate::DrawKind::AttachmentFormats + pub(crate) fn lacked_past(&self, pass: &Pass) -> Option { + let fixed = &self.fixed; + let format = |t: Option<&crate::pass::Target>| { + t.map_or(vk::Format::UNDEFINED, |t| t.attachment.format) + }; + let (within, past) = fixed.colors.split_at_checked(pass.colors.len())?; + let renders = (within.iter().zip(&pass.colors)).all(|(&f, t)| f == format(t.as_ref())) + && fixed.depth == format(pass.depth.as_ref()) + && fixed.stencil == format(pass.stencil.as_ref()) + && fixed.samples == pass.samples; + let lacked = (past.iter().enumerate()) + .filter(|(_, &f)| f != vk::Format::UNDEFINED) + .fold(0u8, |bits, (at, _)| bits | 1 << (pass.colors.len() + at)); + (renders && lacked != 0).then_some(lacked) + } + /// A `VkPipeline` of the content for draws of the class of `topology`, a list topology, under /// `raster`, made through the device's pipeline data, rendering dynamically into the /// descriptor's attachment formats. A draw sets its own topology within the class as dynamic @@ -1528,7 +1562,58 @@ fn release(core: &Core, stages: &[Module]) { } } +#[cfg(test)] +thread_local! { + /// The calls of [`RenderPipelineState::without_colors`] on this thread, each of which takes the + /// translator's key of a descriptor and a lookup of the device's map of contents, which a test + /// reads. + pub(crate) static WITHOUT_COLORS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + impl RenderPipelineState { + /// The state of this state's descriptor with the colours of `lacked` (one bit an index) + /// unset, for a pass that has no attachment for them ([`RenderCompiled::lacked_past`]): a + /// content of its own, which the device's map of contents holds as any content, and which the + /// calling thread makes where the device holds none, its functions lowered again, the fragment + /// function storing those colours nowhere as for any descriptor that leaves them unset. Its + /// samplers are numbered at this state's indices; its `VkPipeline` is made by the first draw + /// (a first-use wait, `Metrics::first_use_unfinished_waits`). + /// + /// Err: as [`new_render_pipeline_state`](crate::Device::new_render_pipeline_state); + /// [`DrawKind::AttachmentFormats`](crate::DrawKind::AttachmentFormats) where that content + /// numbers other samplers or does not render into `pass`. + pub(crate) fn without_colors( + &self, + device: &crate::Device, + lacked: u8, + pass: &Pass, + ) -> Result { + #[cfg(test)] + WITHOUT_COLORS.with(|calls| calls.set(calls.get() + 1)); + let refused = || { + Error::Unsupported(Gap::Draw { + kind: crate::DrawKind::AttachmentFormats, + }) + }; + let mut descriptor = self.inner.descriptor.clone(); + for (at, color) in descriptor.color_attachments.iter_mut().enumerate() { + if lacked & 1 << at != 0 { + *color = None; + } + } + let numbered = (&self.inner.compiled.numbered, &self.inner.numbered.ids); + let state = device.render_pipeline_state(&descriptor, |samplers| { + match samplers == numbered.0.as_slice() { + true => Ok(numbered.1.clone()), + false => Err(refused()), + } + })?; + match state.inner.compiled.renders_into(pass) { + true => Ok(state), + false => Err(refused()), + } + } + /// No Metal counterpart: makes the state's main `VkPipeline`s on the calling thread, through /// the device's pipeline cache, once the state's creation has answered. Metal compiles a /// render state when the state is made. Here the creation does everything up to the driver's diff --git a/crates/metal2vulkan-runtime/src/render_encoder.rs b/crates/metal2vulkan-runtime/src/render_encoder.rs index 4081f6a27..88405a427 100644 --- a/crates/metal2vulkan-runtime/src/render_encoder.rs +++ b/crates/metal2vulkan-runtime/src/render_encoder.rs @@ -957,7 +957,16 @@ impl RenderCommandEncoder { /// `setRenderPipelineState:`. The command buffer keeps the state until it retires. /// - /// Err: [`Refusal::OtherDevice`] for another device's state. + /// A state that names colours past the pass's last colour attachment, its formats up to that + /// attachment, its depth and stencil formats and its raster sample count all the pass's, + /// draws through the state of its descriptor without those colours, as plain Metal draws it + /// (Metal's validation stops it): one key of that descriptor and a lookup of the device's + /// contents at each such call, and that content's translation where the device holds none. + /// A state that renders into the pass takes neither. + /// + /// Err: [`Refusal::OtherDevice`] for another device's state; the error of making the state + /// without those colours (as `new_render_pipeline_state`), whose draws the encoder then + /// refuses as `DrawKind::AttachmentFormats`. pub fn set_render_pipeline_state(&mut self, state: &RenderPipelineState) -> Result<(), Error> { if !state.is_of(self.building().device.core()) { return Err(Error::Refused(Refusal::OtherDevice)); @@ -966,10 +975,27 @@ impl RenderCommandEncoder { return Ok(()); } self.renders_into = state.inner.compiled.renders_into(&self.pass); - // SAFETY: the encoder holds the borrow, and it ends before its command buffer commits. - self.pipeline = Some(unsafe { self.building().lend_render_pipeline(state) }); + let lacked = match self.renders_into { + true => None, + false => state.inner.compiled.lacked_past(&self.pass), + }; + let Some(lacked) = lacked else { + // SAFETY: the encoder holds the borrow, and it ends before its command buffer commits. + self.pipeline = Some(unsafe { self.building().lend_render_pipeline(state) }); + self.changed(); + return Ok(()); + }; + let building = (self.building.as_ref()) + .expect("an encoder holds its command buffer's recording until it ends"); + let (drawn, failed) = match state.without_colors(&building.device, lacked, &self.pass) { + Ok(made) => (made, None), + Err(error) => (state.clone(), Some(error)), + }; + self.renders_into = failed.is_none(); + // SAFETY: as above. + self.pipeline = Some(unsafe { self.building().lend_render_pipeline(&drawn) }); self.changed(); - Ok(()) + failed.map_or(Ok(()), Err) } /// `setVertexBuffer:offset:atIndex:` (`setVertexBuffers:offsets:withRange:` is a loop of it). diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 26ff9a63c..0b99665ef 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -134,6 +134,7 @@ mod texture_accesses; mod texture_buffers; mod translate; mod translator_fields; +mod unattached_colors; mod upload; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod validation; diff --git a/crates/metal2vulkan-runtime/src/tests/unattached_colors.rs b/crates/metal2vulkan-runtime/src/tests/unattached_colors.rs new file mode 100644 index 000000000..be3fb742c --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/unattached_colors.rs @@ -0,0 +1,261 @@ +//! A pipeline state that names colours its pass has no attachment for +//! (`RenderCompiled::lacked_past`), under a device cfg on every device of the cfg's kind. +//! +//! - A state of colour 0 `BGRA8Unorm` and colour 1 `RG16Float` over `rt6_pair_two` (engine +//! `rt6_pair`: colour 0 from fragment buffer 0 at the fragment's texel, colour 1 from buffer 2) +//! draws in a pass of colour 0 alone, as plain Metal draws it (the conformance case +//! `pass-pipeline-color-unattached`): through the state of its descriptor without colour 1, +//! whose content the first such set makes and whose `VkPipeline` the first draw makes, a +//! first-use wait. Colour 0 holds the fragment's codes in the scissor's rows and the clear in the +//! others. A second encoder's set takes the content the device holds: no translation and no +//! pipeline. Draws of the state in a pass of both colours, before it, make no such state at all. +//! - A state of three colours over `cg_five` (engine `color_groups`) in a pass of colours 0 and 2 +//! is refused, `DrawKind::AttachmentFormats`: there plain Metal writes colour 1's value into +//! colour 2's attachment (`pass-pipeline-color-unattached-between`). +//! - The lacking state is refused in a pass whose colour 0 is another format, in a pass with a +//! depth attachment, and at a raster sample count other than the pass's. + +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod on_device { + use crate::render::WITHOUT_COLORS; + use crate::tests::command::on_device::each_device; + use crate::tests::draw::on_device::{floats, library, read, run, state, target, Buffers, SIDE}; + use crate::{ + ColorAttachmentDescriptor, DrawKind, Error, FunctionDescriptor, Gap, Library, LoadAction, + PixelFormat, PrimitiveType, RenderPassDescriptor, RenderPipelineDescriptor, ScissorRect, + StageSource, StorageMode, Texture, TextureDescriptor, TextureType, TextureUsage, + }; + use metal2vulkan_devtools::engine_dir; + + /// The codes colour 0's buffer gives texel `at`, `(r, g, b, a)`. + fn codes(at: u32) -> [u32; 4] { + [64 + at, 128 + at, 192 + at, at] + } + + /// The clear colour 0 takes, as codes. + const CLEAR: [u32; 4] = [3, 5, 7, 250]; + + /// The rows the draw is confined to: the top half. + fn rows() -> ScissorRect { + ScissorRect { + x: 0, + y: 0, + width: u64::from(SIDE), + height: u64::from(SIDE / 2), + } + } + + /// A state of `vertex` and `fragment` of `library` over `colors`, by index, at `samples`. + fn descriptor( + library: &Library, + (vertex, fragment): (&str, &str), + colors: &[Option], + samples: u32, + ) -> RenderPipelineDescriptor { + let function = |name| { + StageSource::Function(FunctionDescriptor::new( + library.function(name).expect("the function"), + )) + }; + let mut d = RenderPipelineDescriptor::new(function(vertex)); + d.fragment = Some(function(fragment)); + for (at, format) in colors.iter().enumerate() { + d.color_attachments[at] = format.map(ColorAttachmentDescriptor::new); + } + d.raster_sample_count = samples; + d + } + + /// A pass of `colors`, by index (`None` unset), each cleared to [`CLEAR`]. + fn pass(colors: &[Option<&Texture>]) -> RenderPassDescriptor { + let mut d = RenderPassDescriptor::default(); + for (at, texture) in colors.iter().enumerate() { + let c = &mut d.color_attachments[at]; + c.texture = texture.cloned(); + c.load_action = LoadAction::Clear; + c.clear_color = crate::ClearColor { + red: f64::from(CLEAR[0]) / 255.0, + green: f64::from(CLEAR[1]) / 255.0, + blue: f64::from(CLEAR[2]) / 255.0, + alpha: f64::from(CLEAR[3]) / 255.0, + }; + } + d + } + + #[test] + fn every_device_draws_a_state_whose_last_colour_its_pass_lacks_and_refuses_the_rest() { + let (Some(pair), Some(groups)) = ( + library(&engine_dir().join("rt6_pair.ll")), + library(&engine_dir().join("color_groups.ll")), + ) else { + return; + }; + let two = [Some(PixelFormat::BGRA8Unorm), Some(PixelFormat::RG16Float)]; + let pair_fns = ("rt6_pair_vertex", "rt6_pair_two"); + let lacking = descriptor(&pair, pair_fns, &two, 1); + let multisampled = descriptor(&pair, pair_fns, &two, 4); + let three = [ + Some(PixelFormat::BGRA8Unorm), + Some(PixelFormat::RG16Float), + Some(PixelFormat::RGBA8Unorm), + ]; + let between = descriptor(&groups, ("cg_cover", "cg_five"), &three, 1); + each_device("unattached_colors", |name, _, device| { + let state = state(name, &device, &lacking); + let between = self::state(name, &device, &between); + let mut buffers = Buffers::new(&device); + let zeros: Vec = (0..SIDE * SIDE) + .flat_map(|at| codes(at).map(|code| code as f32 / 255.0)) + .collect(); + let zeros = buffers.of(&device, &floats(&zeros)); + let width = buffers.of(&device, &SIDE.to_le_bytes()); + let ones = buffers.of(&device, &floats(&[0.5; (4 * SIDE * SIDE) as usize])); + let colour = |format| target(&device, format, TextureUsage::RENDER_TARGET); + let queue = device.new_command_queue(4).expect("a queue"); + let fail = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); + let refused = Err::<(), _>(Error::Unsupported(Gap::Draw { + kind: DrawKind::AttachmentFormats, + })); + let same = |got: Result<(), Error>, case: &str| { + assert_eq!(format!("{got:?}"), format!("{refused:?}"), "{name}: {case}"); + }; + let counters = device.counters(); + let calls = || WITHOUT_COLORS.with(std::cell::Cell::get); + + // Draws that render into their pass: no state without colours is asked for. + let (zero, one) = ( + colour(PixelFormat::BGRA8Unorm), + colour(PixelFormat::RG16Float), + ); + let before = (counters.metrics(), calls()); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer + .render_command_encoder(&pass(&[Some(&zero), Some(&one)]))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + for _ in 0..4 { + fail(encoder.set_render_pipeline_state(&state)); + fail(encoder.set_fragment_buffer(Some(&zeros), 0, 0)); + fail(encoder.set_fragment_buffer(Some(&width), 0, 1)); + fail(encoder.set_fragment_buffer(Some(&ones), 0, 2)); + fail(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0)); + } + encoder.end_encoding(); + run(name, &command_buffer); + let after = (counters.metrics(), calls()); + assert_eq!( + ( + after.1 - before.1, + after.0.translations - before.0.translations, + after.0.pipelines_created - before.0.pipelines_created, + ), + (0, 0, 0), + "{name}: matching draws: states without colours asked for, translations, \ + pipelines made" + ); + + // The pass of colour 0 alone, twice, each in an encoder of its own. + let targets = [ + colour(PixelFormat::BGRA8Unorm), + colour(PixelFormat::BGRA8Unorm), + ]; + let mut each = Vec::new(); + for target in &targets { + let before = (counters.metrics(), calls()); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = (command_buffer.render_command_encoder(&pass(&[Some(target)]))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + fail(encoder.set_render_pipeline_state(&state)); + fail(encoder.set_fragment_buffer(Some(&zeros), 0, 0)); + fail(encoder.set_fragment_buffer(Some(&width), 0, 1)); + fail(encoder.set_fragment_buffer(Some(&ones), 0, 2)); + encoder.set_scissor_rect(rows()); + fail(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0)); + fail(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0)); + encoder.end_encoding(); + run(name, &command_buffer); + let after = (counters.metrics(), calls()); + each.push(( + after.1 - before.1, + after.0.translations > before.0.translations, + after.0.pipelines_created - before.0.pipelines_created, + after.0.first_use_unfinished_waits - before.0.first_use_unfinished_waits, + )); + } + assert_eq!( + each, + vec![(1, true, 1, 1), (1, false, 0, 0)], + "{name}: each lacking pass: states without colours asked for, whether it lowered a \ + function, pipelines made, first-use waits" + ); + let want: Vec = (0..SIDE * SIDE) + .flat_map(|at| { + let [r, g, b, a] = match at < SIDE * SIDE / 2 { + true => codes(at), + false => CLEAR, + }; + [b, g, r, a].map(|code| code as u8) + }) + .collect(); + for (at, target) in targets.iter().enumerate() { + assert_eq!(read(target, 4), want, "{name}: pass {at}: colour 0"); + } + + // Colour 1 unset between colours 0 and 2: refused. + let (zero, two) = ( + colour(PixelFormat::BGRA8Unorm), + colour(PixelFormat::RGBA8Unorm), + ); + let before = calls(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = + (command_buffer.render_command_encoder(&pass(&[Some(&zero), None, Some(&two)]))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + fail(encoder.set_render_pipeline_state(&between)); + same( + encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0), + "colour 1 unset between colours 0 and 2", + ); + encoder.end_encoding(); + assert_eq!(calls() - before, 0, "{name}: between: asked for"); + + // The lacking state where the rest is not the pass's. + let other = colour(PixelFormat::RGBA8Unorm); + let mut depth_desc = + TextureDescriptor::new(TextureType::Type2D, PixelFormat::Depth32Float, SIDE, SIDE); + depth_desc.usage = TextureUsage::RENDER_TARGET; + depth_desc.storage_mode = StorageMode::Private; + let depth = (device.new_texture_for_views(&depth_desc)).expect("a depth target"); + let mut with_depth = pass(&[Some(&zero)]); + with_depth.depth_attachment.texture = Some(depth.clone()); + let multisampled = self::state(name, &device, &multisampled); + for (case, descriptor, drawn) in [ + ("colour 0 another format", pass(&[Some(&other)]), &state), + ("a depth attachment the state lacks", with_depth, &state), + ( + "another raster sample count", + pass(&[Some(&zero)]), + &multisampled, + ), + ] { + let before = calls(); + let mut encoder = (command_buffer.render_command_encoder(&descriptor)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + fail(encoder.set_render_pipeline_state(drawn)); + same( + encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0), + case, + ); + encoder.end_encoding(); + assert_eq!(calls() - before, 0, "{name}: {case}: asked for"); + } + run(name, &command_buffer); + println!( + "{name}: colour 0 drawn in a pass that lacks colour 1, through 1 state made at the \ + first set and 1 pipeline at its first draw, none at the second pass's; the \ + between shape, another format, a depth attachment and another sample count \ + refused" + ); + }); + } +}