From b337c83e25ee96f7fa2fb9a5f2353d87f798bf99 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 3 Dec 2026 09:35:34 -0800 Subject: [PATCH] Byte copies: the kernel's heap slot is the kernel stage's; the draw's docs, the README's and API.md's lines, and the device test's all-codes row and counts The translator's sample kernel named its heap slot under a stage that does not exist (Stage::Kernel is the compute stage's); fixed with the other error the first build (lavapipe job m3-max-84536) reported. The runtime README states the measured layout, the form, the refusals left with their causes, and names this caller on the stencil-export known gap; API.md documents own_draw and SamplesToBytes and catalogues PrecisionNote::RoundedSampleDepthCopy. The device test gains a 128 x 128 Depth16Unorm row at 4 samples whose 65,536 units are every code once, checks every unit of the copy back out, and asserts the counts: 2 sample copies a row, and 8 stencil bit draws for a stencil row on a device without stencil export, else none. --- crates/metal2vulkan-runtime/README.md | 48 ++++++++-- .../src/tests/multisample_bytes.rs | 87 ++++++++++++++----- .../metal2vulkan/src/pipeline/own/samples.rs | 4 +- docs/API.md | 30 +++++++ 4 files changed, 142 insertions(+), 27 deletions(-) diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 837164735..c82d4fc38 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -2525,8 +2525,12 @@ made, with no lock, and never rewritten for layouts. an Iris Xe) clamp it to `[0, 1]`, store a NaN of either sign, a denormal and `-0.0` as `+0.0`, and compare what they stored, so a shadow map uploaded outside `[0, 1]` compares otherwise there. -- Their bytes are not copied for a format of depth and stencil both or a multisample texture - (`Gap::TextureBytes`). +- Their bytes are not copied (`Gap::TextureBytes`, its `TextureBytesCause` naming why) for a + format of depth and stencil both in a copy of both (`replace_region`, `get_bytes`, a Managed + texture's places, a blit's copy without a plane option), for the depth of + `Depth24Unorm_Stencil8` held in a 24-bit depth, and for a multisample texture by + `replace_region`, `get_bytes` or a Managed texture's places; what a blit's copy of a + multisample texture refuses is in the known gaps of blit encoders. - `Device::pixel_format_info` answers as an Apple M3 Max under macOS 27.0.1, which describes none of the values from 630 to 645 (`BGRA10Unorm`, its packed, sRGB, PQ and HLG forms, `R10UintX6`, `RG10UintX12` and the rest); an Apple M4 under that release describes them. @@ -3547,6 +3551,26 @@ while the driver's exit handler waited on a lock, with every runtime thread alre `copy_from_texture` does, each way: plain Metal copies the block of a level of 4 x 2 texels at 4 x 4 from a buffer too, where Metal's validation layer stops it (`(destinationOrigin.y + sourceSize.height)(4) must be <= height(2)`), and the runtime does what plain Metal does. +- A copy between a buffer and a multisample texture's stencil or 16-bit depth, which no Vulkan + copy command takes (a buffer copy's image is single-sample), is the runtime's own work, in + Metal's layout: copy unit `i` of a row of the region (a stencil's byte, a 16-bit depth's two) + is texel `i / n` of the row, sample `i % n`, for `n` samples, rows `bytesPerRow` apart; the + samples outside the region keep theirs; and the copy back out returns the bytes bit for bit. + Apple's pages for the two calls say nothing of a multisample texture; the layout is as measured + on an Apple M3 Max under macOS 27.0.1, and on a Radeon Pro 5300M and an Intel UHD Graphics 630 + under macOS 26.7.1, each plainly and under Metal's API validation layer, which reported nothing. + Into the texture: one rendering of its attachment view over the region, loaded and stored, of + the runtime's own draw, each sample shaded once, each fragment reading its unit at the buffer's + device address and writing it, a 16-bit depth as `FragDepth` under the static note + `PrecisionNote::RoundedSampleDepthCopy` (`Texture::SAMPLE_DEPTH_COPY_NOTE`), a stencil as + `FragStencilRefEXT`, and on a device without `VK_EXT_shader_stencil_export` by bits (the known + gaps of render encoders). Out of it: one dispatch of the runtime's own kernel, an invocation a + sample, which reads it through the texture's element of set 1's sampled-image array, its image + at home, and stores its unit at the buffer's device address, a 16-bit depth as the code nearest + its value. No image or buffer of the runtime's lies between. Each copy counts in + `Metrics::sample_copies`, and its pipelines, each made once a device at its first use, in + `Metrics::pipelines_created`. What of a multisample texture's bytes is not copied is in the + known gaps of blit encoders. `MTLBlitOptionRowLinearPVRTC` is not offered, as no PVRTC texture is made. Each records `vkCmdCopyBufferToImage` or `vkCmdCopyImageToBuffer` against the bytes shaders reach (a Managed buffer's device copy, where the device keeps one), one region an image of the region, each at its @@ -3644,6 +3668,16 @@ while the driver's exit handler waited on a lock, with every runtime thread alre ### Known gaps of blit encoders +- A blit's copy between a buffer and a multisample texture is refused (`Gap::TextureBytes`, + its cause each): of a colour format (`Multisample`); of a 32-bit float depth's depth + (`Depth32Float`, `Depth32Float_Stencil8`; `MultisampleFloatDepth`), as the draw that would write + it takes no value outside `[0, 1]` through `FragDepth`, and Metal's copy of `-0.0`, values + outside `[0, 1]`, NaNs and infinities into one is to be read on a Mac first; into a texture made + without `RenderTarget` usage (`MultisampleUnrendered`), whose image takes no depth and stencil + attachment usage for the draw to write through; out of one made without `ShaderRead` usage + (`MultisampleUnread`), which has no element of set 1's sampled-image array for the kernel to + read through; and out of the stencil of a format of depth and stencil both + (`MultisampleStencilBesideDepth`), whose element reads its depth. - A copy whose source and destination share memory in no order a copy command keeps is not built (`Gap::OverlappingCopy`), and each refusal counts in `Metrics::overlapping_copies_refused`: no Vulkan copy command reads bytes it writes @@ -5019,8 +5053,12 @@ cache is answered compile-required on both. every other operation `Keep`, and no depth write; where the state writes the depth under a compare other than `Always` and `Never`, the first draw writes none and a last draw writes it. That is up to 10 draws where Metal draws once (`Metrics::stencil_bit_draws`), and a draw whose state replaces - no bit, or tests no stencil, is drawn once. Two fragments of one draw on one sample store the OR - of their outputs where Metal stores the later one, and under a depth test that writes, each + no bit, or tests no stencil, is drawn once. A blit's copy of bytes into a multisample texture's + stencil takes the same form there: its draw is drawn 9 times, once under the reference 0 and the + whole write mask, which clears the region's samples, then once for each of the 8 bits, keeping + the samples whose unit holds it (`Metrics::stencil_bit_draws` counts the 8 beyond the first); + each sample is one fragment, so the copy stores Metal's values. Two fragments of one draw on one + sample store the OR of their outputs where Metal stores the later one, and under a depth test that writes, each fragment's stencil operation is chosen against the depth from before the draw: the static note `PrecisionNote::StencilOutputOverlap` on the fragment stage of every such function. Refused at creation there, an `Error::Translation` naming `StencilExport`: a function that also writes a @@ -6337,7 +6375,7 @@ Presenting runs on the runtime's own device; nothing is exported or imported. | `VK_KHR_shader_subgroup_uniform_control_flow` | device, where listed | SIMD groups' reconvergence where maximal reconvergence is not offered | | `VK_KHR_shader_quad_control` | device, where listed | a fragment function's group operations over other lanes, through the quad-control feature below | | `VK_EXT_fragment_shader_interlock` | device, where listed | a fragment function's raster order groups on memory it reads and writes, through the pixel-interlock feature below | -| `VK_EXT_shader_stencil_export` | device, where listed | a fragment function's `[[stencil]]` output as the fragment's stencil reference (`FragStencilRefEXT`); a device without it draws the output by bits (the known gaps); RADV, ANV, lavapipe, KosmicKrisp and the UHD 630's Windows driver list it, NVIDIA's 615 and 620 drivers do not | +| `VK_EXT_shader_stencil_export` | device, where listed | a fragment function's `[[stencil]]` output as the fragment's stencil reference (`FragStencilRefEXT`); a device without it draws the output, and a blit's copy into a multisample texture's stencil, by bits (the known gaps); RADV, ANV, lavapipe, KosmicKrisp and the UHD 630's Windows driver list it, NVIDIA's 615 and 620 drivers do not | | `VK_KHR_portability_enumeration` | instance, where offered | listing portability devices, each checked against the floor as any other | | `VK_KHR_portability_subset` | device, where listed | Vulkan requires it enabled where a device lists it; the device is asked for the portability features below | | `VK_EXT_attachment_feedback_loop_layout` | device, with the feedback loop | a draw's read of an attachment of its own pass through a texture, in the feedback layout, with the colour flag the pipelines of a state whose functions can read a texture take (Render encoders) | diff --git a/crates/metal2vulkan-runtime/src/tests/multisample_bytes.rs b/crates/metal2vulkan-runtime/src/tests/multisample_bytes.rs index 51e1649cc..c89266c6d 100644 --- a/crates/metal2vulkan-runtime/src/tests/multisample_bytes.rs +++ b/crates/metal2vulkan-runtime/src/tests/multisample_bytes.rs @@ -16,7 +16,14 @@ //! 0x5a) by a pass that draws nothing; the copy in; every sample read by the owned `rt6_samples` //! kernels (`rt6_read_stencil`, `rt6_read_depth`, one threadgroup a sample); the copy out into a //! buffer holding 0xee. The rows: an 8 x 8 texture whole at 4 and at 2 samples, and a 4 x 3 region -//! at (2, 1) of one at 4, each where the device makes a texture of that sample count. +//! at (2, 1) of one at 4, each where the device makes a texture of that sample count; and a +//! 128 x 128 `Depth16Unorm` texture at 4 samples whole, whose 65,536 units are every code once +//! (`(i * 7919 + 13) mod 65536`, 7919 odd): each code goes in and back out bit for bit +//! (`Texture::SAMPLE_DEPTH_COPY_NOTE`). +//! +//! Each row's two copies count 2 in `Metrics::sample_copies`, and a stencil row's copy in counts +//! 8 in `Metrics::stencil_bit_draws` on a device without `VK_EXT_shader_stencil_export` (the +//! stencil drawn by bits) and none on one with it; the test prints the form each device took. //! //! `llvm-as` assembles the fixture; without it the test skips visibly. @@ -30,37 +37,42 @@ use crate::{ }; use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError}; -/// The texture's side. +/// The texture's side, but the all-codes row's. const SIDE: u32 = 8; +/// The all-codes row's side: 128 x 128 texels of 4 samples hold 65,536 units. +const ALL_CODES: u32 = 128; /// What the pass clears to. const CLEAR_DEPTH: f64 = 0.25; const CLEAR_STENCIL: u8 = 0x5a; /// The byte the copy-back buffer holds before the copy. const UNWRITTEN: u8 = 0xee; -/// One row: the format, its plane option, the samples, and the region's origin and size. +/// One row: the format, the samples, the texture's side, and the region's origin and size. struct Row { format: PixelFormat, samples: u32, + side: u32, origin: [u32; 2], size: [u32; 2], } -const ROWS: [Row; 6] = [ - whole(PixelFormat::Stencil8, 4), - whole(PixelFormat::Stencil8, 2), +const ROWS: [Row; 7] = [ + whole(PixelFormat::Stencil8, 4, SIDE), + whole(PixelFormat::Stencil8, 2, SIDE), part(PixelFormat::Stencil8), - whole(PixelFormat::Depth16Unorm, 4), - whole(PixelFormat::Depth16Unorm, 2), + whole(PixelFormat::Depth16Unorm, 4, SIDE), + whole(PixelFormat::Depth16Unorm, 2, SIDE), part(PixelFormat::Depth16Unorm), + whole(PixelFormat::Depth16Unorm, 4, ALL_CODES), ]; -const fn whole(format: PixelFormat, samples: u32) -> Row { +const fn whole(format: PixelFormat, samples: u32, side: u32) -> Row { Row { format, samples, + side, origin: [0, 0], - size: [SIDE, SIDE], + size: [side, side], } } @@ -68,6 +80,7 @@ const fn part(format: PixelFormat) -> Row { Row { format, samples: 4, + side: SIDE, origin: [2, 1], size: [4, 3], } @@ -125,8 +138,14 @@ impl Row { fn name(&self) -> String { format!( - "{:?} at {} samples, {} x {} at ({}, {})", - self.format, self.samples, self.size[0], self.size[1], self.origin[0], self.origin[1] + "{:?} at {} samples, {} x {} at ({}, {}) of {side} x {side}", + self.format, + self.samples, + self.size[0], + self.size[1], + self.origin[0], + self.origin[1], + side = self.side ) } } @@ -170,14 +189,15 @@ fn holds(stencil: bool, word: u32, value: u32) -> bool { /// Runs `row` on `device`, its texture at index `index`, and checks Metal's answer. fn copy_row(name: &str, device: &Device, library: &Library, row: &Row, index: u32) { let what = format!("{name}: {}", row.name()); - let mut d = TextureDescriptor::new(TextureType::Type2DMultisample, row.format, SIDE, SIDE); + let side = row.side; + let mut d = TextureDescriptor::new(TextureType::Type2DMultisample, row.format, side, side); d.sample_count = row.samples; d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; d.storage_mode = StorageMode::Private; let texture = (device.new_texture(&d, Some(index))).unwrap_or_else(|error| panic!("{what}: {error}")); let input = row.input(); - let samples = (SIDE * SIDE * row.samples) as usize; + let samples = (side * side * row.samples) as usize; let mut buffers = Buffers::new(device); let source = buffers.of(device, &input); let back = buffers.of(device, &vec![UNWRITTEN; input.len()]); @@ -230,13 +250,13 @@ fn copy_row(name: &str, device: &Device, library: &Library, row: &Row, index: u3 ok(encoder.set_compute_pipeline_state(&state), "the kernel"); ok(encoder.set_texture(Some(&texture), 0), "the texture"); ok(encoder.set_buffer(Some(&words), 0, 0), "the words"); - let shape: Vec = [SIDE, row.samples] + let shape: Vec = [side, row.samples] .iter() .flat_map(|word| word.to_le_bytes()) .collect(); ok(encoder.set_bytes(&shape, 1), "the shape"); ok( - encoder.dispatch_threadgroups([SIDE, SIDE, row.samples], [1, 1, 1]), + encoder.dispatch_threadgroups([side, side, row.samples], [1, 1, 1]), "the reads", ); encoder.end_encoding(); @@ -252,9 +272,36 @@ fn copy_row(name: &str, device: &Device, library: &Library, row: &Row, index: u3 )) .unwrap_or_else(|error| panic!("{what}: the copy out: {error}")); blit.end_encoding(); + let before = device.counters().metrics(); run(&what, &command_buffer); + let after = device.counters().metrics(); - assert_eq!(read(&back), input, "{what}: the copy back out"); + let back = read(&back); + let moved: Vec = (0..row.units()) + .filter(|&i| back[i * row.unit()..][..row.unit()] != input[i * row.unit()..][..row.unit()]) + .collect(); + assert!( + moved.is_empty(), + "{what}: the copy back out: {} of {} units differ, the first (unit, in, out) {:?}", + moved.len(), + row.units(), + moved.first().map(|&i| { + let unit = |bytes: &[u8]| bytes[i * row.unit()..][..row.unit()].to_vec(); + (i, unit(&input), unit(&back)) + }) + ); + let copies = after.sample_copies - before.sample_copies; + assert_eq!(copies, 2, "{what}: the copies' count"); + let bits = after.stencil_bit_draws - before.stencil_bit_draws; + let exports = device.translator().profile().fragment().stencil_export; + let want_bits = match row.stencil() && !exports { + true => 8, + false => 0, + }; + assert_eq!(bits, want_bits, "{what}: the stencil's draws by bits"); + if row.stencil() { + println!("M2V-FORM {what}: the stencil copied in with {bits} draws by bits (stencil export {exports})"); + } let words: Vec = (read(&words).as_chunks::<4>().0.iter()) .map(|word| u32::from_le_bytes(*word)) .collect(); @@ -264,15 +311,15 @@ fn copy_row(name: &str, device: &Device, library: &Library, row: &Row, index: u3 }; let n = row.samples; let mut wrong = Vec::new(); - for y in 0..SIDE { - for x in 0..SIDE { + for y in 0..side { + for x in 0..side { for s in 0..n { let (rx, ry) = (x.wrapping_sub(row.origin[0]), y.wrapping_sub(row.origin[1])); let want = match rx < row.size[0] && ry < row.size[1] { true => row.value(((ry * row.size[0] + rx) * n + s) as usize), false => clear, }; - let word = words[((y * SIDE + x) * n + s) as usize]; + let word = words[((y * side + x) * n + s) as usize]; if !holds(row.stencil(), word, want) { wrong.push((x, y, s, word, want)); } diff --git a/crates/metal2vulkan/src/pipeline/own/samples.rs b/crates/metal2vulkan/src/pipeline/own/samples.rs index 075f36bae..daf02b43a 100644 --- a/crates/metal2vulkan/src/pipeline/own/samples.rs +++ b/crates/metal2vulkan/src/pipeline/own/samples.rs @@ -273,7 +273,7 @@ pub(super) fn samples_to_bytes(aspect: SampleAspect, arrayed: bool) -> BResult BResult { let high = fb.binary(BinOp::ShiftRightLogical, vertex, one)?; let four = f32_value(&mut fb, t.f32_, 4.0)?; let minus_one = f32_value(&mut fb, t.f32_, -1.0)?; - let mut axis = |fb: &mut FunctionBuilder<'_>, bit: Value| -> BResult { + let axis = |fb: &mut FunctionBuilder<'_>, bit: Value| -> BResult { let bit = fb.convert(ConvOp::ConvertUToF, bit, t.f32_)?; let far = fb.binary(BinOp::FMul, bit, four)?; fb.binary(BinOp::FAdd, far, minus_one) diff --git a/docs/API.md b/docs/API.md index 408375a0d..cd6ededa6 100644 --- a/docs/API.md +++ b/docs/API.md @@ -308,6 +308,23 @@ the runtime's, the command line's, the compile worker's and every validation too into the parameter block `pipeline::ExecutionCounts` lays out, where each part's `sequenceCountAddress` reads it. Its interface is a compiled function's: the one push range, holding the block's device address at offset 0, and no descriptor. +- **A blit's copy between a buffer and a multisample texture's samples.** No Vulkan copy command + takes a multisample image, so a runtime moves a stencil's or a 16-bit depth's samples with + modules built from no Metal function, in Metal's layout as measured (copy unit `i` of a row of + the region is texel `i / n` of the row, sample `i % n`, for `n` samples). Out of the texture, + `pipeline::own_kernel(OwnKernel::SamplesToBytes { aspect, arrayed }, profile)`: a compute + stage of `SampleBytes::WORKGROUP` invocations a workgroup along x, one a unit, dispatched with + `ceil(width * samples / 64)` workgroups along x and one a row of the region along y, which reads + each sample through set 1's sampled-image array (binding 0) at the texture's element and stores + its unit (a 16-bit depth as the code nearest its value) at a device address. Into it, + `pipeline::own_draw(write, profile)`: a vertex stage that draws one triangle over the viewport + from `VertexIndex` 0 to 2 and a fragment stage, run once a sample (it reads `SampleId`; the + pipeline enables sample shading at 1), that reads its unit at a device address and writes it + as `SampleWrite` says: `FragDepth` for a 16-bit depth (`PrecisionNote::RoundedSampleDepthCopy`), + `FragStencilRefEXT`, or, on a device without stencil export, no output, the invocation demoted + where the bit `SampleBytes::BIT_AT` names is clear in its unit, for a draw a bit. Both take + `SampleBytes`' parameter block, its device address the one push field at offset 0 + (`PushField::ArgumentTableAddress`). - **A kernel's bound buffers** (`DeviceProfile::binds_kernel_buffers`). Under the identity domains, on a device that answers this query, a kernel reaches each buffer argument through a storage buffer of set 0 bound over that buffer, not at its address. The descriptor covers the @@ -2005,6 +2022,19 @@ category, and says what makes an operation carry the note and what may differ. E before the draw, where Metal tests a later fragment against the depth an earlier one wrote. A draw whose fragments reach each sample at most once (a quad of two triangles, one fullscreen triangle) stores Metal's values. +- `metal2vulkan-degrade-rounded-sample-depth-copy` (precision). + `PrecisionNote::RoundedSampleDepthCopy`: A copy of bytes into the 16-bit depth + (`Depth16Unorm`) of a multisample texture by a blit's copy from a buffer, on every device. On + `metal2vulkan-runtime` it is the static note `Texture::SAMPLE_DEPTH_COPY_NOTE` of + `copy_from_buffer_with_options` into one, decided by the format, never by the bytes. No Vulkan + copy command writes a multisample image, so the runtime draws the bytes in + (`pipeline::own_draw` of `SampleWrite::Depth16`): each sample's fragment writes the code `c` it + reads as `FragDepth`, `(c + 1/4) / 65535` (1 for 65535), and the device converts that `float` to + a code, which Vulkan's fixed-point conversion lets be either of the two codes nearest it + (`convertFloatToUint`). A device that rounds to nearest, as Vulkan says implementations should, + or toward zero stores `c`, Metal's code: the `float`'s error is far below a quarter code. Cost: + a device that rounded up would store `c + 1`, one code above Metal's, which a later depth test + or read sees. - `metal2vulkan-degrade-cube-gradient-footprint` (precision). `PrecisionNote::CubeGradientFootprint`: An explicit-gradient sample of a cube texture takes Metal's footprint in the form Vulkan's rule reads, in every stage on every device. Cost: the