From 2b97fc1cf0c8c9ffcafbdb120ec07213ddacf385 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 19 Oct 2026 00:15:59 +0300 Subject: [PATCH] Render packed 16-bit, 8-bit sRGB and RGB9E5 attachments the device cannot render through integer views of their words The RTX 5080 samples A1BGR5Unorm, ABGR4Unorm (and every other 16-bit packed order), R8Unorm_sRGB, RG8Unorm_sRGB and RGB9E5Float but renders none of them, and lavapipe renders neither 8-bit sRGB format. A render target, clear or draw of such a texture was refused as the device lacking the format, which ends the guest of any app that renders to one. They now render through an R8_UINT, R16_UINT or R32_UINT view of the same bits, the fragment function writing Metal's word. What changes: - metal::format::WordAttachment (public, with WordField): a format's fields in its word (packed 16-bit layouts named from the least significant bit, Srgb8, Rgb9e5). WordAttachment::of holds where the device samples the format (or its UNORM twin), does not render it, and renders the word's integer format: derived from format features alone, on every driver. - Translator: LoweringInputs::word_colors names such attachments. The fragment output to one is declared as a uint and each return stores Metal's word: a packed channel h(x) to nearest even, NaN 0, clamped to [0, 1], times the maximum code, rounded to even; an sRGB channel through Metal's twelve-bit table; RGB9E5 by the truncating kernel-write rule (shared with the storage write, lower::texture::rgb9e5_word). The cache codec carries the new fields. - Partial write masks and blends: - in the pixel interlock (where the device orders fetch through it alone), a packed 16-bit or 8-bit sRGB word's partial mask merges the kept fields from the word read first; - a packed 16-bit word's blend other than One/Zero decodes each code as Metal's blend reads it, h(c / m), blends in half as the 8-bit unorm blend does and encodes Metal's word. Metal's tile holds a pass's earlier result finer than the codes, so this is a near-equivalent within one code, recorded as PrecisionNote::DeviceColorConversion and announced; the exact form (the extended-range half shadow taken by word attachments) is a FAST-PATHS "not built yet" row; - where fetch reads rasterization-order input attachments (lavapipe), an 8-bit sRGB word's partial mask merges over its input attachment (new RuntimeFact::WordInputMerge), per sample in a multisampled pipeline. - Runtime: the texture's image keeps its own format, sampled and blitted natively, made mutable with extended usage and the word view listed; the pass's attachment is the view; a pass clear writes the word of Metal's clear. - New degradation kind shared-exponent-kept (Precision): Metal's tile store normalizes a loaded RGB9E5 word whose largest mantissa is below 256 in each tile a draw reaches, which a Vulkan pass keeps; announced at each such draw, with a FAST-PATHS row. - DeviceColorConversion's rustdoc states that Metal blends a packed 16-bit attachment against its tile's finer values within a pass. - Still refused, recorded as FAST-PATHS known gaps: colour inputs and resolves of word attachments, blended or fetched sRGB words, an output of fewer than four lanes for a blended packed word, RGB9E5 half outputs, blends, masks, inputs and resolves. - New owned fixture engine/wm_samples and runtime_lane::word_samples for the multisampled merge. Why: these formats are Metal render targets the guest uses, and the device holds and samples them; only rendering them directly is missing. Metal's rules, measured with plain Metal on the M3 Max under macOS 27.0.1: 65,536 float4 and half4 outputs and 4,096 clear colours per packed format, 0 texels off the rule; a One/Zero blend stores the same bytes; the blend sweep (2,891 states, 8,192 random pixels, four packed formats, half and float, fast and safe maths) gave Metal's code in every channel without fast maths and within one code under it; within a pass Metal's tile holds a packed attachment finer than its codes (blends in one pass follow the unrounded value, across two passes the stored codes); RGB9E5 draws and clears 65,536 of each, 0 off. Verified: - Translator and runtime unit filters on gem10: 162 of 162 and 258 of 258 (word attachments), 394 (partial masks in the interlock), 370 and 422 (blends, including 864 words the M3 stored checked on the interpreter), 538 (sRGB and RGB9E5 words), 38 and 108 (input-attachment merge). - On lavapipe: runtime_lane::color_writes 5 passed, RG8UnormSRGB under the red mask 0 of 107,814 channels off where it was refused before; word_samples, 64 texels of 4 samples merged, the edge texels keeping both greens; public_fixtures_engine with the new rows. - clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc. --- .../metal2vulkan-runtime/src/clear_value.rs | 84 ++- .../metal2vulkan-runtime/src/degradation.rs | 14 + .../src/framebuffer_fetch.rs | 15 +- crates/metal2vulkan-runtime/src/image_plan.rs | 36 +- crates/metal2vulkan-runtime/src/render.rs | 5 + .../src/render/executions.rs | 2 + .../src/render/unused_bits_load.rs | 11 + .../metal2vulkan-runtime/src/render_pass.rs | 30 +- crates/metal2vulkan-runtime/src/resolve.rs | 15 + .../src/tests/image_plan.rs | 80 ++- crates/metal2vulkan-validation/build.rs | 1 + .../fixtures/public/engine/TOOLCHAIN | 1 + .../fixtures/public/engine/wm_samples.air.ll | 173 ++++++ .../fixtures/public/engine/wm_samples.ll | 169 ++++++ .../fixtures/public/engine/wm_samples.metal | 41 ++ .../src/runtime_lane.rs | 2 + .../src/runtime_lane/color_writes.rs | 292 ++++++++- .../src/runtime_lane/degrade_notices.rs | 7 +- .../src/runtime_lane/snorm_tile_store.rs | 56 ++ .../src/runtime_lane/word_samples.rs | 225 +++++++ crates/metal2vulkan/src/cache/codec.rs | 5 +- crates/metal2vulkan/src/device/mechanism.rs | 3 + .../src/device/tests/mechanism.rs | 10 +- .../src/lower/arith/color_write.rs | 7 + .../src/lower/arith/extended_range/blend.rs | 81 ++- crates/metal2vulkan/src/lower/arith/tests.rs | 1 + .../src/lower/arith/tests/blend_packed.rs | 295 +++++++++ .../src/lower/arith/tests/color_write.rs | 69 +++ .../metal2vulkan/src/lower/fragment/color.rs | 19 +- .../metal2vulkan/src/lower/fragment/fetch.rs | 285 ++++++++- .../src/lower/fragment/fetch/tests.rs | 88 +++ .../src/lower/fragment/input_blend.rs | 3 +- crates/metal2vulkan/src/lower/fragment/mod.rs | 14 +- .../src/lower/fragment/word_input.rs | 143 +++++ crates/metal2vulkan/src/lower/stage_io/mod.rs | 24 +- .../metal2vulkan/src/lower/stage_io/plan.rs | 19 +- .../src/lower/stage_io/word_color.rs | 285 +++++++++ crates/metal2vulkan/src/lower/texture/emit.rs | 21 + crates/metal2vulkan/src/lower/texture/mod.rs | 9 +- crates/metal2vulkan/src/metal/format/mod.rs | 2 + crates/metal2vulkan/src/metal/format/word.rs | 338 +++++++++++ crates/metal2vulkan/src/pipeline/api_tests.rs | 5 + crates/metal2vulkan/src/pipeline/artifact.rs | 13 + .../metal2vulkan/src/pipeline/color_writes.rs | 165 +++++ crates/metal2vulkan/src/pipeline/compile.rs | 37 +- .../metal2vulkan/src/pipeline/compile/key.rs | 5 + .../src/pipeline/compile/tests.rs | 1 + crates/metal2vulkan/src/pipeline/facts.rs | 12 + crates/metal2vulkan/src/pipeline/link.rs | 3 + .../metal2vulkan/src/pipeline/link/fetch.rs | 61 +- .../src/pipeline/link/graphics.rs | 36 +- .../metal2vulkan/src/pipeline/lower_inputs.rs | 15 + crates/metal2vulkan/src/pipeline/stage_io.rs | 20 +- crates/metal2vulkan/src/pipeline/testing.rs | 3 +- .../src/tests/engine_word_attachments.rs | 566 ++++++++++++++++++ crates/metal2vulkan/src/tests/mod.rs | 1 + .../tests/air_input/wm_samples.txt | 210 +++++++ crates/metal2vulkan/tests/api_surface.rs | 2 + docs/API.md | 35 ++ docs/FAST-PATHS.md | 18 + 60 files changed, 4105 insertions(+), 83 deletions(-) create mode 100644 crates/metal2vulkan-validation/fixtures/public/engine/wm_samples.air.ll create mode 100644 crates/metal2vulkan-validation/fixtures/public/engine/wm_samples.ll create mode 100644 crates/metal2vulkan-validation/fixtures/public/engine/wm_samples.metal create mode 100644 crates/metal2vulkan-validation/src/runtime_lane/word_samples.rs create mode 100644 crates/metal2vulkan/src/lower/arith/tests/blend_packed.rs create mode 100644 crates/metal2vulkan/src/lower/fragment/word_input.rs create mode 100644 crates/metal2vulkan/src/lower/stage_io/word_color.rs create mode 100644 crates/metal2vulkan/src/metal/format/word.rs create mode 100644 crates/metal2vulkan/src/tests/engine_word_attachments.rs create mode 100644 crates/metal2vulkan/tests/air_input/wm_samples.txt diff --git a/crates/metal2vulkan-runtime/src/clear_value.rs b/crates/metal2vulkan-runtime/src/clear_value.rs index 7c1c696ac..1678ccce1 100644 --- a/crates/metal2vulkan-runtime/src/clear_value.rs +++ b/crates/metal2vulkan-runtime/src/clear_value.rs @@ -47,8 +47,9 @@ //! level compressed and the pass has no draw call (`nan_clear::keeps_nan_sign`, the pass's encoder //! choosing at its end), a bfloat channel's `float` is rounded straight to bfloat, on the M4 under //! 27.0.1 and the M3 Max under 26.7 alike, and a `BGR10_XR` or `BGRA10_XR` channel's code is -//! straight from its `float`, `BGR10_XR`'s bits 30 and 31 zero (EVs XSH-clr2-m4 to XSH-clr5-m4, the -//! M4 under 27.0.1); the two-plane formats store the same on either route. +//! A **word** attachment (`metal::format::WordAttachment`: a packed 16-bit, one- or two-channel +//! 8-bit sRGB or `RGB9E5Float` format the device holds but does not render) renders through the +//! view of its word, so its clear value is the word Metal's clear stores ([`word`]). //! //! A **two-plane YCbCr** attachment whose store is matched (`metal::format::ycbcr_renders`) renders //! into floats, which the pass's store encodes into the planes as Metal stores a drawn texel: its @@ -253,6 +254,30 @@ pub(super) fn color( }) } +/// The Vulkan clear value of Metal's clear `color` for an attachment of `pf` that renders through +/// the view of its word `word` (`metal::format::WordAttachment`): the word of the codes Metal's +/// clear stores ([`color`]'s conversion of each channel; `RGB9E5Float`'s word of the color +/// through `float`, its mantissas truncated, `WordAttachment::output_word`), in the view's one +/// unsigned component. `None` for a format with no clear rule. +pub(super) fn word( + pf: PixelFormat, + color: [f64; 4], + word: WordAttachment, +) -> Option { + if word == WordAttachment::Rgb9e5 { + let uint32 = [word.output_word(color.map(|c| c as f32)), 0, 0, 0]; + return Some(vk::ClearColorValue { uint32 }); + } + let codes = convert(&channels(pf)?, color).map(|t| match t { + Texel::Norm { k, .. } => u32::try_from(k).unwrap_or(0), + Texel::Srgb(k) => k, + _ => 0, + }); + Some(vk::ClearColorValue { + uint32: [word.pack(codes), 0, 0, 0], + }) +} + /// Where a `half` or small-float channel of `value`, the Vulkan clear value [`color`] gives an /// attachment of `pf`, is a NaN, whose bits Vulkan leaves to the device's conversion /// (`nan_clear.rs`): the unsigned-integer format of the texel's size and the clear value that @@ -730,6 +755,61 @@ pub(crate) mod tests { Some(bits.to_le_bytes()[..bytes].to_vec()) } + /// A word attachment's clear value ([`word`]) is the little-endian word of the texel Metal's + /// clear writes ([`texel_bytes`]), for every packed 16-bit layout, the one- and two-channel + /// 8-bit sRGB ones and `RGB9E5Float`'s, over colors at and beside each layout's ties, NaN, + /// negative values, values past one and past `RGB9E5Float`'s largest, and tiny ones. + #[test] + fn word_clears_are_metals_texels() { + let values = [ + 0.0, + 1.0, + 0.5, + 0.49, + 0.1, + 0.25, + 0.75, + 1.0 / 3.0, + 0.016, + -0.5, + 2.0, + f64::NAN, + 15.5 / 31.0, + 7.5 / 15.0, + 31.5 / 63.0, + 70000.0, + 3.0e-6, + 1000.3, + ]; + for pf in [ + P::B5G6R5Unorm, + P::A1BGR5Unorm, + P::ABGR4Unorm, + P::BGR5A1Unorm, + P::R8UnormSRGB, + P::RG8UnormSRGB, + P::RGB9E5Float, + ] { + let layout = WordAttachment::layout(pf).expect("a word layout"); + for (i, &r) in values.iter().enumerate() { + let n = values.len(); + let color = [ + r, + values[(i + 3) % n], + values[(i + 7) % n], + values[(i + 11) % n], + ]; + let got = word(pf, color, layout).expect("a clear value"); + // SAFETY: every member of the union is four 32-bit values; any bits are a `u32`. + let got = unsafe { got.uint32 }; + let texel = bytes(pf, color); + let want = + (texel.iter().enumerate()).fold(0u32, |w, (i, &b)| w | u32::from(b) << (8 * i)); + assert_eq!(got, [want, 0, 0, 0], "{pf:?} {color:?}"); + } + } + } + /// The texels Metal writes, as little-endian bytes. fn bytes(pf: PixelFormat, c: [f64; 4]) -> Vec { texel_bytes(pf, c).unwrap_or_else(|| panic!("no packing for {pf:?}")) diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 5c88ddbe4..e45206bd2 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1138,10 +1138,24 @@ degradations! { channel's minimum code (-128, or -32768 for 16 bits) as the code above it (-127, \ -32767) in each tile a draw reaches: a texel whose bytes no Metal write left \ (uploaded or copied bytes) keeps a code Metal's pass would change"; + /// A draw in a render pass that loads a single-sampled `RGB9E5Float` color attachment and + /// does not discard it at the store (`render.rs`). Metal's pass, once it draws, writes + /// each 32 x 32 tile a draw reaches back through its texels' values, so a word whose + /// largest mantissa is below 256 under an exponent above 0 is stored normalized: its + /// mantissas shifted up a bit as its exponent steps down one, until the largest reaches + /// 256 or the exponent 0 (measured on an Apple M3 Max under macOS 27.0.1: the format + /// scout's draw over uploaded words, 22 of 143 untouched texels of the reached tile + /// normalized, none other changed), where the device's pass keeps the bytes its draws do + /// not write. Announced at every draw, an indirect command buffer's executed commands' /// too, naming every such attachment of the pass. Not where `DriverFact::TileStoreIsMetals` /// holds (MoltenVK's pass is a Metal pass), nor under /// [`metal2vulkan::device::TileStorePolicy::Exact`] for an attachment the load pass /// (`render/unused_bits_load.rs`) rewrites. + SharedExponentKept = "shared-exponent-kept", Precision, + "the texels the pass's draws do not write keep their words; Metal's pass normalizes \ + a word whose largest mantissa is below 256 (its exponent above 0) in each tile a \ + draw reaches: a texel whose bytes no Metal write left (uploaded or copied words) \ + keeps a word Metal's pass would change, of the same value"; /// A blit between a buffer and a level of `RGB10A8_2P_XR10` or its sRGB twin whose width /// is not a multiple of 4 (`two_planes.rs`): it moves the texels at the rows the texture /// holds them in, where Metal's blit addresses the level's rows `⌊4 w / 16⌋ · 16` bytes diff --git a/crates/metal2vulkan-runtime/src/framebuffer_fetch.rs b/crates/metal2vulkan-runtime/src/framebuffer_fetch.rs index 30846037f..ea25ff439 100644 --- a/crates/metal2vulkan-runtime/src/framebuffer_fetch.rs +++ b/crates/metal2vulkan-runtime/src/framebuffer_fetch.rs @@ -97,8 +97,7 @@ use super::error::Error; use super::image_plan::{hiz_candidate, ImagePlan}; use super::Device; use metal2vulkan::bind::PlanesCopy; -use metal2vulkan::device::{DeviceProfile, FormatUsage, VkFeature, VkProperty}; -use metal2vulkan::error::{Capability, Feature, Unsupported}; +use metal2vulkan::metal::format::WordAttachment; use metal2vulkan::metal::TextureType; use metal2vulkan::pipeline::{GraphicsState, StorageAttachmentUse}; use metal2vulkan::vk::{Format, ImageCreateFlags, ImageUsageFlags, NumericFormat}; @@ -235,12 +234,22 @@ pub(crate) fn storage_candidate(plan: &ImagePlan, profile: &DeviceProfile) -> Op let usage = plan.usage; let samples = plan.samples.as_raw(); let own_image = samples == 1 || through_multisampled_storage(profile, samples); + // A packed 16-bit render target the device renders through its word's view + // (`image_plan.rs`), which a fetching draw stores through too: `STORAGE` is that view's, which + // the image's extended usage lets it hold. + let word = WordAttachment::of(plan.pixel_format, profile) + .map(WordAttachment::word_format) + .filter(|&w| { + plan.flags.contains(ImageCreateFlags::EXTENDED_USAGE) + && views_in(plan, w) + && profile.supports_format(w, FormatUsage::StorageImage) + }); let candidate = through_storage(profile) && usage.contains(ImageUsageFlags::COLOR_ATTACHMENT) && !usage.intersects(ImageUsageFlags::STORAGE | ImageUsageFlags::TRANSIENT_ATTACHMENT) && own_image && stores_samples(profile, samples) - && profile.supports_format(plan.format, FormatUsage::StorageImage); + && (profile.supports_format(plan.format, FormatUsage::StorageImage) || word.is_some()); if !candidate { return None; } diff --git a/crates/metal2vulkan-runtime/src/image_plan.rs b/crates/metal2vulkan-runtime/src/image_plan.rs index 7befeffc1..28c1efeb0 100644 --- a/crates/metal2vulkan-runtime/src/image_plan.rs +++ b/crates/metal2vulkan-runtime/src/image_plan.rs @@ -724,6 +724,18 @@ fn plan_held( _ => Vec::new(), }; let wants_attachment = wants(TextureUsage::RENDER_TARGET) && attachment.is_some(); + // A format the device samples but does not render, whose word it renders, renders through a + // view of the word (`metal::format::WordAttachment`): its image keeps the format (an 8-bit + // sRGB format the device holds no image of, its UNORM twin), mutable, with the attachment + // usage extended to the word's view. + let word = match ( + wants(TextureUsage::RENDER_TARGET), + attachment, + depth_stencil, + ) { + (true, None, false) => WordAttachment::of(pf, profile).map(|w| w.word_format()), + _ => None, + }; // An 8-bit sRGB texture whose format the device holds no image of at all (`R8G8_SRGB` on // NVIDIA) is held in its UNORM twin (`srgb_raw_twin`), which is its storage alias's own view: // the twin serves the storage too. Where the device holds the sRGB format, it stays the @@ -833,6 +845,9 @@ fn plan_held( if depth_stencil { flags |= compatible_depth(profile, format, samples); } + } else if let Some(word) = word.filter(|_| format == direct || Some(format) == unorm_twin) { + usage_flags |= attachment_flag(false, profile); + views.insert(word); } else { unavailable |= usage.intersection(TextureUsage::RENDER_TARGET); } @@ -899,20 +914,28 @@ fn plan_held( views.insert(raw); } } - // The sRGB twin's views, which Metal makes without `PixelFormatView`. + // The sRGB twin's views, which Metal makes without `PixelFormatView`; not the view of the + // twin's word (`WordAttachment`), which would make every such render target mutable for a view + // few textures take: an attachment view of the twin the device renders only through its word + // is refused, as without the word. if let Some(twin) = srgb_twin(pf) { + let twin_word = WordAttachment::of(twin, profile).map(|w| w.word_format()); views.extend( view_formats(twin, usage_flags, profile) .into_iter() - .filter(|&f| compatible(format, f, true)), + .filter(|&f| compatible(format, f, true) && Some(f) != twin_word), ); } views.insert(format); // A usage the image's own format lacks, which a view format has (a storage alias, a sampled - // twin), needs extended usage. + // twin, a word attachment), needs extended usage. let extended = [ (ImageUsageFlags::SAMPLED, FormatUsage::SampledImage), (ImageUsageFlags::STORAGE, FormatUsage::StorageImage), + ( + ImageUsageFlags::COLOR_ATTACHMENT, + FormatUsage::ColorAttachment, + ), ] .iter() .any(|&(bit, need)| usage_flags.contains(bit) && !profile.supports_format(format, need)); @@ -1020,7 +1043,8 @@ fn plan_depth_twin( /// The formats of the views the runtime makes of a texture of `pf` for the Vulkan usages in /// `usage` on `profile`: its sampled representation, its storage view (the alias, or the direct -/// format), and its attachment format (the direct format). A view the device cannot make for `pf` +/// format), and its attachment format (the direct format, or the view of its word where the device +/// renders that and not the format, `WordAttachment`). A view the device cannot make for `pf` /// is left out: a format list naming a format the device lacks is one some drivers make no image /// of (ANV, for an `RG8Unorm` render target listing its twin's `R8G8_SRGB`). pub(super) fn view_formats( @@ -1048,6 +1072,10 @@ pub(super) fn view_formats( FormatUsage::ColorAttachment }; out.extend(direct_format(pf).filter(|&f| profile.supports_format(f, need))); + // A format the device samples but does not render renders through its word's view. + if usage.contains(ImageUsageFlags::COLOR_ATTACHMENT) { + out.extend(WordAttachment::of(pf, profile).map(|w| w.word_format())); + } } out } diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 8ad682843..8f629889e 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -6260,6 +6260,8 @@ impl RenderCommandEncoder { }); } + /// Announce `shared-exponent-kept` at a draw in a pass that loads a single-sampled + /// `RGB9E5Float` color attachment (and does not discard it at the store), whatever the draw's /// state, naming every such attachment, `kept` (`unused_bits_load::shared_exponent_kept`): /// Metal's pass, once it draws, writes each tile a draw reaches back through its texels' /// values, so a word the draws do not write whose largest mantissa is below 256 under an @@ -6267,6 +6269,9 @@ impl RenderCommandEncoder { /// whose pass stores it so too (`DriverFact::TileStoreIsMetals`), nor for an attachment the /// load pass rewrites (`TileStorePolicy::Exact`). fn degrade_shared_exponent(device: &Device, kept: &[String]) { + if kept.is_empty() { + return; + } device.degrade(Degradation::SharedExponentKept, || { ( format!("a draw in a render pass that loads {}", kept.join(" and ")), diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index 979076459..e8981e371 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -500,6 +500,8 @@ impl RenderCommandEncoder { ) -> Result<(), Error> { self.sync_heaps(); // An execution rewrites an extended-range or padded attachment as a draw does, of reset + // commands too, and a signed normalized one's minimum codes, and an + // `RGB9E5Float` one's words. self.degrade_kept_attachments(); self.rewrites_unused_bits = true; self.degrade_extended_range_execution(); diff --git a/crates/metal2vulkan-runtime/src/render/unused_bits_load.rs b/crates/metal2vulkan-runtime/src/render/unused_bits_load.rs index 6723842a3..70ed36426 100644 --- a/crates/metal2vulkan-runtime/src/render/unused_bits_load.rs +++ b/crates/metal2vulkan-runtime/src/render/unused_bits_load.rs @@ -404,6 +404,7 @@ pub(super) fn snorm_minimum_kept(color: &ColorTarget) -> bool { && takes(color, true).is_none() } +/// Whether `color` is a single-sampled `RGB9E5Float` attachment, loaded and not discarded at the /// store, where the load pass does not take it: Metal's pass, once it draws, writes each tile a /// draw reaches back through its texels' values, so a word whose largest mantissa is below 256 /// under an exponent above 0 (one no Metal write leaves) is stored normalized, its mantissas @@ -411,7 +412,17 @@ pub(super) fn snorm_minimum_kept(color: &ColorTarget) -> bool { /// not write (`degrade_shared_exponent`, which reads `DriverFact::TileStoreIsMetals`). The load /// pass rewrites them under the exact tile store (`TileStorePolicy::Exact`) where it takes the /// attachment. +pub(super) fn shared_exponent_kept(color: &ColorTarget) -> bool { + let target = own(color); + let discarded = color.store == StoreAction::DontCare && !color.late_store; + target.texture.pixel_format() == PixelFormat::RGB9E5Float + && target.samples == 1 + && color.load == LoadAction::Load + && !color.memoryless + && !discarded && takes(color, true).is_none() +} + /// The color attachments of a pass's layout that each of a draw's kept-attachment notices names, as /// `color {index}, {format:?}`: the extended-range or padded ones the load pass does not take /// ([`untaken`], `degrade_unused_bits`) and, on a driver whose pass does not store as Metal's diff --git a/crates/metal2vulkan-runtime/src/render_pass.rs b/crates/metal2vulkan-runtime/src/render_pass.rs index 547e123a0..18c2604c2 100644 --- a/crates/metal2vulkan-runtime/src/render_pass.rs +++ b/crates/metal2vulkan-runtime/src/render_pass.rs @@ -1327,8 +1327,16 @@ pub(super) fn layout( // An extended-range attachment's codes by either of Metal's routes: the pass's encoder // chooses as it ends, once it knows whether the pass draws (`ColorTarget::straight_clear`). let channels = color.clear_color.channels(); - let clear = clear_value::color(texture.pixel_format(), channels, ClearRoute::ThroughHalf) - .ok_or_else(not_yet)?; + // A word attachment clears to the word of Metal's codes. + let word = metal2vulkan::metal::format::WordAttachment::of( + texture.pixel_format(), + device.compile_device().profile(), + ) + .filter(|w| w.word_format() == target.format); + let clear = match word { + Some(word) => clear_value::word(texture.pixel_format(), channels, word), + } + .ok_or_else(not_yet)?; let straight_clear = ExtendedRange::of(texture.pixel_format()).and_then(|_| { clear_value::color(texture.pixel_format(), channels, ClearRoute::Straight) }); @@ -1658,6 +1666,9 @@ pub(super) fn not_2d(target: &Target) -> bool { /// stencil view (the stencil view of a combined texture) renders in its image's format, the one the /// device represents the view's format by; one the device represents otherwise is not built, nor is /// a color view without a direct format or one the image cannot take (`NotImplemented(Render)`). +/// A color format the device samples but does not render, whose word it renders +/// (`metal::format::WordAttachment`), renders in the word's format where the image takes that +/// view, as the pipeline's fragment function writes it. pub(super) fn attachment_format( which: Attachment, plan: &ImagePlan, @@ -1665,11 +1676,23 @@ pub(super) fn attachment_format( device: &Device, ) -> Result { use metal2vulkan::device::FormatUsage; + let profile = device.compile_device().profile(); + let family = block_family(pixel_format) == block_family(plan.pixel_format); + // A color format the device samples but does not render renders through the view of its word + // (`metal::format::WordAttachment`), which a pipeline's fragment function writes, where the + // image takes that view. + if let Attachment::Color(_) = which { + if let Some(word) = metal2vulkan::metal::format::WordAttachment::of(pixel_format, profile) { + let format = word.word_format(); + if views_as(plan, format, family) { + return Ok(format); + } + } + } if plan.pixel_format == pixel_format { return Ok(plan.format); } let not_built = || Error::NotImplemented(RuntimeGap::Render); - let profile = device.compile_device().profile(); if let Attachment::Depth | Attachment::Stencil = which { let usages: std::collections::BTreeSet<_> = [FormatUsage::DepthStencilAttachment].into(); return match vk_format(pixel_format, &usages, profile) { @@ -1688,7 +1711,6 @@ pub(super) fn attachment_format( }, ))); } - let family = block_family(pixel_format) == block_family(plan.pixel_format); if !views_as(plan, direct, family) { return Err(not_built()); } diff --git a/crates/metal2vulkan-runtime/src/resolve.rs b/crates/metal2vulkan-runtime/src/resolve.rs index 3490ee505..267e3e597 100644 --- a/crates/metal2vulkan-runtime/src/resolve.rs +++ b/crates/metal2vulkan-runtime/src/resolve.rs @@ -42,6 +42,10 @@ //! another one each run, and a 32-bit channel takes such a value even where the samples //! agree; only an 8- or 16-bit channel (`RGB10A2Uint`'s too) whose samples agree resolves to //! their value. No rule that holds for every pixel: refused. +//! - A packed 16-bit attachment the device renders through the view of its word +//! (`metal::format::WordAttachment`) holds each sample's stored codes, while Metal's resolve +//! averages its tile's values, finer than the codes: not modelled, refused +//! `NotImplemented(Format)`. //! - The depth filters `Sample0`, `Min` and `Max` take sample 0's depth, the smallest and the //! largest. The stencil filter `Sample0` takes sample 0's stencil, and `DepthResolvedSample` //! the stencil of the sample whose depth the depth filter took: of equal depths, the last @@ -468,6 +472,17 @@ pub(super) fn color( { return Err(Error::Unsupported(unsupported)); } + // An attachment rendered through the view of its word (`metal::format::WordAttachment`) holds + // each sample's stored codes, while Metal resolves its tile's values: not modelled. + let word = metal2vulkan::metal::format::WordAttachment::of( + source.texture.pixel_format(), + device.compile_device().profile(), + ); + if word.is_some_and(|w| w.word_format() == source.format) { + return Err(Error::Unsupported( + metal2vulkan::error::Unsupported::not_implemented(metal2vulkan::error::Feature::Format), + )); + } single_sampled(call, which, source)?; let Some(destination) = destination(call, device, which, source, texture, wanted)? else { return Ok(None); diff --git a/crates/metal2vulkan-runtime/src/tests/image_plan.rs b/crates/metal2vulkan-runtime/src/tests/image_plan.rs index 65853ef3d..fb727b89a 100644 --- a/crates/metal2vulkan-runtime/src/tests/image_plan.rs +++ b/crates/metal2vulkan-runtime/src/tests/image_plan.rs @@ -195,7 +195,12 @@ fn check_plan( ); } if plan.usage.contains(ImageUsageFlags::COLOR_ATTACHMENT) { - assert!(supports(FormatUsage::ColorAttachment), "{what}"); + // Or, with extended usage, through the view of the format's word. + let word = WordAttachment::of(pf, profile).map(|w| w.word_format()); + assert!( + supports(FormatUsage::ColorAttachment) || (extended && word.is_some_and(&viewable)), + "{what}" + ); } // A color attachment is an input attachment exactly where the device's framebuffer fetch // reads input attachments. @@ -447,6 +452,7 @@ fn a_written_only_view_serves_where_no_slot_both_reads_and_writes() { /// An 8-bit sRGB format the device samples only through its UNORM twin is held in the twin's /// format, sampled, with no usage the device lacks for the sRGB format: lavapipe's `R8Unorm_sRGB` /// and ANV's and NVIDIA's `RG8Unorm_sRGB`. A device that samples the format keeps its own image. +/// A render target the device renders through its word's view (`WordAttachment`) lists that view. #[test] fn an_srgb_format_the_device_cannot_sample_is_held_as_its_unorm_twin() { let mut held = Vec::new(); @@ -482,12 +488,16 @@ fn an_srgb_format_the_device_cannot_sample_is_held_as_its_unorm_twin() { assert!(plan.usage.contains(ImageUsageFlags::SAMPLED), "{what}"); assert!(plan.unavailable.is_empty(), "{what}"); check_plan(&name, pf, TextureUsage::SHADER_READ, &plan, &facts); - // A render target or a storage view the device lacks for the format stays - // unavailable. + // A render target the device lacks for the format stays unavailable, unless the + // device renders the view of its word, which the twin's image lists. let usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; let plan = plan_image(&l, usage, false, &facts).expect(&what); assert!(plan.usage.contains(ImageUsageFlags::SAMPLED), "{what}"); - if !profile.supports_format( + let word = WordAttachment::of(pf, profile).map(|w| w.word_format()); + if let Some(word) = word { + assert!(plan.unavailable.is_empty(), "{what}: {plan:?}"); + assert!(plan.view_formats.contains(&word), "{what}: {plan:?}"); + } else if !profile.supports_format( direct_format(pf).expect(&what), FormatUsage::ColorAttachment, ) { @@ -636,6 +646,68 @@ fn twin_attachment_views_the_device_lacks_are_left_out() { ); } +/// A packed 16-bit render target a device samples but does not render renders through the view of +/// its word (`metal::format::WordAttachment`): its image keeps the format, mutable with extended +/// usage, takes the attachment usage and lists `R16_UINT`; where the device renders the format the +/// image takes neither, and one it does not hold is not planned so. +#[test] +fn packed_render_targets_the_device_cannot_render_take_their_word_view() { + let (mut with, mut without) = (0, 0); + for (name, desc, device) in committed() { + let facts = facts(&desc, &device); + for pf in [ + PixelFormat::A1BGR5Unorm, + PixelFormat::ABGR4Unorm, + PixelFormat::B5G6R5Unorm, + PixelFormat::BGR5A1Unorm, + ] { + let l = layout(TextureType::Type2D, pf, 1, 1); + for usage in [ + TextureUsage::RENDER_TARGET, + TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, + ] { + let what = format!("{name}: {pf:?} {usage:?}"); + let Ok(plan) = plan_image(&l, usage, false, &facts) else { + continue; + }; + let word = WordAttachment::of(pf, device.profile()); + match word { + Some(word) => { + with += 1; + assert_eq!(Some(plan.format), direct_format(pf), "{what}"); + assert!( + plan.usage.contains(ImageUsageFlags::COLOR_ATTACHMENT), + "{what}" + ); + assert!( + plan.flags.contains( + ImageCreateFlags::MUTABLE_FORMAT | ImageCreateFlags::EXTENDED_USAGE + ), + "{what}" + ); + assert!( + plan.view_formats.contains(&word.word_format()), + "{what}: {plan:?}" + ); + assert!( + !plan.unavailable.contains(TextureUsage::RENDER_TARGET), + "{what}" + ); + } + None => { + without += 1; + assert!(!plan.view_formats.contains(&Format::R16_UINT), "{what}"); + } + } + } + } + } + assert!( + with > 0 && without > 0, + "{with} with the word, {without} without" + ); +} + /// A `ulong` texture (`RG32Uint`) made for atomics takes the `R64_UINT` view its atomics update /// on every profile with that view's storage atomics, and only there; without `ShaderAtomic` it /// keeps its one format. diff --git a/crates/metal2vulkan-validation/build.rs b/crates/metal2vulkan-validation/build.rs index a6d6e8868..786ca90ef 100644 --- a/crates/metal2vulkan-validation/build.rs +++ b/crates/metal2vulkan-validation/build.rs @@ -158,6 +158,7 @@ fn main() { "metal2vulkan/src/metal/format/extended_srgb.rs", "metal2vulkan/src/metal/format/mod.rs", "metal2vulkan/src/metal/format/padded_srgb.rs", + "metal2vulkan/src/metal/format/word.rs", "metal2vulkan/src/metal/generated.rs", "metal2vulkan/src/metal/mod.rs", "metal2vulkan/src/metal/sampler.rs", diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN b/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN index cc173b76a..9ed7eaa75 100644 --- a/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN +++ b/crates/metal2vulkan-validation/fixtures/public/engine/TOOLCHAIN @@ -305,6 +305,7 @@ fixture unv_runtime_levels: metal: Apple metal version 32023.921 (metalfe-32023. fixture vft_tile_caller: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture vft_vertex_caller: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture vv1_sixteen_byte_units: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) +fixture wm_samples: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture wrg_cube_ties: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture wrg_gather_depth_positions: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) fixture wrg_sampler_positions: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425) diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/wm_samples.air.ll b/crates/metal2vulkan-validation/fixtures/public/engine/wm_samples.air.ll new file mode 100644 index 000000000..e85ff5da2 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/wm_samples.air.ll @@ -0,0 +1,173 @@ +; Generated by scripts/regen-air-fixtures from wm_samples.metal (typed pointers; xcrun metal-as reassembles it). Do not edit. +; ModuleID = '-' +source_filename = "-" +target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +%struct._texture_2d_ms_t = type opaque +%struct._sampler_t = type opaque +%struct._texture_2d_t = type opaque + +; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn +define <{ <4 x float> }> @wm_vertex(i32 noundef %0) local_unnamed_addr #0 { + %2 = shl i32 %0, 1 + %3 = and i32 %2, 2 + %4 = tail call fast float @air.convert.f.f32.u.i32(i32 %3) #8 + %5 = insertelement <2 x float> undef, float %4, i64 0 + %6 = and i32 %0, 2 + %7 = tail call fast float @air.convert.f.f32.u.i32(i32 %6) #8 + %8 = insertelement <2 x float> %5, float %7, i64 1 + %9 = fmul fast <2 x float> %8, + %10 = fadd fast <2 x float> %9, + %11 = shufflevector <2 x float> %10, <2 x float> poison, <4 x i32> + %12 = shufflevector <4 x float> %11, <4 x float> , <4 x i32> + %13 = insertvalue <{ <4 x float> }> undef, <4 x float> %12, 0 + ret <{ <4 x float> }> %13 +} + +; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn +declare float @air.convert.f.f32.u.i32(i32) local_unnamed_addr #1 + +; Function Attrs: mustprogress nofree norecurse nosync nounwind readnone willreturn +define <{ <4 x float> }> @wm_half_vertex(i32 noundef %0) local_unnamed_addr #2 { + %2 = icmp eq i32 %0, 1 + %3 = select fast i1 %2, float 1.000000e+00, float -1.000000e+00 + %4 = icmp eq i32 %0, 2 + %5 = select fast i1 %4, float 1.000000e+00, float -1.000000e+00 + %6 = insertelement <4 x float> , float %3, i64 0 + %7 = insertelement <4 x float> %6, float %5, i64 1 + %8 = insertvalue <{ <4 x float> }> undef, <4 x float> %7, 0 + ret <{ <4 x float> }> %8 +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind readnone willreturn +define <4 x float> @wm_fill(<4 x float> %0, <4 x float> addrspace(2)* nocapture noundef readonly "air-buffer-no-alias" %1) local_unnamed_addr #3 { + %3 = load <4 x float>, <4 x float> addrspace(2)* %1, align 16, !tbaa !36, !alias.scope !39 + ret <4 x float> %3 +} + +; Function Attrs: mustprogress nofree nounwind +define void @wm_read_samples(%struct._texture_2d_ms_t addrspace(1)* %0, <4 x float> addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %1, <2 x i32> noundef %2) local_unnamed_addr #4 { + %4 = extractelement <2 x i32> %2, i64 1 + %5 = shl i32 %4, 3 + %6 = extractelement <2 x i32> %2, i64 0 + %7 = add i32 %5, %6 + %8 = shl i32 %7, 2 + br label %10 + +9: ; preds = %10 + ret void + +10: ; preds = %3, %10 + %11 = phi i32 [ 0, %3 ], [ %18, %10 ] + %12 = tail call %struct._sampler_t addrspace(2)* @air.get_read_sampler() #9 + %13 = tail call { <4 x float>, i8 } @air.read_texture_2d_ms.v4f32(%struct._texture_2d_ms_t addrspace(1)* nocapture readonly %0, %struct._sampler_t addrspace(2)* %12, <2 x i32> %2, i32 %11, i32 1) #10 + %14 = extractvalue { <4 x float>, i8 } %13, 0 + %15 = add nuw nsw i32 %11, %8 + %16 = zext i32 %15 to i64 + %17 = getelementptr inbounds <4 x float>, <4 x float> addrspace(1)* %1, i64 %16 + store <4 x float> %14, <4 x float> addrspace(1)* %17, align 16, !tbaa !36, !alias.scope !42, !noalias !45 + %18 = add nuw nsw i32 %11, 1 + %19 = icmp eq i32 %18, 4 + br i1 %19, label %9, label %10, !llvm.loop !47 +} + +; Function Attrs: mustprogress nofree nounwind willreturn +define void @wm_read(%struct._texture_2d_t addrspace(1)* nocapture readonly %0, <4 x float> addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %1, <2 x i32> noundef %2) local_unnamed_addr #5 { + %4 = tail call %struct._sampler_t addrspace(2)* @air.get_read_sampler() #9 + %5 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly %0, %struct._sampler_t addrspace(2)* %4, <2 x i32> %2, <2 x i32> zeroinitializer, i32 0, i32 1) #10 + %6 = extractvalue { <4 x float>, i8 } %5, 0 + %7 = extractelement <2 x i32> %2, i64 1 + %8 = shl i32 %7, 3 + %9 = extractelement <2 x i32> %2, i64 0 + %10 = add i32 %8, %9 + %11 = zext i32 %10 to i64 + %12 = getelementptr inbounds <4 x float>, <4 x float> addrspace(1)* %1, i64 %11 + store <4 x float> %6, <4 x float> addrspace(1)* %12, align 16, !tbaa !36, !alias.scope !49, !noalias !52 + ret void +} + +; Function Attrs: inaccessiblememonly mustprogress nofree nounwind readonly willreturn +declare %struct._sampler_t addrspace(2)* @air.get_read_sampler() local_unnamed_addr #6 + +; Function Attrs: argmemonly mustprogress nofree nounwind readonly willreturn +declare { <4 x float>, i8 } @air.read_texture_2d_ms.v4f32(%struct._texture_2d_ms_t addrspace(1)* nocapture readonly, %struct._sampler_t addrspace(2)*, <2 x i32>, i32, i32) local_unnamed_addr #7 + +; Function Attrs: argmemonly mustprogress nofree nounwind readonly willreturn +declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly, %struct._sampler_t addrspace(2)*, <2 x i32>, <2 x i32>, i32, i32) local_unnamed_addr #7 + +attributes #0 = { mustprogress nofree nosync nounwind readnone willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { mustprogress nofree nosync nounwind readnone willreturn } +attributes #2 = { mustprogress nofree norecurse nosync nounwind readnone willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #3 = { mustprogress nofree norecurse nosync nounwind readnone willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #4 = { mustprogress nofree nounwind "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #5 = { mustprogress nofree nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #6 = { inaccessiblememonly mustprogress nofree nounwind readonly willreturn } +attributes #7 = { argmemonly mustprogress nofree nounwind readonly willreturn } +attributes #8 = { nounwind readnone willreturn } +attributes #9 = { inaccessiblememonly nounwind readonly willreturn } +attributes #10 = { argmemonly nounwind readonly willreturn } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.vertex = !{!9, !14} +!air.fragment = !{!15} +!air.kernel = !{!21, !27} +!air.compile_options = !{!30, !31, !32} +!llvm.ident = !{!33} +!air.version = !{!34} +!air.language_version = !{!35} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 0]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{<{ <4 x float> }> (i32)* @wm_vertex, !10, !12} +!10 = !{!11} +!11 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!12 = !{!13} +!13 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"id"} +!14 = !{<{ <4 x float> }> (i32)* @wm_half_vertex, !10, !12} +!15 = !{<4 x float> (<4 x float>, <4 x float> addrspace(2)*)* @wm_fill, !16, !18} +!16 = !{!17} +!17 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} +!18 = !{!19, !20} +!19 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position", !"air.arg_unused"} +!20 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} +!21 = !{void (%struct._texture_2d_ms_t addrspace(1)*, <4 x float> addrspace(1)*, <2 x i32>)* @wm_read_samples, !22, !23} +!22 = !{} +!23 = !{!24, !25, !26} +!24 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d_ms", !"air.arg_name", !"t"} +!25 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"} +!26 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"g"} +!27 = !{void (%struct._texture_2d_t addrspace(1)*, <4 x float> addrspace(1)*, <2 x i32>)* @wm_read, !22, !28} +!28 = !{!29, !25, !26} +!29 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!30 = !{!"air.compile.denorms_disable"} +!31 = !{!"air.compile.fast_math_enable"} +!32 = !{!"air.compile.framebuffer_fetch_enable"} +!33 = !{!"Apple metal version 32023.921 (metalfe-32023.921.6)"} +!34 = !{i32 2, i32 8, i32 0} +!35 = !{!"Metal", i32 4, i32 0, i32 0} +!36 = !{!37, !37, i64 0} +!37 = !{!"omnipotent char", !38, i64 0} +!38 = !{!"Simple C++ TBAA"} +!39 = !{!40} +!40 = distinct !{!40, !41, !"air-alias-scope-arg(1)"} +!41 = distinct !{!41, !"air-alias-scopes(wm_fill)"} +!42 = !{!43} +!43 = distinct !{!43, !44, !"air-alias-scope-arg(1)"} +!44 = distinct !{!44, !"air-alias-scopes(wm_read_samples)"} +!45 = !{!46} +!46 = distinct !{!46, !44, !"air-alias-scope-textures"} +!47 = distinct !{!47, !48} +!48 = !{!"llvm.loop.mustprogress"} +!49 = !{!50} +!50 = distinct !{!50, !51, !"air-alias-scope-arg(1)"} +!51 = distinct !{!51, !"air-alias-scopes(wm_read)"} +!52 = !{!53} +!53 = distinct !{!53, !51, !"air-alias-scope-textures"} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/wm_samples.ll b/crates/metal2vulkan-validation/fixtures/public/engine/wm_samples.ll new file mode 100644 index 000000000..423292782 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/wm_samples.ll @@ -0,0 +1,169 @@ +; Generated by scripts/regen-air-fixtures from wm_samples.metal (llvm-dis of wm_samples.air). Do not edit. +; ModuleID = '' +source_filename = "-" +target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) +define <{ <4 x float> }> @wm_vertex(i32 noundef %0) local_unnamed_addr #0 { + %2 = shl i32 %0, 1 + %3 = and i32 %2, 2 + %4 = tail call fast float @air.convert.f.f32.u.i32(i32 %3) #8 + %5 = insertelement <2 x float> undef, float %4, i64 0 + %6 = and i32 %0, 2 + %7 = tail call fast float @air.convert.f.f32.u.i32(i32 %6) #8 + %8 = insertelement <2 x float> %5, float %7, i64 1 + %9 = fmul fast <2 x float> %8, splat (float 2.000000e+00) + %10 = fadd fast <2 x float> %9, splat (float -1.000000e+00) + %11 = shufflevector <2 x float> %10, <2 x float> poison, <4 x i32> + %12 = shufflevector <4 x float> %11, <4 x float> , <4 x i32> + %13 = insertvalue <{ <4 x float> }> undef, <4 x float> %12, 0 + ret <{ <4 x float> }> %13 +} + +; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) +declare float @air.convert.f.f32.u.i32(i32) local_unnamed_addr #1 + +; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none) +define <{ <4 x float> }> @wm_half_vertex(i32 noundef %0) local_unnamed_addr #2 { + %2 = icmp eq i32 %0, 1 + %3 = select fast i1 %2, float 1.000000e+00, float -1.000000e+00 + %4 = icmp eq i32 %0, 2 + %5 = select fast i1 %4, float 1.000000e+00, float -1.000000e+00 + %6 = insertelement <4 x float> , float %3, i64 0 + %7 = insertelement <4 x float> %6, float %5, i64 1 + %8 = insertvalue <{ <4 x float> }> undef, <4 x float> %7, 0 + ret <{ <4 x float> }> %8 +} + +; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none) +define <4 x float> @wm_fill(<4 x float> %0, ptr addrspace(2) noundef readonly captures(none) "air-buffer-no-alias" %1) local_unnamed_addr #3 { + %3 = load <4 x float>, ptr addrspace(2) %1, align 16, !tbaa !36, !alias.scope !39 + ret <4 x float> %3 +} + +; Function Attrs: mustprogress nofree nounwind +define void @wm_read_samples(ptr addrspace(1) %0, ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %1, <2 x i32> noundef %2) local_unnamed_addr #4 { + %4 = extractelement <2 x i32> %2, i64 1 + %5 = shl i32 %4, 3 + %6 = extractelement <2 x i32> %2, i64 0 + %7 = add i32 %5, %6 + %8 = shl i32 %7, 2 + br label %10 + +9: ; preds = %10 + ret void + +10: ; preds = %10, %3 + %11 = phi i32 [ 0, %3 ], [ %18, %10 ] + %12 = tail call ptr addrspace(2) @air.get_read_sampler() #9 + %13 = tail call { <4 x float>, i8 } @air.read_texture_2d_ms.v4f32(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(2) %12, <2 x i32> %2, i32 %11, i32 1) #10 + %14 = extractvalue { <4 x float>, i8 } %13, 0 + %15 = add nuw nsw i32 %11, %8 + %16 = zext i32 %15 to i64 + %17 = getelementptr inbounds <4 x float>, ptr addrspace(1) %1, i64 %16 + store <4 x float> %14, ptr addrspace(1) %17, align 16, !tbaa !36, !alias.scope !42, !noalias !45 + %18 = add nuw nsw i32 %11, 1 + %19 = icmp eq i32 %18, 4 + br i1 %19, label %9, label %10, !llvm.loop !47 +} + +; Function Attrs: mustprogress nofree nounwind willreturn +define void @wm_read(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %1, <2 x i32> noundef %2) local_unnamed_addr #5 { + %4 = tail call ptr addrspace(2) @air.get_read_sampler() #9 + %5 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none) %0, ptr addrspace(2) %4, <2 x i32> %2, <2 x i32> zeroinitializer, i32 0, i32 1) #10 + %6 = extractvalue { <4 x float>, i8 } %5, 0 + %7 = extractelement <2 x i32> %2, i64 1 + %8 = shl i32 %7, 3 + %9 = extractelement <2 x i32> %2, i64 0 + %10 = add i32 %8, %9 + %11 = zext i32 %10 to i64 + %12 = getelementptr inbounds <4 x float>, ptr addrspace(1) %1, i64 %11 + store <4 x float> %6, ptr addrspace(1) %12, align 16, !tbaa !36, !alias.scope !49, !noalias !52 + ret void +} + +; Function Attrs: mustprogress nofree nounwind willreturn memory(inaccessiblemem: read) +declare ptr addrspace(2) @air.get_read_sampler() local_unnamed_addr #6 + +; Function Attrs: mustprogress nofree nounwind willreturn memory(argmem: read) +declare { <4 x float>, i8 } @air.read_texture_2d_ms.v4f32(ptr addrspace(1) readonly captures(none), ptr addrspace(2), <2 x i32>, i32, i32) local_unnamed_addr #7 + +; Function Attrs: mustprogress nofree nounwind willreturn memory(argmem: read) +declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) local_unnamed_addr #7 + +attributes #0 = { mustprogress nofree nosync nounwind willreturn memory(none) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { mustprogress nofree nosync nounwind willreturn memory(none) } +attributes #2 = { mustprogress nofree norecurse nosync nounwind willreturn memory(none) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #3 = { mustprogress nofree norecurse nosync nounwind willreturn memory(none) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #4 = { mustprogress nofree nounwind "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #5 = { mustprogress nofree nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #6 = { mustprogress nofree nounwind willreturn memory(inaccessiblemem: read) } +attributes #7 = { mustprogress nofree nounwind willreturn memory(argmem: read) } +attributes #8 = { nounwind willreturn memory(none) } +attributes #9 = { nounwind willreturn memory(inaccessiblemem: read) } +attributes #10 = { nounwind willreturn memory(argmem: read) } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.vertex = !{!9, !14} +!air.fragment = !{!15} +!air.kernel = !{!21, !27} +!air.compile_options = !{!30, !31, !32} +!llvm.ident = !{!33} +!air.version = !{!34} +!air.language_version = !{!35} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 0]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{ptr @wm_vertex, !10, !12} +!10 = !{!11} +!11 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!12 = !{!13} +!13 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"id"} +!14 = !{ptr @wm_half_vertex, !10, !12} +!15 = !{ptr @wm_fill, !16, !18} +!16 = !{!17} +!17 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} +!18 = !{!19, !20} +!19 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position", !"air.arg_unused"} +!20 = !{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"color"} +!21 = !{ptr @wm_read_samples, !22, !23} +!22 = !{} +!23 = !{!24, !25, !26} +!24 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d_ms", !"air.arg_name", !"t"} +!25 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 16, !"air.arg_type_align_size", i32 16, !"air.arg_type_name", !"float4", !"air.arg_name", !"out"} +!26 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"g"} +!27 = !{ptr @wm_read, !22, !28} +!28 = !{!29, !25, !26} +!29 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"} +!30 = !{!"air.compile.denorms_disable"} +!31 = !{!"air.compile.fast_math_enable"} +!32 = !{!"air.compile.framebuffer_fetch_enable"} +!33 = !{!"Apple metal version 32023.921 (metalfe-32023.921.6)"} +!34 = !{i32 2, i32 8, i32 0} +!35 = !{!"Metal", i32 4, i32 0, i32 0} +!36 = !{!37, !37, i64 0} +!37 = !{!"omnipotent char", !38, i64 0} +!38 = !{!"Simple C++ TBAA"} +!39 = !{!40} +!40 = distinct !{!40, !41, !"air-alias-scope-arg(1)"} +!41 = distinct !{!41, !"air-alias-scopes(wm_fill)"} +!42 = !{!43} +!43 = distinct !{!43, !44, !"air-alias-scope-arg(1)"} +!44 = distinct !{!44, !"air-alias-scopes(wm_read_samples)"} +!45 = !{!46} +!46 = distinct !{!46, !44, !"air-alias-scope-textures"} +!47 = distinct !{!47, !48} +!48 = !{!"llvm.loop.mustprogress"} +!49 = !{!50} +!50 = distinct !{!50, !51, !"air-alias-scope-arg(1)"} +!51 = distinct !{!51, !"air-alias-scopes(wm_read)"} +!52 = !{!53} +!53 = distinct !{!53, !51, !"air-alias-scope-textures"} diff --git a/crates/metal2vulkan-validation/fixtures/public/engine/wm_samples.metal b/crates/metal2vulkan-validation/fixtures/public/engine/wm_samples.metal new file mode 100644 index 000000000..bf63f45ec --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/engine/wm_samples.metal @@ -0,0 +1,41 @@ +// The functions of the word merge's multisampled lane (validation/src/runtime_lane/word_samples.rs), +// our own MSL: a fullscreen triangle and one over the lower left half of the target, a fragment +// writing the color in buffer 0, and kernels that read every sample of a 4-sample 8 x 8 texture and +// every texel of a single-sample one into buffer 1. +#include +using namespace metal; + +struct Position { + float4 position [[position]]; +}; + +vertex Position wm_vertex(uint id [[vertex_id]]) { + float2 p = float2((id << 1) & 2, id & 2); + Position out; + out.position = float4(p * 2.0 - 1.0, 0.0, 1.0); + return out; +} + +// Its edge runs through the target's texel centers on the diagonal from the top left. +vertex Position wm_half_vertex(uint id [[vertex_id]]) { + float2 p = float2(id == 1 ? 1.0 : -1.0, id == 2 ? 1.0 : -1.0); + Position out; + out.position = float4(p, 0.0, 1.0); + return out; +} + +fragment float4 wm_fill(Position in [[stage_in]], constant float4 *color [[buffer(0)]]) { + return color[0]; +} + +kernel void wm_read_samples(texture2d_ms t [[texture(0)]], + device float4 *out [[buffer(1)]], uint2 g [[thread_position_in_grid]]) { + for (uint s = 0; s < 4; s++) { + out[(g.y * 8 + g.x) * 4 + s] = t.read(g, s); + } +} + +kernel void wm_read(texture2d t [[texture(0)]], + device float4 *out [[buffer(1)]], uint2 g [[thread_position_in_grid]]) { + out[g.y * 8 + g.x] = t.read(g); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index 7fb6c2a4d..0dc1a85a9 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -740,6 +740,8 @@ mod wide_points; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod window_surfaces; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod word_samples; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod wrapped_buffers; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod ycbcr_minify; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/color_writes.rs b/crates/metal2vulkan-validation/src/runtime_lane/color_writes.rs index fa8d7f43d..178728b8a 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/color_writes.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/color_writes.rs @@ -28,6 +28,11 @@ //! A `half` output (probe 5, an M4) converts as its value does, and a half-float channel stores it //! as it is, a NaN's payload included; the half-output cases draw every `half`. //! +//! A packed format the device samples but does not render (the RTX 5080's `A1BGR5Unorm` and +//! `ABGR4Unorm`) draws through the view of its word, the word the fragment function encodes +//! (`metal::format::WordAttachment`): its cases must draw there, plain and blended alike, and say +//! so. +//! //! Each case draws the same inputs into the format, every channel of a texel the same input, //! plain and through blending with factors one and zero, reads the attachment back, and compares //! every channel with the rule. One difference is the recorded near-equivalent @@ -52,15 +57,16 @@ use crate::candidate::runtime_samples::{library, shape}; use crate::runtime_lane::buffer_with; use metal2vulkan::bind::SRGB_RESOLVE_THRESHOLDS; use metal2vulkan::error::DriverDeviation; -use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; +use metal2vulkan::metal::format::WordAttachment; +use metal2vulkan::metal::{BlendFactor, ColorWriteMask, PixelFormat, PrimitiveType, TextureUsage}; use metal2vulkan::pipeline::{ ColorAttachmentDescriptor, PrecisionNote, Reconvergence, RenderPipelineDescriptor, StageSource, }; use metal2vulkan::vk; use metal2vulkan::Budget; use metal2vulkan_runtime::{ - BlitOption, Degradation, LoadAction, PipelineOptions, RenderPassDescriptor, ResourceOptions, - StoreAction, TextureDescriptor, + BlitOption, ClearColor, Degradation, LoadAction, PipelineOptions, RenderPassDescriptor, + ResourceOptions, StoreAction, TextureDescriptor, }; use std::collections::BTreeSet; @@ -717,9 +723,25 @@ struct Drawn { /// the capability (4436). const IO16_CAPABILITY: [u32; 2] = [0x0002_0011, 4436]; -/// The texels a draw of `values` into `case`'s format stores, plain or through blending with -/// factors one and zero, and how the fragment stage was compiled; or why it could not draw. -fn drawn(lane: &Lane, case: &Case, values: &[f32], blended: bool) -> Result { +/// How a draw blends: not at all, with factors one and zero, or by premultiplied source-over (one +/// and one minus the source alpha, added, for color and alpha). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum DrawBlend { + Off, + Replace, + Over, +} + +/// The texels a draw of `values` into `case`'s format stores, blended by `blend`, and how the +/// fragment stage was compiled; or why it could not draw. Where `masked`, under that write mask +/// over a pass that clears to that color. +fn drawn( + lane: &Lane, + case: &Case, + values: &[f32], + blend: DrawBlend, + masked: Option<(ColorWriteMask, [f64; 4])>, +) -> Result { let device = &lane.device; let height = values.len().div_ceil(WIDTH); let library = library(device).map_err(|e| e.to_string())?; @@ -737,7 +759,14 @@ fn drawn(lane: &Lane, case: &Case, values: &[f32], blended: bool) -> Result Result DrawBlend::Replace, + false => DrawBlend::Off, + }; let Drawn { stored, noted, sixteen, rounded, - } = match drawn(&lane, case, &values, blended) { + } = match drawn(&lane, case, &values, blend, None) { Ok(drawn) => drawn, Err(why) => { eprintln!("color write {label} on {name}: {why}"); + if word.is_some() { + differ.push(format!("{label}: not drawn through its word view: {why}")); + } continue; } }; + if word.is_some() { + eprintln!("color write {label} on {name}: through the view of its word"); + } let (mut channels, mut wrong, mut examples) = (0usize, 0usize, Vec::new()); let (mut nans, mut stores) = (0usize, BTreeSet::new()); for (i, &x) in values.iter().enumerate() { @@ -889,6 +934,237 @@ fn draws_store_metals_codes() { quiet(lane, &messages); } +/// A packed 16-bit or two-channel 8-bit sRGB format's draw under a write mask of some of its +/// channels, over a pass that clears it: each written channel stores Metal's code of the output +/// and each kept one the code of the clear (Metal's rule of both). A format the device holds but +/// does not render must draw so through the view of its word (`metal::format::WordAttachment`), +/// which the fragment function merges into the texel's, in the pixel interlock or over the +/// attachment's input attachment on a device that orders fetch through them (lavapipe; an 8-bit +/// sRGB word), and says so. +#[test] +fn partly_masked_packed_formats_keep_their_fields() { + let (messages, _cache, lane) = lane(); + let name = lane.device.name().to_owned(); + let profile = lane.device.compile_device().profile().clone(); + // Each clear channel's code is clear of a tie at 4, 5 and 1 bits, so a device that clears a + // format it renders by its own conversion stores Metal's code too. + let clear = [0.2, 0.6, 0.8, 0.4]; + let masks = [ + ColorWriteMask::RED, + ColorWriteMask::RED | ColorWriteMask::GREEN, + ColorWriteMask::ALPHA, + ColorWriteMask::RED | ColorWriteMask::GREEN | ColorWriteMask::BLUE, + ]; + let mut differ = Vec::new(); + let cases = CASES.iter().filter(|c| { + matches!( + c.pf, + PixelFormat::A1BGR5Unorm | PixelFormat::ABGR4Unorm | PixelFormat::RG8UnormSRGB + ) && c.output == Output::Float + }); + for case in cases { + let values = (case.values)(); + let word = WordAttachment::of(case.pf, &profile); + for mask in masks { + let label = format!("{:?} under {mask:?}", case.pf); + let stored = match drawn(&lane, case, &values, DrawBlend::Off, Some((mask, clear))) { + Ok(drawn) => drawn.stored, + Err(why) => { + eprintln!("masked color write {label} on {name}: {why}"); + if word.is_some() { + differ.push(format!("{label}: not drawn through its word: {why}")); + } + continue; + } + }; + if word.is_some() { + eprintln!("masked color write {label} on {name}: its word merged into the texel's"); + } + let (mut channels, mut wrong, mut examples) = (0usize, 0usize, Vec::new()); + for (i, &x) in values.iter().enumerate() { + let texel = &stored[i * case.bytes..(i + 1) * case.bytes]; + // The case lists red, green, blue and alpha by their fields, least significant + // first; each channel's mask bit names it. + for &(offset, channel) in case.channels { + let lane_of = channel_lane(case.pf, offset); + let bit = [ + ColorWriteMask::RED, + ColorWriteMask::GREEN, + ColorWriteMask::BLUE, + ColorWriteMask::ALPHA, + ][lane_of]; + channels += 1; + let got = field(texel, offset, channel.bits()); + let want = match mask.contains(bit) { + true => metal(channel, x, false), + false => metal(channel, clear[lane_of] as f32, false), + }; + if got != want { + wrong += 1; + if examples.len() < 6 { + examples.push(format!( + "{x:e} at bit {offset}: {got:#x}, Metal's {want:#x}" + )); + } + } + } + } + if wrong == 0 { + eprintln!( + "masked color write {label} on {name}: Metal's, 0 of {channels} channels differ" + ); + } else { + eprintln!( + "masked color write {label} on {name}: {wrong} of {channels} channels differ: {}", + examples.join("; ") + ); + differ.push(format!("{label}: {wrong} of {channels}")); + } + } + } + assert!( + differ.is_empty(), + "masked color writes not Metal's: {differ:#?}" + ); + quiet(lane, &messages); +} + +/// `x` rounded to `half`, nearest even, for `x` in `[0, 2]`. +fn half_even(x: f64) -> f64 { + if x == 0.0 { + return 0.0; + } + let step = 2f64.powi((x.log2().floor() as i32).max(-14) - 10); + (x / step).round_ties_even() * step +} + +/// A packed 16-bit format's draw blended by premultiplied source-over (one and one minus the +/// source alpha, added, for color and alpha) over a pass that clears it to codes it holds exactly, +/// so Metal's tile holds the codes' values: each channel stores Metal's code of the blend, under +/// the fixture's fast math `h(fma(d, h(1 - a), s))`, the output clamped to `[0, 1]` (a NaN 0) and +/// rounded to `half` to nearest even, `a` its alpha, each code `c` of the clear read as +/// `h(c / m)`, the result's code to nearest even (the packed 16-bit blend sweep of the M3 Max +/// under macOS 27.0.1: every channel of this state, into each packed format, from `half4` and +/// `float4` outputs). A format the device samples but does not render must draw so through the +/// pixel interlock, which computes the blend over its word, and says so; a format the device +/// renders takes the device's blend, printed against Metal's and not held to it +/// (`DeviceColorConversion`). +#[test] +fn blended_packed_formats_store_metals_blend() { + let (messages, _cache, lane) = lane(); + let name = lane.device.name().to_owned(); + let profile = lane.device.compile_device().profile().clone(); + let mut differ = Vec::new(); + let cases = CASES + .iter() + .filter(|c| matches!(c.pf, PixelFormat::A1BGR5Unorm | PixelFormat::ABGR4Unorm)); + for case in cases { + let values = (case.values)(); + let word = WordAttachment::of(case.pf, &profile); + let layout = WordAttachment::layout(case.pf).expect("a packed format"); + // Red, green, blue and alpha codes, each the clear's exact value. + let codes = match case.pf { + PixelFormat::A1BGR5Unorm => [6u32, 18, 25, 1], + _ => [3, 9, 12, 6], + }; + let maxima = layout + .fields() + .map(|f| f.map_or(1, |f| (1u32 << f.bits) - 1)); + let clear: [f64; 4] = std::array::from_fn(|l| f64::from(codes[l]) / f64::from(maxima[l])); + let label = format!( + "{:?}{}", + case.pf, + if case.output == Output::Half { + " from half" + } else { + "" + } + ); + let stored = match drawn( + &lane, + case, + &values, + DrawBlend::Over, + Some((ColorWriteMask::ALL, clear)), + ) { + Ok(drawn) => drawn.stored, + Err(why) => { + eprintln!("blended color write {label} on {name}: {why}"); + if word.is_some() { + differ.push(format!("{label}: not drawn through the interlock: {why}")); + } + continue; + } + }; + if word.is_some() { + eprintln!( + "blended color write {label} on {name}: blended over its word in the interlock" + ); + } + let (mut channels, mut wrong, mut examples) = (0usize, 0usize, Vec::new()); + for (i, &x) in values.iter().enumerate() { + let texel = &stored[i * case.bytes..(i + 1) * case.bytes]; + // The output as the function returns it, clamped and rounded to `half`. + let out = match case.output { + Output::Float => f64::from(x), + Output::Half => f64::from(widen(narrow(x))), + }; + let s = match out.is_nan() { + true => 0.0, + false => half_even(out.clamp(0.0, 1.0)), + }; + let minus = half_even(1.0 - s); + for &(offset, channel) in case.channels { + let l = channel_lane(case.pf, offset); + channels += 1; + let m = f64::from(maxima[l]); + let d = half_even(f64::from(codes[l]) / m); + let v = half_even(d * minus + s); + let want = (v.clamp(0.0, 1.0) * m).round_ties_even() as u64; + let got = field(texel, offset, channel.bits()); + if got != want { + wrong += 1; + if examples.len() < 6 { + examples.push(format!( + "{x:e} at bit {offset}: {got:#x}, Metal's {want:#x}" + )); + } + } + } + } + if wrong == 0 { + eprintln!( + "blended color write {label} on {name}: Metal's, 0 of {channels} channels differ" + ); + } else { + eprintln!( + "blended color write {label} on {name}: {wrong} of {channels} channels differ: {}", + examples.join("; ") + ); + if word.is_some() { + differ.push(format!("{label}: {wrong} of {channels}")); + } + } + } + assert!( + differ.is_empty(), + "blended color writes not Metal's: {differ:#?}" + ); + quiet(lane, &messages); +} + +/// The channel (0 red to 3 alpha) whose field starts at bit `offset` of a texel of packed 16-bit +/// format `pf` (`metal::format::WordAttachment::layout`). +fn channel_lane(pf: PixelFormat, offset: u32) -> usize { + WordAttachment::layout(pf) + .and_then(|w| { + w.fields() + .iter() + .position(|f| f.is_some_and(|f| u32::from(f.shift) == offset)) + }) + .expect("a field of a packed format") +} + /// Render pipeline states, each made twice, announce their fragment stage's color writes once, /// with their stages' other kinds not announced before, and nothing else. A fragment function writing `float4` to an /// `RGBA8Unorm` attachment announces `shader-color-conversion` where the device does not convert diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index fce91b2ef..2e8dca9b4 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -107,8 +107,9 @@ //! over a buffer they do not store through the image its texture keeps in `kept_buffer_bytes` //! ([`KEPT_BYTES`]), the device's //! first sparse texture on a driver whose first sparse resource waits for every queue's work in -//! `first_use` ([`FIRST_SPARSE`]), visibility counts of draws writing several colors on a driver -//! that counts each sample once per color in `color_groups` ([`PER_COLOR_COUNTS`]), +//! `color_groups` ([`PER_COLOR_COUNTS`]), passes that load and draw a signed normalized attachment +//! holding a minimum code, or an `RGB9E5Float` one holding an unnormalized word, in +//! `snorm_tile_store` ([`SNORM_MINIMUM`], [`SHARED_EXPONENT`]), //! and //! pipeline states, whose stages' precision notes and reconvergence are announced where the //! runtime makes their objects (one site, which maps every note to its kind; a fragment function's @@ -187,6 +188,7 @@ use super::resource_ids::{ use super::rotated_textures::ROTATED_LOADS; use super::sample_copies::DRAWN_DEPTH; use super::shader_stencil::SHADOW; +use super::snorm_tile_store::{SHARED_EXPONENT, SNORM_MINIMUM}; use super::sparse_textures::SPARSE; use super::texture_blits::{MIPMAPS, TWINS, UPLOADS}; use super::tile_dispatches::TILE_DISPATCHES; @@ -510,6 +512,7 @@ fn every_kind_has_a_site_a_lane_test_takes() { &EXTENDED_RANGE_BITS, &UNREACHED_TILES, &SNORM_MINIMUM, + &SHARED_EXPONENT, &STORED_CODES, &UNADVERTISED_VERTEX_SIMDGROUPS, &YCBCR_FILTERS, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/snorm_tile_store.rs b/crates/metal2vulkan-validation/src/runtime_lane/snorm_tile_store.rs index 72a62997b..52616c82b 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/snorm_tile_store.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/snorm_tile_store.rs @@ -8,6 +8,7 @@ //! written back the same way, through their values, so a word whose largest mantissa is below 256 //! under an exponent above 0 is stored normalized (its mantissas shifted up as its exponent steps //! down; measured there too). +//! //! Under `TileStorePolicy::Device`, the default, the runtime keeps the device's load and store //! (docs/FAST-PATHS.md), so the texels keep their codes and words, and a draw in such a pass //! announces `snorm-minimum-kept` or `shared-exponent-kept`, naming the attachment. Under @@ -22,11 +23,16 @@ use metal2vulkan::device::{DriverFact, TileStorePolicy}; use metal2vulkan::metal::{ColorWriteMask, PixelFormat, TextureUsage}; use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; use metal2vulkan_runtime::{ + BlitOption, Degradation, Error, LoadAction, PipelineOptions, Region, RenderPassDescriptor, + ResourceOptions, StoreAction, Texture, TextureDescriptor, }; /// The kind a draw in a pass that loads a single-sampled signed normalized color announces. pub(super) const SNORM_MINIMUM: [Degradation; 1] = [Degradation::SnormMinimumKept]; +/// The kind a draw in a pass that loads a single-sampled `RGB9E5Float` color announces. +pub(super) const SHARED_EXPONENT: [Degradation; 1] = [Degradation::SharedExponentKept]; + /// The signed normalized formats Metal's tile store rewrites: each one's bytes a texel, the bytes /// of a channel's minimum code and those of the code above it, which Metal's pass stores. const FORMATS: [(PixelFormat, u64, &[u8], &[u8]); 6] = [ @@ -192,6 +198,7 @@ fn snorm_minimum_codes(tile_store: TileStorePolicy) { } quiet(lane, &messages); } + /// [`snorm_minimum_codes`] under the default, the device's load and store. #[test] fn a_drawing_pass_keeps_a_snorm_minimum_code_and_says_so() { @@ -204,23 +211,64 @@ fn the_exact_tile_store_raises_a_snorm_minimum_code() { snorm_minimum_codes(TileStorePolicy::Exact); } +/// A pass that loads a 4² `RGB9E5Float` target whose every word is unnormalized (mantissas 1, 2 +/// and 3 under the exponent 20: its largest mantissa below 256) and draws under a write mask of /// none of its channels, under `tile_store`: where the device's store is Metal's or the load pass /// rewrites the words (one load pass), every word takes Metal's (mantissas 128, 256 and 384 under /// the exponent 13) and nothing is announced; else every word stays and `shared-exponent-kept` is /// announced once (the device asks for it at each occurrence), naming color 0 and its format. A /// pass that loads it and draws nothing announces nothing. A device that renders no +/// `RGB9E5Float` (refusing its texture or pipeline state) takes neither, and says so. fn shared_exponent_words(tile_store: TileStorePolicy) { + let pf = PixelFormat::RGB9E5Float; let (messages, _cache, lane) = lane_with(|options| { options.announce_each = SHARED_EXPONENT.into_iter().collect(); options.policy.tile_store = tile_store; }); + let name = lane.device.name(); let (metals, rewritten) = expected(&lane, tile_store); + let mut descriptor = TextureDescriptor::texture_2d(pf, SIZE, SIZE, false); + descriptor.usage = TextureUsage::RENDER_TARGET; + descriptor.resource_options = ResourceOptions::shared(); + let t = match lane.device.new_texture(&descriptor) { + Ok(t) => t, + Err(Error::Unsupported(why)) => { + println!("SHARED-EXPONENT-SKIP {pf:?} on {name}: {why:?}"); + quiet(lane, &messages); + return; + } + Err(e) => panic!("{pf:?} on {name}: {e:?}"), + }; + let pipeline = match lane + .device + .new_render_pipeline_state(&unwritten(&lane, pf), &PipelineOptions::default()) + { + Ok(p) => p, + Err(Error::Unsupported(why)) => { + println!("SHARED-EXPONENT-SKIP {pf:?} pipeline on {name}: {why:?}"); + quiet(lane, &messages); + return; + } + Err(e) => panic!("{pf:?} pipeline on {name}: {e:?}"), + }; + let word: u32 = 1 | 2 << 9 | 3 << 18 | 20 << 27; let metal: u32 = 128 | 256 << 9 | 384 << 18 | 13 << 27; + let bytes = word.to_le_bytes().repeat((SIZE * SIZE) as usize); + t.replace_region(Region::new_2d(0, 0, SIZE, SIZE), 0, 0, &bytes, 4 * SIZE, 0) + .unwrap(); let before = load_passes(&lane); + lane.run(&pass(&t, LoadAction::Load), |l, e, h| { + l.draw(e, h, &pipeline, 0.5) + }) + .unwrap(); let loads = load_passes(&lane) - before; + let got = lane.read(&t, (0, 0), 4, BlitOption::None); + let notices = messages.take_notices(); + assert_eq!( loads, u64::from(rewritten), "{pf:?} {tile_store:?} on {name}: load passes" + ); if metals || rewritten { let normalized = metal.to_le_bytes().repeat((SIZE * SIZE) as usize); assert!( @@ -249,6 +297,14 @@ fn shared_exponent_words(tile_store: TileStorePolicy) { }); assert!(named, "{pf:?} on {name}: the notice names no color 0"); } + lane.run(&pass(&t, LoadAction::Load), |_, _, _| {}).unwrap(); + let notices = messages.take_notices(); + assert!( + !counts(¬ices).contains_key(&SHARED_EXPONENT[0]), + "{pf:?} on {name}: a pass of no draw" + ); + quiet(lane, &messages); +} /// [`shared_exponent_words`] under the default, the device's load and store. #[test] diff --git a/crates/metal2vulkan-validation/src/runtime_lane/word_samples.rs b/crates/metal2vulkan-validation/src/runtime_lane/word_samples.rs new file mode 100644 index 000000000..d867d0b6c --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/word_samples.rs @@ -0,0 +1,225 @@ +//! A partly masked draw into a 4-sample `RG8Unorm_sRGB` attachment on the device the cfg selects, +//! under the validation layer. On a device that renders the format only through the view of its +//! word (`metal::format::WordAttachment`) and orders fetch through rasterization-order input +//! attachments (lavapipe), the fragment function merges its word into each sample's own texel, +//! read through the attachment's input attachment at the invocation's sample +//! (`lower::fragment::word_input`), the pipeline running once per covered sample. +//! +//! The owned fixture `wm_samples` draws an 8 x 8 target: a pass clears it to (0.2, 0.6) and draws +//! (0.25, 0.75) over its lower left half under the full mask, so the samples of each texel on the +//! edge hold either color; a second pass loads it and draws (0.6, 0.1) over all of it under the red +//! bit alone. Every sample must then hold the second draw's red and keep its own green, and both +//! colors must be the ones a single-sample texture of the format stores under the same draws (a +//! path `runtime_lane::color_writes::partly_masked_packed_formats_keep_their_fields` holds to +//! Metal's codes). Each sample is read by a kernel through `texture2d_ms`, decoded through Metal's +//! table, so equal codes read equal values. + +use super::{buffer_with, read_buffer, validated_device_with, Messages, ScratchCache, WAIT}; +use crate::air_library::AirLibrary; +use crate::gpu::TEST_DEVICE; +use metal2vulkan::metal::format::WordAttachment; +use metal2vulkan::metal::{ColorWriteMask, PixelFormat, PrimitiveType, TextureType, TextureUsage}; +use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource, +}; +use metal2vulkan_devtools::{engine_dir, llvm_assemble}; +use metal2vulkan_runtime::{ + ClearColor, CommandBufferStatus, CommandQueue, Device, Library, LoadAction, PipelineOptions, + RenderPassDescriptor, ResourceOptions, Size, StoreAction, Texture, TextureDescriptor, +}; + +/// The target's side and samples. +const SIDE: u64 = 8; +const SAMPLES: u64 = 4; +const TEXELS: usize = (SIDE * SIDE) as usize; + +const PF: PixelFormat = PixelFormat::RG8UnormSRGB; +const CLEAR: [f64; 4] = [0.2, 0.6, 0.0, 1.0]; +const FIRST: [f32; 4] = [0.25, 0.75, 0.0, 1.0]; +const SECOND: [f32; 4] = [0.6, 0.1, 0.0, 1.0]; + +struct Lane { + device: Device, + queue: CommandQueue, + library: Library, +} + +impl Lane { + fn function(&self, name: &str) -> StageSource { + StageSource::Function( + self.library + .new_function_with_name(name) + .unwrap() + .function_descriptor(), + ) + } + + /// A private `RG8Unorm_sRGB` texture `samples` deep that renders and reads. + fn texture(&self, samples: u64) -> Texture { + let mut d = TextureDescriptor::texture_2d(PF, SIDE, SIDE, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = ResourceOptions::private(); + if samples > 1 { + d.texture_type = TextureType::Type2DMultisample; + d.sample_count = samples; + } + self.device + .new_texture(&d) + .unwrap_or_else(|e| panic!("a {samples}-sample texture: {e}")) + } + + /// A pass into `target`, cleared to [`CLEAR`] where `clear` and else loaded, drawing `color` + /// with `vertex` under `mask`. + fn pass( + &self, + target: &Texture, + clear: bool, + vertex: &str, + mask: ColorWriteMask, + color: [f32; 4], + ) { + let mut c = ColorAttachmentDescriptor::new(PF); + c.write_mask = mask; + let mut d = RenderPipelineDescriptor::new(self.function(vertex)); + d.fragment = Some(self.function("wm_fill")); + d.color_attachments[0] = Some(c); + d.raster_sample_count = target.sample_count() as u32; + let pipeline = self + .device + .new_render_pipeline_state(&d, &PipelineOptions::default()) + .unwrap_or_else(|e| panic!("{vertex} under {mask:?}: {e}")); + let mut pass = RenderPassDescriptor::new(); + let a = &mut pass.color_attachments[0]; + a.texture = Some(target.clone()); + a.store_action = StoreAction::Store; + match clear { + true => { + let [r, g, b, alpha] = CLEAR; + a.load_action = LoadAction::Clear; + a.clear_color = ClearColor::new(r, g, b, alpha); + } + false => a.load_action = LoadAction::Load, + } + let bytes: Vec = color.iter().flat_map(|v| v.to_le_bytes()).collect(); + let values = buffer_with(&self.device, &bytes).unwrap(); + let command_buffer = self.queue.command_buffer().unwrap(); + let mut e = command_buffer.render_command_encoder(&pass).unwrap(); + e.set_render_pipeline_state(&pipeline).unwrap(); + e.set_fragment_buffer(Some(&values), 0, 0).unwrap(); + e.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) + .unwrap(); + e.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + } + + /// Every texel's red and green bits as `kernel` reads them, `per` a texel (its samples). + fn read(&self, kernel: &str, t: &Texture, per: usize) -> Vec<[u32; 2]> { + let state = self + .device + .new_compute_pipeline_state( + &ComputePipelineDescriptor::new(self.function(kernel)), + &PipelineOptions::default(), + ) + .unwrap_or_else(|e| panic!("{kernel}: {e}")); + let length = 16 * TEXELS * per; + let out = buffer_with(&self.device, &vec![0xee; length]).unwrap(); + let command_buffer = self.queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&state).unwrap(); + encoder.set_buffer(Some(&out), 0, 1).unwrap(); + encoder.set_texture(Some(t), 0).unwrap(); + encoder + .dispatch_threads(Size::new(SIDE, SIDE, 1), Size::new(SIDE, SIDE, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + let bytes = read_buffer(&out, 0, length as u64).unwrap(); + bytes + .chunks(16) + .map(|t| { + let lane = |i: usize| u32::from_le_bytes(t[4 * i..4 * i + 4].try_into().unwrap()); + [lane(0), lane(1)] + }) + .collect() + } +} + +/// Each sample of a 4-sample `RG8Unorm_sRGB` target takes a red-masked draw's red and keeps its +/// own green: the samples of the texels on the first draw's edge keep greens that differ, each the +/// one a single-sample texture stores under the same draw. +#[test] +fn a_partly_masked_draw_merges_each_samples_own_word() { + let messages = Messages::default(); + let cache = ScratchCache::new().unwrap(); + let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |_| {}).unwrap(); + let bitcode = llvm_assemble(&engine_dir().join("wm_samples.ll")).unwrap(); + let lane = Lane { + queue: device.new_command_queue().unwrap(), + library: device.new_library_with_air(&bitcode).unwrap(), + device, + }; + let name = lane.device.name().to_owned(); + let word = WordAttachment::of(PF, lane.device.compile_device().profile()); + let red = ColorWriteMask::RED; + // The single-sample answers: the clear's green under a red-masked draw, and a full draw's + // green. + let one = lane.texture(1); + lane.pass(&one, true, "wm_vertex", red, SECOND); + let kept = lane.read("wm_read", &one, 1); + lane.pass(&one, true, "wm_vertex", ColorWriteMask::ALL, FIRST); + let drawn = lane.read("wm_read", &one, 1); + let ([red_bits, clear_green], [_, first_green]) = (kept[0], drawn[0]); + assert!(kept.iter().all(|t| *t == kept[0]) && drawn.iter().all(|t| *t == drawn[0])); + assert_ne!(clear_green, first_green); + // The 4-sample target: half drawn, then red-masked over all of it. + let ms = lane.texture(SAMPLES); + lane.pass(&ms, true, "wm_half_vertex", ColorWriteMask::ALL, FIRST); + let before = lane.read("wm_read_samples", &ms, SAMPLES as usize); + lane.pass(&ms, false, "wm_vertex", red, SECOND); + let after = lane.read("wm_read_samples", &ms, SAMPLES as usize); + let mut mixed = 0; + for texel in 0..TEXELS { + let samples = texel * SAMPLES as usize..(texel + 1) * SAMPLES as usize; + let greens: Vec = before[samples.clone()].iter().map(|s| s[1]).collect(); + for (s, &green) in greens.iter().enumerate() { + assert!( + green == clear_green || green == first_green, + "{name}: texel {texel} sample {s} held green {green:#x} before the masked draw" + ); + } + if greens.contains(&clear_green) && greens.contains(&first_green) { + mixed += 1; + } + for (s, (b, a)) in before[samples.clone()] + .iter() + .zip(&after[samples]) + .enumerate() + { + assert_eq!( + *a, + [red_bits, b[1]], + "{name}: texel {texel} sample {s}: before {b:x?}" + ); + } + } + println!( + "WORD-SAMPLES {name}: {} texels of {SAMPLES} samples merged, {mixed} on the edge with \ + both greens; {}", + TEXELS, + match word { + Some(_) => "through the view of its word", + None => "rendered in its own format", + } + ); + assert!(mixed > 0, "{name}: no texel's samples differ"); + drop(lane); + let reported = messages.take(); + assert!( + reported.is_empty(), + "the validation layer reported: {reported:#?}" + ); +} diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index e27167b0b..0d8f39d39 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -29,7 +29,7 @@ use crate::device::requirements::{ use crate::device::subgroup::SubgroupRequirement; use crate::library::{FunctionArtifact, FunctionCompileKey, KernelFacts}; use crate::metal; -use crate::metal::format::ExtendedRange; +use crate::metal::format::{ExtendedRange, WordAttachment, WordField}; use crate::metal::TextureWriteRoundingMode; use crate::pipeline::artifact::{ ComputePipeline, ComputePipelineMetalInfo, PrecisionNote, Reconvergence, RenderPipeline, @@ -1074,6 +1074,7 @@ codec_struct! { float_blend_colors, zero_indices, color_group, } ColorGroup { present, width, group } + WordField { shift, bits } SelectedWrite { lanes, rounds, nans } ExtendedRangeColor { form, blended, nearest_even } PulledInput { index, ty, fetch } @@ -1115,6 +1116,7 @@ codec_enum! { Bgr10 { srgb }, Bgra10 { srgb }, Planes { srgb }, R10X6, Rg10X12, R10X6Srgb, Rg10X12Srgb, R16Bfloat, Rg16Bfloat, Rgba16Bfloat, } + WordAttachment { Packed16 { fields }, Srgb8 { fields }, Rgb9e5 } FactorLane { Zero, One, Output(f0) } RotatedBlendForm { Premultiplied, Unmeasured } CaptureForm { Vertices, Indexed(f0) } @@ -1192,6 +1194,7 @@ codec_enum! { HeapRawSamples { stage, sampler }, ShaderStencilTest { formatless }, ExtendedRangeInputBlend { color, blend, kept }, + WordInputMerge { color, kept }, CrossClassReads { slot }, StorageTextureWriteRounding { slot, halves }, HeapWriteRounding { stage, halves }, diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index 2f4f4e6ce..04c12a7aa 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -227,6 +227,9 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { // Link gives the attachment no Vulkan blend and its input attachment, which the consumer // binds as `GraphicsState::input_attachments` states. RuntimeFact::ExtendedRangeInputBlend { .. } => Mechanism::RenderPassContract, + // Link writes the whole word and gives the attachment its input attachment, which the + // consumer binds as `GraphicsState::input_attachments` states. + RuntimeFact::WordInputMerge { .. } => Mechanism::RenderPassContract, // Keyed by the slots bound in a format of another numeric class than the declared one, // whose texels the function reads in that class. RuntimeFact::CrossClassReads { .. } => Mechanism::Variant, diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index d9633e7c5..ca065f57d 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -204,6 +204,10 @@ fn every_fact() -> Vec { }, kept: crate::vk::ColorComponentFlags::empty(), }, + RuntimeFact::WordInputMerge { + color: 1, + kept: crate::vk::ColorComponentFlags::G, + }, RuntimeFact::CrossClassReads { slot }, RuntimeFact::StorageTextureWriteRounding { slot, halves: true }, RuntimeFact::HeapWriteRounding { @@ -368,6 +372,7 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::SynthesizedGeometry { .. } => 88, RuntimeFact::ObjectThreadgroupArena { .. } => 89, RuntimeFact::ExactFormsOverCompilerLimit { .. } => 90, + RuntimeFact::WordInputMerge { .. } => 91, } } @@ -375,7 +380,7 @@ fn variant(f: &RuntimeFact) -> usize { fn mechanism_is_total_over_every_fact_and_profile() { let facts = every_fact(); let covered: std::collections::BTreeSet = facts.iter().map(variant).collect(); - assert_eq!(covered, (0..91).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..92).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -491,7 +496,8 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::ShaderTests { .. } | RuntimeFact::ShaderStencilTest { .. } | RuntimeFact::TileImageblock { .. } - | RuntimeFact::ExtendedRangeInputBlend { .. } => Mechanism::RenderPassContract, + | RuntimeFact::ExtendedRangeInputBlend { .. } + | RuntimeFact::WordInputMerge { .. } => Mechanism::RenderPassContract, RuntimeFact::ExecutionStatus => match f.buffer_access { crate::device::profile::BufferAccess::Addressed => Mechanism::PushConstant, _ => Mechanism::SyntheticBinding, diff --git a/crates/metal2vulkan/src/lower/arith/color_write.rs b/crates/metal2vulkan/src/lower/arith/color_write.rs index f3231aac6..2737402ed 100644 --- a/crates/metal2vulkan/src/lower/arith/color_write.rs +++ b/crates/metal2vulkan/src/lower/arith/color_write.rs @@ -515,6 +515,13 @@ pub fn small_float( } } +/// `v` (`f32` lanes of form `s`) rounded to the nearest `half`, ties to even, held in an `f32`: a +/// NaN stays a NaN and a value past the largest finite `half` an infinity (a packed 16-bit +/// format's channel reads it so, `ChannelWrite::HalfUnorm`). +pub(crate) fn half_rounded(fb: &mut FunctionBuilder<'_>, s: Form, v: Value) -> BResult { + float_nearest_even(fb, s, v, 10, true) +} + /// `v` (`f32` lanes of form `s`) rounded to nearest even to a float of a five-bit exponent (bias /// 15) and `mantissa` fraction bits, signed or not, held in an `f32` (see the module docs): `x`'s /// bits plus `2^(k-1) - 1` and the lowest kept bit, shifted right by the `k` bits dropped, is the diff --git a/crates/metal2vulkan/src/lower/arith/extended_range/blend.rs b/crates/metal2vulkan/src/lower/arith/extended_range/blend.rs index b6ae2b715..43c6c46c3 100644 --- a/crates/metal2vulkan/src/lower/arith/extended_range/blend.rs +++ b/crates/metal2vulkan/src/lower/arith/extended_range/blend.rs @@ -1218,6 +1218,54 @@ impl Blend { Ok(b) } + /// Metal's blend `eq` of a four-lane output of a module of math `math` into a packed 16-bit + /// unorm attachment (`B5G6R5Unorm`, `A1BGR5Unorm`, `ABGR4Unorm`, `BGR5A1Unorm`) storing the + /// channels `written` of four, computed by [`blend_packed16`] in `half` arithmetic whatever the + /// output's type, over the output clamped to `[0, 1]` and rounded to `half`, and the + /// destination's code decoded to `half` (alpha one in a format without it), the result stored + /// by Metal's write of the format's codes. Without fast math the 8-bit unorm blend's rounded + /// forms in `half` ([`Blend::unorm8`]); under fast math the 16-bit float blend's forms of four + /// channels ([`Blend::half_float`]), and a write mask of one color channel the 8-bit unorm + /// blend's scalar plan. Measured on plain Metal on the M3 Max under macOS 27.0.1, our own MSL: + /// 2,891 states (every factor and operation pair for color beside source-over alpha, the same + /// pair for both, and random states under random write masks, one blend color) over 8,192 + /// random pixels of `half4` and `float4` outputs into each of the four formats, under fast and + /// safe math. Without fast math every channel holds Metal's code; under fast math every channel + /// lies within one code of Metal's, and 3,527 of 94,732,288 channels miss it (`B5G6R5Unorm`; + /// at most 1,232 in each other format): Metal regroups some sums otherwise than either form. + /// A factor of the second source is not built (`Feature::FramebufferFetch` `NotImplemented`). + pub fn packed16( + eq: &BlendEquation, + written: ColorWriteMask, + math: BlendMath, + ) -> Result { + use BlendFactor as F; + let factors = [ + eq.source_rgb, + eq.destination_rgb, + eq.source_alpha, + eq.destination_alpha, + ]; + let second = |f: &BlendFactor| { + matches!( + f, + F::Source1Color + | F::OneMinusSource1Color + | F::Source1Alpha + | F::OneMinusSource1Alpha + ) + }; + if factors.iter().any(second) { + return Err(Unsupported::not_implemented(Feature::FramebufferFetch).into()); + } + let unorm8 = (true, Family::Unorm8(BlendArith::Half)); + match math { + BlendMath::Rounded => planned_for(eq, unorm8, written, (false, math)), + BlendMath::Fast => planned_for(eq, (true, Family::HalfFloat), written, (false, math)) + .or_else(|_| planned_for(eq, unorm8, written, (false, math))), + } + } + /// Whether every class the blend stores takes a form the 16-bit float sweeps fit in every state /// ([`Blend::half_float`]): the rounded forms without fast math; under fast math no term, one /// term, one fused multiply-add, a minimum or maximum, or a blend constant's difference @@ -2108,9 +2156,22 @@ pub fn blend_unorm8( (s, texel): (Value, Value), color: Option, ) -> BResult { - let f = floats(); let s = clamped(fb, s, (0.0, 1.0))?; let d = unorm8_tile_value(fb, texel, arith)?; + clamped_blend(fb, b, arith, (s, d), color) +} + +/// Blend `b` of the clamped output `s` over the destination `d`, both `vec4`s of `f32` in +/// `arith`, the blend color `color` clamped to `[0, 1]` (a NaN 0) and rounded to `arith`, and +/// its one minus that of the read: [`blend_unorm8`]'s and [`blend_packed16`]'s arithmetic. +fn clamped_blend( + fb: &mut FunctionBuilder<'_>, + b: &Blend, + arith: BlendArith, + (s, d): (Value, Value), + color: Option, +) -> BResult { + let f = floats(); let constant = match color { Some(words) => { let ft = ty(fb, f)?; @@ -2146,6 +2207,24 @@ pub fn blend_unorm8( lanes(fb, b, &inputs) } +/// Metal's blend `b` ([`Blend::packed16`]) of a four-lane output `s` (a `vec4` of `f32`: a +/// `half4` output's `half`s, or a `float4` one) over `d`, a packed 16-bit attachment's texel as +/// Metal's blend reads it (a `vec4` of `f32`, each channel its code over its maximum rounded to +/// `half`, a channel the format lacks 0, alpha 1), in `half` arithmetic: a `vec4` of `f32` holding +/// each blended lane, a `half`, which the caller stores as the format's codes. Metal clamps the +/// output to `[0, 1]` first, a NaN to 0, and rounds it to `half`, nearest even, a `float4` one too; +/// `color`, the blend color, reads as [`blend_unorm8`]'s in `half`. +pub fn blend_packed16( + fb: &mut FunctionBuilder<'_>, + b: &Blend, + (s, d): (Value, Value), + color: Option, +) -> BResult { + let f = floats(); + let s = clamped(fb, s, (0.0, 1.0))?; + clamped_blend(fb, b, BlendArith::Half, (s, d), color) +} + /// Metal's read of each lane of `texel` (a `vec4` of `f32`, an 8-bit unorm texel as the storage /// image reads it, `c / 255` for each code `c`, Vulkan's conversion of a normalized fixed-point /// value) in `arith`: the code `c` (the lane times 255, rounded to the nearest integer, which any diff --git a/crates/metal2vulkan/src/lower/arith/tests.rs b/crates/metal2vulkan/src/lower/arith/tests.rs index e7d54445c..504439453 100644 --- a/crates/metal2vulkan/src/lower/arith/tests.rs +++ b/crates/metal2vulkan/src/lower/arith/tests.rs @@ -4100,6 +4100,7 @@ mod atan2; mod bicubic; mod blend16; mod blend8; +mod blend_packed; mod color_write; mod depth16; mod divide; diff --git a/crates/metal2vulkan/src/lower/arith/tests/blend_packed.rs b/crates/metal2vulkan/src/lower/arith/tests/blend_packed.rs new file mode 100644 index 000000000..c385aea88 --- /dev/null +++ b/crates/metal2vulkan/src/lower/arith/tests/blend_packed.rs @@ -0,0 +1,295 @@ +//! A packed 16-bit word attachment's blend on the interpreter: the word read as Metal's blend +//! reads it (`stage_io::word_color::decode`), blended (`extended_range::blend::blend_packed16`), +//! encoded as Metal's word (`stage_io::word_color::encode`), and the fields of the channels the +//! write mask keeps taken from the word read, against words Metal stored. The words are the M3 +//! Max's under macOS 27.0.1 (plain Metal, our own MSL, a target loaded with the destination's +//! words): nine states of the packed 16-bit blend sweep (`Blend::packed16`) of every form the +//! planner names (a fused product, a contracted pair, a common factor, a lerp of the blend color, +//! minimum and maximum, write masks of one color channel, of red and alpha, and of all but red), +//! each into every packed 16-bit format from `half4` and `float4` outputs under fast and safe math, +//! over six pixels of the sweep: one with an infinite lane, one past both ends of `[0, 1]`, four +//! inside it. + +use super::*; +use crate::lower::arith::extended_range::blend::{blend_packed16, Blend, BlendMath}; +use crate::metal::format::WordAttachment; +use crate::metal::{BlendFactor, BlendOperation, ColorWriteMask, PixelFormat as P}; +use crate::pipeline::lower_inputs::BlendEquation; + +/// The pixels: the output's four lanes (as `f32` bits) and the destination's word. +const PIXELS: [([u32; 4], u16); 6] = [ + ([0x3f2dcb14, 0x3d46318c, 0x3df3cf3d, 0xff800000], 0x4955), + ([0x3f2cee30, 0xbe679b5a, 0x3eefbefc, 0x3ff7099d], 0xcae6), + ([0x3f1b0000, 0x3df42000, 0x3f54c000, 0x3f362000], 0x68b4), + ([0x3eb7870d, 0x3ebb68d0, 0x3ebcc000, 0x3f2b2000], 0x06ad), + ([0x3e082000, 0x3f665d72, 0x3f5fa000, 0x3f7aa000], 0x844b), + ([0x3d088889, 0x3f154000, 0x3e972000, 0x3f02c000], 0x3165), +]; + +/// The states: source and destination factors and operation of color, then alpha (Metal's +/// enumerations), the write mask, and the blend color (as `f32` bits). +const STATES: [([u32; 7], [u32; 4]); 9] = [ + ( + [1, 5, 0, 1, 5, 0, 15], + [0x3e99999a, 0x3f19999a, 0x3f666666, 0x3ee66666], + ), + ( + [4, 5, 0, 1, 5, 0, 15], + [0x3e99999a, 0x3f19999a, 0x3f666666, 0x3ee66666], + ), + ( + [14, 14, 0, 14, 1, 3, 4], + [0x3f76ceb7, 0x3e9e8f0f, 0x3ec3fe9a, 0x3da46ba8], + ), + ( + [11, 3, 0, 7, 14, 4, 15], + [0x3ee6c29e, 0x3f92f0c0, 0x3f3abf47, 0x3e9e5b86], + ), + ( + [5, 6, 2, 14, 7, 1, 15], + [0x3ec91e09, 0x3f2e55d9, 0xbe263f9d, 0x3f9d77bb], + ), + ( + [11, 2, 2, 11, 13, 1, 15], + [0x3e9b4ea9, 0x3f017c31, 0x3e62035b, 0x3df4d713], + ), + ( + [1, 1, 4, 1, 1, 4, 15], + [0x3e99999a, 0x3f19999a, 0x3f666666, 0x3ee66666], + ), + ( + [13, 12, 4, 14, 13, 0, 9], + [0x3e9b462a, 0xbdd04230, 0x3f403c27, 0x3eb75716], + ), + ( + [11, 11, 2, 9, 2, 1, 7], + [0x3f10cf42, 0x3e591def, 0xbe1e5284, 0x3f7b28e6], + ), +]; + +/// Metal's words, one row each: the state, the format, the output (`half4` or `float4`), the math +/// (fast or safe), and the word each pixel stored, in hex. +const WORDS: &str = "\ +0 B5G6R5 half fast f1b9 a80f b93f 5d30 273b 254c +0 B5G6R5 half safe f1b9 a80f b93f 5d30 273b 254c +0 B5G6R5 float fast f1b9 a80f b93f 5d30 273b 254c +0 B5G6R5 float safe f1b9 a80f b93f 5d30 273b 254c +0 A1BGR5 half fast f1dd a81f b93f 5d27 2737 2565 +0 A1BGR5 half safe f1dd a81f b93f 5d27 2737 2565 +0 A1BGR5 float fast f1dd a81f b93f 5d27 2737 2565 +0 A1BGR5 float safe f1dd a81f b93f 5d27 2737 2565 +0 ABGR4 half fast ea75 a07f b4fc 579e 2edf 297a +0 ABGR4 half safe ea75 a07f b4fc 579e 2edf 297a +0 ABGR4 float fast ea75 a07f b4fc 579e 2edf 297a +0 ABGR4 float safe ea75 a07f b4fc 579e 2edf 297a +0 BGR5A1 half fast 7d79 d40f e8bf ae50 939b 9eec +0 BGR5A1 half safe 7d79 d40f e8bf ae50 939b 9eec +0 BGR5A1 float fast 7d79 d40f e8bf ae50 939b 9eec +0 BGR5A1 float safe 7d79 d40f e8bf ae50 939b 9eec +1 B5G6R5 half fast 4955 a80f 88f8 3c2c 271b 1b07 +1 B5G6R5 half safe 4955 a80f 88f8 3c2c 271b 1b07 +1 B5G6R5 float fast 4955 a80f 88f8 3c2c 271b 1b07 +1 B5G6R5 float safe 4955 a80f 88f8 3c2c 271b 1b07 +1 A1BGR5 half fast 4955 a81f 88f5 3c1f 2737 1b1b +1 A1BGR5 half safe 4955 a81f 88f5 3c1f 2737 1b1b +1 A1BGR5 float fast 4955 a81f 88f5 3c1f 2737 1b1b +1 A1BGR5 float safe 4955 a81f 88f5 3c1f 2737 1b1b +1 ABGR4 half fast 4955 a07f 84cc 467e 2ddf 255a +1 ABGR4 half safe 4955 a07f 84cc 467e 2ddf 255a +1 ABGR4 float fast 4955 a07f 84cc 467e 2ddf 255a +1 ABGR4 float safe 4955 a07f 84cc 467e 2ddf 255a +1 BGR5A1 half fast 4955 d40f d498 a1ec 937b 99e7 +1 BGR5A1 half safe 4955 d40f d498 a1ec 937b 99e7 +1 BGR5A1 float fast 4955 d40f d498 a1ec 937b 99e7 +1 BGR5A1 float safe 4955 d40f d498 a1ec 937b 99e7 +2 B5G6R5 half fast 4995 caa6 6994 07ed 87eb 3585 +2 B5G6R5 half safe 4995 caa6 6994 07ed 87eb 3585 +2 B5G6R5 float fast 4995 caa6 6994 07ed 87eb 3585 +2 B5G6R5 float safe 4995 caa6 6994 07ed 87eb 3585 +2 A1BGR5 half fast 4995 caa6 6974 07ed 87cb 3565 +2 A1BGR5 half safe 4995 caa6 6974 07ed 87cb 3565 +2 A1BGR5 float fast 4995 caa6 6974 07ed 87cb 3565 +2 A1BGR5 float safe 4995 caa6 6974 07ed 87cb 3565 +2 ABGR4 half fast 4955 c9e6 69b4 0bad 8f4b 3965 +2 ABGR4 half safe 4955 c9e6 69b4 0bad 8f4b 3965 +2 ABGR4 float fast 4955 c9e6 69b4 0bad 8f4b 3965 +2 ABGR4 float safe 4955 c9e6 69b4 0bad 8f4b 3965 +2 BGR5A1 half fast 4975 caa6 6914 07cd 878b 3365 +2 BGR5A1 half safe 4975 caa6 6914 07cd 878b 3365 +2 BGR5A1 float fast 4975 caa6 6914 07cd 878b 3365 +2 BGR5A1 float safe 4975 caa6 6914 07cd 878b 3365 +3 B5G6R5 half fast 61b5 92ee 7196 2f31 8795 352a +3 B5G6R5 half safe 61b5 92ee 7196 2f31 8795 352a +3 B5G6R5 float fast 61b5 92ee 7196 2f31 8795 352a +3 B5G6R5 float safe 61b5 92ee 7196 2f31 8795 352a +3 A1BGR5 half fast 6197 92eb 716f 2f2d 87a9 3527 +3 A1BGR5 half safe 6199 92eb 716f 2f2d 87a9 3527 +3 A1BGR5 float fast 6197 92eb 716f 2f2d 87a9 3527 +3 A1BGR5 float safe 6199 92eb 716f 2f2d 87a9 3527 +3 ABGR4 half fast 6965 8adf 69bb 29ad 8eaf 3978 +3 ABGR4 half safe 6965 8adf 69bb 29ad 8eaf 3978 +3 ABGR4 float fast 6965 8adf 69bb 29ad 8eaf 3978 +3 ABGR4 float safe 6965 8adf 69bb 29ad 8eaf 3978 +3 BGR5A1 half fast 3d75 beee cd16 9b31 8f95 b2ea +3 BGR5A1 half safe 3d75 beee cd16 9b31 8f95 b2ea +3 BGR5A1 float fast 3d75 beee cd16 9b31 8f95 b2ea +3 BGR5A1 float safe 3d75 beee cd16 9b31 8f95 b2ea +4 B5G6R5 half fast 000b a101 0005 04a2 4223 0800 +4 B5G6R5 half safe 000b a101 0005 04a2 4223 0800 +4 B5G6R5 float fast 000b a101 0005 04a2 4223 0800 +4 B5G6R5 float safe 000b a101 0005 04a2 4223 0800 +4 A1BGR5 half fast 0000 a118 001c 0498 4240 080c +4 A1BGR5 half safe 0000 a118 001c 0498 4240 080c +4 A1BGR5 float fast 0000 a118 001c 0498 4240 080c +4 A1BGR5 float safe 0000 a118 001c 0498 4240 080c +4 ABGR4 half fast 0500 a7d0 0440 0150 4110 0000 +4 ABGR4 half safe 0500 a7d0 0440 0150 4110 0000 +4 ABGR4 float fast 0500 a7d0 0440 0150 4110 0000 +4 ABGR4 float safe 0500 a7d0 0440 0150 4110 0000 +4 BGR5A1 half fast 004b 2a21 4005 0142 0003 1000 +4 BGR5A1 half safe 004b 2a21 4005 0142 0003 1000 +4 BGR5A1 float fast 004b 2a21 4005 0142 0003 1000 +4 BGR5A1 float safe 004b 2a21 4005 0142 0003 1000 +5 B5G6R5 half fast 0002 5800 100b 0102 0844 0000 +5 B5G6R5 half safe 0002 5800 100b 0102 0844 0000 +5 B5G6R5 float fast 0002 5800 100b 0102 0844 0000 +5 B5G6R5 float safe 0002 5800 100b 0102 0844 0000 +5 A1BGR5 half fast 0000 580c 1020 010c 0840 0006 +5 A1BGR5 half safe 0000 580c 1020 010c 0840 0006 +5 A1BGR5 float fast 0000 580c 1020 010c 0840 0006 +5 A1BGR5 float safe 0000 580c 1020 010c 0840 0006 +5 ABGR4 half fast 0000 5051 1061 0020 0010 0010 +5 ABGR4 half safe 0000 5051 1061 0020 0010 0010 +5 ABGR4 float fast 0000 5051 1061 0020 0010 0010 +5 ABGR4 float safe 0000 5051 1061 0020 0010 0010 +5 BGR5A1 half fast 1802 1800 280b 0042 0004 0000 +5 BGR5A1 half safe 1802 1800 280b 0042 0004 0000 +5 BGR5A1 float fast 1802 1800 280b 0042 0004 0000 +5 BGR5A1 float safe 1802 1800 280b 0042 0004 0000 +6 B5G6R5 half fast a955 caef 991a 5ead 873b 34a9 +6 B5G6R5 half safe a955 caef 991a 5ead 873b 34a9 +6 B5G6R5 float fast a955 caef 991a 5ead 873b 34a9 +6 B5G6R5 float safe a955 caef 991a 5ead 873b 34a9 +6 A1BGR5 half fast a955 cae7 9935 5ead 8737 34a5 +6 A1BGR5 half safe a955 cae7 9935 5ead 8737 34a5 +6 A1BGR5 float fast a955 cae7 9935 5ead 8737 34a5 +6 A1BGR5 float safe a955 cae7 9935 5ead 8737 34a5 +6 ABGR4 half fast a955 caef 98cb 56ad 8ddf 3968 +6 ABGR4 half safe a955 caef 98cb 56ad 8ddf 3968 +6 ABGR4 float fast a955 caef 98cb 56ad 8ddf 3968 +6 ABGR4 float safe a955 caef 98cb 56ad 8ddf 3968 +6 BGR5A1 half fast 5555 d6ef e8ba aead 939b b249 +6 BGR5A1 half safe 5555 d6ef e8ba aead 939b b249 +6 BGR5A1 float fast 5555 d6ef e8ba aead 939b b249 +6 BGR5A1 float safe 5555 d6ef e8ba aead 939b b249 +7 B5G6R5 half fast a955 cae6 98b4 5ead 844b 3165 +7 B5G6R5 half safe a955 cae6 98b4 5ead 844b 3165 +7 B5G6R5 float fast a955 cae6 98b4 5ead 844b 3165 +7 B5G6R5 float safe a955 cae6 98b4 5ead 844b 3165 +7 A1BGR5 half fast a954 cae7 98b4 5ead 844b 3165 +7 A1BGR5 half safe a954 cae7 98b4 5ead 844b 3165 +7 A1BGR5 float fast a954 cae7 98b4 5ead 844b 3165 +7 A1BGR5 float safe a954 cae7 98b4 5ead 844b 3165 +7 ABGR4 half fast a952 caec 98b8 56ab 844d 3167 +7 ABGR4 half safe a952 caec 98b8 56ab 844d 3167 +7 ABGR4 float fast a952 caec 98b8 56ab 844d 3167 +7 ABGR4 float safe a952 caec 98b8 56ab 844d 3167 +7 BGR5A1 half fast 5555 d6e6 68b4 2ead 904b 3165 +7 BGR5A1 half safe 5555 d6e6 68b4 2ead 904b 3165 +7 BGR5A1 float fast 5555 d6e6 68b4 2ead 904b 3165 +7 BGR5A1 float safe 5555 d6e6 68b4 2ead 904b 3165 +8 B5G6R5 half fast 4820 c8a0 6800 00c0 8000 3000 +8 B5G6R5 half safe 4820 c8a0 6800 00c0 8000 3000 +8 B5G6R5 float fast 4820 c8a0 6800 00c0 8000 3000 +8 B5G6R5 float safe 4820 c8a0 6800 00c0 8000 3000 +8 A1BGR5 half fast 4840 c881 6801 00c0 8000 3000 +8 A1BGR5 half safe 4840 c881 6801 00c0 8000 3000 +8 A1BGR5 float fast 4840 c881 6801 00c0 8000 3000 +8 A1BGR5 float safe 4840 c881 6801 00c0 8000 3000 +8 ABGR4 half fast 4200 c203 6105 0000 8000 3003 +8 ABGR4 half safe 4200 c203 6105 0000 8000 3003 +8 ABGR4 float fast 4200 c203 6105 0000 8000 3003 +8 ABGR4 float safe 4200 c203 6105 0000 8000 3003 +8 BGR5A1 half fast 4840 48a0 e800 8440 0400 b000 +8 BGR5A1 half safe 4840 48a0 e800 8440 0400 b000 +8 BGR5A1 float fast 4840 48a0 e800 8440 0400 b000 +8 BGR5A1 float safe 4840 48a0 e800 8440 0400 b000 +"; + +#[test] +fn a_packed_word_attachment_blend_stores_metals_words() { + let f4 = vec(float(32), 4); + let u4 = vec(int(32), 4); + let factor = |x: u32| BlendFactor::try_from(x).expect("a factor"); + let operation = |x: u32| BlendOperation::try_from(x).expect("an operation"); + for row in WORDS.lines() { + let cols: Vec<&str> = row.split_whitespace().collect(); + let state: usize = cols[0].parse().expect("a state"); + let pf = match cols[1] { + "B5G6R5" => P::B5G6R5Unorm, + "A1BGR5" => P::A1BGR5Unorm, + "ABGR4" => P::ABGR4Unorm, + _ => P::BGR5A1Unorm, + }; + let (half, fast) = (cols[2] == "half", cols[3] == "fast"); + let words: Vec = (cols[4..].iter()) + .map(|w| u16::from_str_radix(w, 16).expect("a word")) + .collect(); + assert_eq!(words.len(), PIXELS.len(), "{row}"); + let (st, color) = STATES[state]; + let eq = BlendEquation { + source_rgb: factor(st[0]), + destination_rgb: factor(st[1]), + rgb_operation: operation(st[2]), + source_alpha: factor(st[3]), + destination_alpha: factor(st[4]), + alpha_operation: operation(st[5]), + }; + let mask = ColorWriteMask::try_from(st[6]).expect("a mask"); + let word = WordAttachment::layout(pf).expect("a word layout"); + // A channel the format lacks counts as written, as the storage form plans it. + let written = [ + ColorWriteMask::RED, + ColorWriteMask::GREEN, + ColorWriteMask::BLUE, + ColorWriteMask::ALPHA, + ] + .into_iter() + .zip(word.fields()) + .filter(|&(c, f)| mask.contains(c) || f.is_none()) + .fold(ColorWriteMask::NONE, |m, (c, _)| m.union(c)); + let kept: u32 = [ + ColorWriteMask::RED, + ColorWriteMask::GREEN, + ColorWriteMask::BLUE, + ColorWriteMask::ALPHA, + ] + .into_iter() + .zip(word.fields()) + .filter_map(|(c, f)| f.filter(|_| !mask.contains(c))) + .fold(0, |m, f| m | (((1u32 << f.bits) - 1) << f.shift)); + let math = match fast { + true => BlendMath::Fast, + false => BlendMath::Rounded, + }; + let what = format!("state {state} {pf:?} half {half} fast {fast}"); + let b = Blend::packed16(&eq, written, math).unwrap_or_else(|e| panic!("{what}: {e:?}")); + let cases: Vec = PIXELS + .iter() + .map(|(s, d)| { + let s = + s.iter() + .map(|&x| match half { + true => (f16_to_f64(f64_to_f16(f64::from(f32::from_bits(x)))) as f32) + .to_bits(), + false => x, + }) + .map(u64::from) + .collect(); + let c = color.iter().map(|&x| u64::from(x)).collect(); + vec![s, vec![u64::from(*d)], c] + }) + .collect(); + let expected = words; + } +} diff --git a/crates/metal2vulkan/src/lower/arith/tests/color_write.rs b/crates/metal2vulkan/src/lower/arith/tests/color_write.rs index 003f83e5f..1ac769b3e 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/color_write.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/color_write.rs @@ -894,3 +894,72 @@ fn half_bits_are_each_halfs_bits() { color_write::HALF_BITS_WORDS ); } + +/// A word attachment's encode (`stage_io::word_color::encode`) stores Metal's word for every +/// packed 16-bit layout: each lane rounded to `half`, then its code rounded to even +/// (`WordAttachment::output_word`, which the M3 Max's draws and clears matched on every texel), +/// over the values beside each code and tie of the 1-, 4-, 5- and 6-bit channels, the half grid +/// and the specials, each lane of a case a different value, and a three-lane output's alpha 1; +/// and `RGB9E5Float`'s word of a `float` output, its mantissas truncated, over those and values +/// across its range. +#[test] +fn word_attachments_store_metals_words() { + use crate::metal::format::WordAttachment; + use crate::metal::PixelFormat; + let mut values = Vec::new(); + for m in [1, 15, 31, 63] { + values.extend(around_codes(m, false, 1, 2)); + } + values.extend(half_values().into_iter().step_by(5)); + values.extend(specials()); + // `RGB9E5Float`'s range: past its largest, its smallest step, and between. + values.extend([ + 70000.0, + 65408.0, + 65409.0, + 1e-7, + 2f32.powi(-24), + 3e-5, + 1000.3, + 2.5, + 0.375, + ]); + let n = values.len(); + let quad = |i: usize| [0, 1, 2, 3].map(|l| values[(i + l * 7919) % n]); + for pf in [ + PixelFormat::B5G6R5Unorm, + PixelFormat::A1BGR5Unorm, + PixelFormat::ABGR4Unorm, + PixelFormat::BGR5A1Unorm, + PixelFormat::RGB9E5Float, + ] { + let word = WordAttachment::layout(pf).expect("a word layout"); + for lanes in [4u8, 3] { + let f = vec(float(32), lanes); + let cases: Vec = (0..n) + .map(|i| { + let q = quad(i); + vec![q[..usize::from(lanes)] + .iter() + .map(|x| u64::from(x.to_bits())) + .collect()] + }) + .collect(); + check_accept( + &format!("{pf:?} word of {lanes} lanes"), + &[f], + int(32), + &|fb, x| crate::lower::stage_io::word_color::encode(fb, word, (f, x[0]), None), + &cases, + &|c| { + let mut rgba = [0.0, 0.0, 0.0, 1.0]; + for (out, b) in rgba.iter_mut().zip(&c[0]) { + *out = f32::from_bits(*b as u32); + } + Some(vec![u64::from(word.output_word(rgba))]) + }, + &|g, w| g == w, + ); + } + } +} diff --git a/crates/metal2vulkan/src/lower/fragment/color.rs b/crates/metal2vulkan/src/lower/fragment/color.rs index 66e4674bb..a094beb85 100644 --- a/crates/metal2vulkan/src/lower/fragment/color.rs +++ b/crates/metal2vulkan/src/lower/fragment/color.rs @@ -148,6 +148,11 @@ pub(super) fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result, colors: &[ColorInput]) -> u64 { /// Declare one input attachment per color index the plan reads, multisampled for a per-sample /// function (`multisampled`), or its storage image in the interlocked storage form (`fetch`), which /// holds the samples as its view states; the storage image of every other attachment in that form -/// (one the function only writes); and the input attachment of every extended-range attachment -/// whose blend the function computes over it (`input_blend`). +/// (one the function only writes); the input attachment of every extended-range attachment whose +/// blend the function computes over it (`input_blend`); and that of every word attachment whose +/// word the function merges into the texel's (`word_input`), of `uint` texels. pub(super) fn declare( mb: &mut ModuleBuilder, colors: &[ColorInput], - (storage, blends): ( + (storage, blends, merges): ( &BTreeMap, &BTreeMap, + &BTreeMap, ), multisampled: bool, ) -> BResult> { @@ -340,7 +347,11 @@ pub(super) fn declare( e.insert(super::fetch::declare(mb, color, sc)?); } } - for (&color, _) in blends.iter().filter(|(_, ib)| ib.blend.is_some()) { + let blended = blends + .iter() + .filter(|(_, ib)| ib.blend.is_some()) + .map(|(&c, _)| c); + for color in blended.chain(merges.keys().copied()) { if let std::collections::btree_map::Entry::Vacant(e) = out.entry(color) { e.insert(input_attachment(mb, color, false, multisampled)?); } diff --git a/crates/metal2vulkan/src/lower/fragment/fetch.rs b/crates/metal2vulkan/src/lower/fragment/fetch.rs index 9940864f7..fb12ea96b 100644 --- a/crates/metal2vulkan/src/lower/fragment/fetch.rs +++ b/crates/metal2vulkan/src/lower/fragment/fetch.rs @@ -72,7 +72,22 @@ //! `unorm4x8_srgb`; EV XRR2-srgb1-m4 on the M4: every byte read, a texel an earlier draw of the //! pass wrote read as the decode of its stored byte, every encode threshold, 4, 194, 304 floats //! and every half written). The one- and two-channel sRGB formats are not measured, and stay -//! refused. +//! refused; a packed 16-bit format the device samples but does not render +//! (`metal::format::WordAttachment`: `A1BGR5Unorm`, `ABGR4Unorm` on the RTX 5080) through a view +//! of the attachment in its word's unsigned integer format (`R16_UINT`, `StorageView::word`): a +//! write stores Metal's word of the output (`stage_io::word_color::encode`), the fields of the +//! channels its write mask keeps taken from the word it reads first, so they keep their codes as +//! Metal's tile keeps them ([`word_texel`]). The pipeline sends such an attachment here where it +//! writes it unblended (or blended one and zero) under a mask of some of its channels, or +//! blended otherwise (`color_writes::stored_word`). A blended write computes Metal's packed +//! 16-bit blend of a `half4` or `float4` output over the word it reads +//! (`extended_range::Blend::packed16`, `stage_io::word_color::decode`): exact without fast math +//! over an attachment holding the codes Metal's tile does, within one code of Metal's under fast +//! math (Metal regroups some sums otherwise, 3,527 of 94,732,288 channels measured off by one), +//! and over a clear's or an earlier blend's result in the same pass, which Metal's tile holds as +//! a `half` finer than the codes the attachment holds (`PrecisionNote::DeviceColorConversion`, +//! noted for every such blend). An output of fewer lanes and a factor of the second source are +//! not built. A read of one is not built (`NotImplemented(Format)`). //! //! **Per sample**. Metal runs a function that reads a color attachment of a multisampled pass once //! per covered sample, reading its own sample, in draw order per sample, with `[[position]]`'s x @@ -247,6 +262,7 @@ use crate::lower::sync::memory_model; use crate::metal::format::{ accessed_without_format, color_output_components, rgba_twin, rgba_twin_gaps, sampled_type, spirv_image_format, without_format_gaps, ExtendedRange, FormatEmulation, StorageUse, + WordAttachment, }; use crate::metal::ColorWriteMask; use crate::pipeline::artifact::PrecisionNote; @@ -273,6 +289,12 @@ pub(crate) fn interlock_orders(p: &DeviceProfile) -> bool { !f.rasterization_order_color_access && f.pixel_interlock } +/// Whether `p` orders framebuffer fetch through rasterization-order input attachments (lavapipe): +/// rasterization-order color attachment access, which [`interlock_orders`] excludes. +pub(crate) fn inputs_order(p: &DeviceProfile) -> bool { + p.fields().fragment.rasterization_order_color_access +} + /// Whether `p` asks for Metal's 16-bit float blend of a `half4` output, computed by the function /// in the storage form (`DevicePolicy::half_blend`), which a device that orders fetch through /// the pixel interlock alone ([`interlock_orders`]) takes. @@ -294,9 +316,19 @@ pub(crate) fn unorm8_format(pf: crate::metal::PixelFormat) -> bool { matches!(pf, P::R8Unorm | P::RG8Unorm | P::RGBA8Unorm | P::BGRA8Unorm) } +/// Whether `pf` is a packed 16-bit unorm format (`metal::format::WordAttachment::Packed16`), whose +/// blend Metal computes in `half` over its decoded codes ([`extended_range::Blend::packed16`]). +pub(crate) fn packed16_format(pf: crate::metal::PixelFormat) -> bool { + matches!( + WordAttachment::layout(pf), + Some(WordAttachment::Packed16 { .. }) + ) +} + /// Metal's blend `eq` of a format held directly, which the shader computes in the storage form, /// storing the channels `written` of four under math `math`: an 8-bit unorm attachment's in -/// `arith` ([`extended_range::Blend::unorm8`]), else a 16-bit float one's +/// `arith` ([`extended_range::Blend::unorm8`]), a packed 16-bit one's +/// ([`extended_range::Blend::packed16`], in `half` whatever the output), else a 16-bit float one's /// ([`extended_range::Blend::half_float`], which takes its arithmetic when it computes). The /// planning callers pass `BlendArith::Half`: what is refused, what reads the blend color, and the /// words are the same in either arithmetic. @@ -309,6 +341,9 @@ fn direct_blend( extended_range::blend::BlendArith, ), ) -> Result { + if packed16_format(pf) { + return extended_range::Blend::packed16(eq, written, math); + } match unorm8_format(pf) { true => extended_range::Blend::unorm8(eq, pf, written, (math, arith)), false => extended_range::Blend::half_float(eq, pf, written, math), @@ -640,15 +675,20 @@ pub struct StorageView { /// image or written to it has red and blue exchanged ([`metal_order`]), so the function sees /// Metal's channels. `None` for another format and device. pub rgba_view: Option, + /// The word layout of a packed 16-bit attachment the device renders through a view of its + /// words (`metal::format::WordAttachment`): the view and the declaration are the word's + /// unsigned integer format, and a write encodes Metal's word ([`word_texel`]). `None` for + /// another format and device. + pub word: Option, } impl StorageView { /// The numeric class of the function's reads and writes: an extended-range attachment's /// values are floats, whatever its raw texels. pub fn read_class(&self) -> SampledType { - match (self.extended, self.uint_view) { - (Some(_), _) | (_, Some(_)) => SampledType::Float, - (None, None) => self.numeric, + match (self.extended, self.uint_view, self.word) { + (Some(_), _, _) | (_, Some(_), _) | (_, _, Some(_)) => SampledType::Float, + (None, None, None) => self.numeric, } } @@ -765,9 +805,10 @@ pub(crate) fn kept_channels( /// where it covers none of the format's channels, all where it covers every one, and for a mask /// covering some, every channel of the format but the first, the one mask that stands for them /// all), so the write masks of a class share one key and one module; any other format's `mask` as -/// it is. A blended 8-bit unorm attachment with alpha splits the partial class in three, as -/// Metal's blend forms do (`extended_range::Blend::unorm8`): alpha alone (`ALPHA`), one color -/// channel with or without alpha (`RED` and `ALPHA`), and two or more color channels. +/// it is. A blended 8-bit unorm attachment with alpha, or a blended packed 16-bit one, splits the +/// partial class in three, as Metal's blend forms do (`extended_range::Blend::unorm8`, +/// `extended_range::Blend::packed16`): alpha alone (`ALPHA`), one color channel with or without +/// alpha (`RED` and `ALPHA`), and two or more color channels. pub(crate) fn compiled_write_mask( pf: crate::metal::PixelFormat, mask: ColorWriteMask, @@ -786,7 +827,9 @@ pub(crate) fn compiled_write_mask( .into_iter() .filter(|&c| written.contains(c)) .count(); - let unorm8 = blended && unorm8_format(pf) && all.contains(ColorWriteMask::ALPHA); + // Metal's blend forms differ by the class (`extended_range::Blend::unorm8`, `packed16`). + let unorm8 = blended + && ((unorm8_format(pf) && all.contains(ColorWriteMask::ALPHA)) || packed16_format(pf)); if written.is_empty() { ColorWriteMask::NONE } else if written == all { @@ -824,12 +867,20 @@ pub(crate) fn storage_form( index: color, }))?; let pf = attachment.pixel_format; + // A packed 16-bit attachment the device samples but does not render renders through a view of + // its words, which the function stores as Metal's word and merges by its fields. + let word = WordAttachment::of(pf, p); let usages = BTreeSet::from([FormatUsage::ColorAttachment]); - let mapping = crate::metal::format::vk_format(pf, &usages, p)?; + let (format, emulation) = match word { + Some(word) => (word.word_format(), FormatEmulation::Direct), + None => { + let mapping = crate::metal::format::vk_format(pf, &usages, p)?; + (mapping.format, mapping.emulation) + } + }; // An extended-range attachment holds Metal's raw texels in its raw format, which a read // decodes. let extended = ExtendedRange::of(pf); - let format = mapping.format; let srgb = format .block() .is_some_and(|b| b.color == Some(vk::NumericFormat::Srgb)); @@ -843,7 +894,7 @@ pub(crate) fn storage_form( // and blue the function exchanges on every read and write: the device converts each channel // as it converts the attachment's, so the values are those of the attachment's own view. let alias = StorageAttachmentUse::view_alias_of(format, p) - .filter(|_| mapping.emulation == FormatEmulation::Direct); + .filter(|_| emulation == FormatEmulation::Direct && word.is_none()); let uint_view = alias.filter(|&u| srgb && u == vk::Format::R32_UINT); let rgba_view = alias.filter(|_| !srgb); let viewed = uint_view.or(rgba_view).unwrap_or(format); @@ -893,8 +944,19 @@ pub(crate) fn storage_form( && attachment.equation.is_some_and(|eq| { extended_range::Blend::unorm8(&eq, pf, written_of_four, (use_.math, half)).is_ok() }); + // And the blend of a packed 16-bit attachment rendered through its word view, which no + // device blends (`extended_range::Blend::packed16`: every factor and operation but the second + // source's, any write mask). + let word_blend = packed16_format(pf) + && word.is_some() + && attachment.blending_enabled + && !attachment.replaces + && attachment.equation.is_some_and(|eq| { + extended_range::Blend::packed16(&eq, written_of_four, use_.math).is_ok() + }); let blend = attachment.equation.filter(|_| { - (extended.is_some_and(|e| !e.padded()) || half_blend || unorm8_blend) && stores + (extended.is_some_and(|e| !e.padded()) || half_blend || unorm8_blend || word_blend) + && stores }); if let Some(eq) = blend { let planned = match extended { @@ -922,6 +984,8 @@ pub(crate) fn storage_form( && !shader_blends && (attachment.blending_enabled || !kept.is_empty())) || (srgb && uint_view.is_none()) + // An `RGB9E5Float` word's mantissas share its exponent: no field is kept apart. + || (word == Some(WordAttachment::Rgb9e5) && stores && merged) // Metal's blend into an sRGB attachment, a replacing one too, is not measured. || (uint_view.is_some() && stores && attachment.blending_enabled) || (writes @@ -995,9 +1059,9 @@ pub(crate) fn storage_form( None } }; - let numeric = match (extended, uint_view) { - (Some(_), _) | (_, Some(_)) => SampledType::Uint, - (None, None) => sampled_type(pf).ok_or_else(not_implemented)?, + let numeric = match (extended, uint_view, word) { + (Some(_), _, _) | (_, Some(_), _) | (_, _, Some(_)) => SampledType::Uint, + (None, None, None) => sampled_type(pf).ok_or_else(not_implemented)?, }; match declared { Some(declared) if common.is_empty() && route.is_empty() => Ok(Ok(StorageView { @@ -1012,6 +1076,7 @@ pub(crate) fn storage_form( blend, uint_view, rgba_view, + word, })), _ => { // A BGRA-order format no declaration reaches, whose RGBA-order twin lacks something @@ -1430,10 +1495,21 @@ pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> { }); let unorm8 = unorm8_format(view.pixel_format); match (planned, blended_output(cx.entry, color)) { - // An 8-bit unorm blend of fewer lanes is not measured. - (Some(Ok(_)), Some((_, lanes))) if unorm8 && lanes < 4 => { + // An 8-bit unorm or packed 16-bit blend of fewer lanes is not measured. + (Some(Ok(_)), Some((_, lanes))) + if (unorm8 || view.word.is_some()) && lanes < 4 => + { Err(not_implemented()) } + // A packed 16-bit blend reads the attachment's codes, where Metal's tile holds + // a clear's or an earlier blend's value finer, and under fast math sums some + // states otherwise (`extended_range::Blend::packed16`): a near-equivalent the + // function notes, taken whether or not the function reads the attachment, as + // no device blends the format. + (Some(Ok(_)), Some(_)) if view.word.is_some() => { + sixteen_exact = false; + Ok((view, None)) + } (Some(Ok(b)), Some((_, lanes))) => { let stated = cx.entry.compile.fast_math.is_some(); // An output of fewer lanes whose color blend reads the source alpha stores @@ -1510,7 +1586,9 @@ pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> { if half.is_ok_and(|h| h.reads_constant()) { cx.push.insert(PushField::HalfBlendColor); } - if !sixteen_exact { + if view.word.is_some() { + cx.precision.insert(PrecisionNote::DeviceColorConversion); + } else if !sixteen_exact { let note = crate::lower::arith::output_precision::half_output_note(cx); cx.precision.insert(note); } @@ -1660,6 +1738,11 @@ pub(super) fn select_read(cx: &mut SelectCx<'_>, c: ColorInput) -> Result<(), Er let Some(sc) = cx.families.fragment.fetch.get(&c.color).copied() else { return Err(cx.invariant("a storage-form read of an attachment of another form")); }; + // A word attachment's read decodes the word, which is not built. + if sc.view.word.is_some() { + let refused = Unsupported::not_implemented(Feature::Format); + return Err(refused.at_attachment(Attachment::Color(c.color)).into()); + } class_of(c.form, sc.view.read_class(), c.color, false)?; // An `_sRGB` extended-range texel decodes through Metal's table. if let Some(e) = sc.view.extended { @@ -1783,9 +1866,29 @@ pub fn select_output( } plan_sample(cx)?; // The write rounds to the code Metal stores where the format converts it; an sRGB attachment's - // write encodes its bytes itself (`math::pack` of a `float` or `half` output), and records the + // write encodes its bytes itself (`math::pack` of a `float` or `half` output), and a word + // attachment's Metal's word of a `float` or `half` output ([`word_texel`]): each records the // pipeline's map, which link checks, without rounding a lane. - if sc.view.uint_view.is_some() { + if sc.view.word.is_some() { + let measured = matches!( + form.float_fmt(), + Some(crate::lower::arith::FloatFmt::F32 | crate::lower::arith::FloatFmt::Half) + ); + if !measured { + return Err(Unsupported::not_implemented(Feature::Format).into()); + } + // An 8-bit sRGB word encodes through Metal's table. + if let Some(WordAttachment::Srgb8 { .. }) = sc.view.word { + cx.families.arith.srgb.get_or_insert(PackDir::Pack); + } + if let Some(rules) = cx.inputs.color_writes.get(&color).copied() { + cx.families + .stage_io + .interface + .color_writes + .insert(color, rules); + } + } else if sc.view.uint_view.is_some() { let measured = matches!( form.float_fmt(), Some(crate::lower::arith::FloatFmt::F32 | crate::lower::arith::FloatFmt::Half) @@ -1881,8 +1984,9 @@ pub(super) fn words(cx: &SelectCx<'_>, uses: u64, rets: u64) -> u64 { .fold(0u64, u64::saturating_add); // A 16-bit float attachment's blended write reads its texel and blends in `half`, or in // `float` with exact multiply-adds (twice the words) and Metal's conversion of the result; an - // 8-bit unorm one's clamps the output, decodes the codes by exact division (about 45 instructions) and stores by - // Metal's unorm rule (`arith::color_write::channel_words`). + // 8-bit unorm one's clamps the output, decodes the codes by exact division (about 45 + // instructions) and stores by Metal's unorm rule (`arith::color_write::channel_words`); a + // packed 16-bit one's clamps the output and rounds it to `half`, and decodes the word. let sixteen: u64 = fetch .values() .filter(|sc| sc.view.extended.is_none()) @@ -1899,10 +2003,15 @@ pub(super) fn words(cx: &SelectCx<'_>, uses: u64, rets: u64) -> u64 { } false => 0, }; + let packed = match sc.view.word { + Some(_) => 48 * 6 + stage_io::word_color::DECODE_WORDS, + None => 0, + }; Some( READ.saturating_add(2 * u64::from(b.words())) .saturating_add(32 * 6) - .saturating_add(unorm8), + .saturating_add(unorm8) + .saturating_add(packed), ) }) .fold(0u64, u64::saturating_add); @@ -1936,6 +2045,14 @@ pub(super) fn words(cx: &SelectCx<'_>, uses: u64, rets: u64) -> u64 { .filter(|sc| sc.writes && sc.view.uint_view.is_some()) .count() as u64; let srgb_write = READ.saturating_add(u64::from(3 * srgb::SEARCH_WORDS) + 400); + // A word attachment's write encodes Metal's word and merges the kept fields: its kept mask + // from the draw's four bits (a test and a select per field). + let word_write: u64 = fetch + .values() + .filter(|sc| sc.writes) + .filter_map(|sc| sc.view.word) + .map(|w| stage_io::word_color::encode_words(w) + 4 * 24 + 40) + .fold(0u64, u64::saturating_add); let write = WRITE .saturating_mul(written) .saturating_add(READ.saturating_mul(merged)) @@ -1944,6 +2061,7 @@ pub(super) fn words(cx: &SelectCx<'_>, uses: u64, rets: u64) -> u64 { .saturating_add(sixteen) .saturating_add(stage_io::extended_color::WORDS.saturating_mul(unblended)) .saturating_add(srgb_write.saturating_mul(srgb_writes)) + .saturating_add(word_write) .saturating_add((READ + WRITE + 8).saturating_mul(shadowed)) .saturating_add((2 * EXCHANGE).saturating_mul(exchanged)) .saturating_add(40); @@ -2278,6 +2396,7 @@ pub(super) fn emit_return( extended_range::encode(fb, range, v, table)? } (None, _) if sc.view.uint_view.is_some() => srgb_texel(cx, fb, color, &sc, form, part)?, + (None, _) if sc.view.word.is_some() => word_texel(cx, fb, color, &sc, form, part)?, (None, _) => { // Metal's 16-bit float blend of an output of one to four lanes, or its 8-bit unorm // blend of four, over the texel. @@ -2821,6 +2940,124 @@ fn srgb_texel( fb.composite_construct(uvec4, &[word, zero, zero, zero]) } +/// The `uvec4` texel that writes output `part` of `form` (`float` or `half` lanes) to word +/// attachment `color` (`StorageView::word`): Metal's word of the output +/// (`stage_io::word_color::encode`), or under a blend (`StorageView::blend`) of Metal's blend of +/// the four-lane output over the word read first at the pixel, inside the interlock, as Metal's +/// blend reads it (`stage_io::word_color::decode`, `extended_range::blend::blend_packed16`, the +/// blend color from `PushField::HalfBlendColor` where the blend reads it); and where the write +/// keeps some of the format's channels, the fields of those channels taken from the word read +/// first, so they keep their codes as Metal's tile keeps them. The kept channels are the draw's +/// (`PushField::StorageKeptChannels`) where the write takes them from it +/// (`StorageView::kept_at_draw`), else the view's. +fn word_texel( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + color: u32, + sc: &StorageColor, + form: Form, + part: SValue, +) -> BResult { + let Some(word) = sc.view.word else { + return Err(cx.fail("a word texel of an attachment without a word")); + }; + // The word read first, where the blend reads it. + let mut read = None; + let mut value = match sc.view.blend { + Some(eq) => { + if form.lanes != 4 { + return Err(cx.fail("a packed 16-bit blend of another output")); + } + let math = extended_range::blend::BlendMath::of(cx.entry.compile.fast_math); + let Ok(b) = extended_range::Blend::packed16(&eq, written(sc.view.kept), math) else { + return Err(cx.fail("a packed 16-bit blend outside Metal's model")); + }; + let texel = read_texel(cx, fb, color, sc)?; + let old = fb.composite_extract(texel, &[0])?; + read = Some(old); + let d = stage_io::word_color::decode(fb, word, old)?; + let constant = match b.reads_constant() { + true => { + let field = cx.push_field(fb, PushField::HalfBlendColor)?; + Some(fb.composite_extract(field, &[0])?) + } + false => None, + }; + let v = extended_range::blend::blend_packed16(fb, &b, (part, d), constant)?; + let f4 = form.with(Held::Float(FloatFmt::F32)); + stage_io::word_color::encode(fb, word, (f4, v), None)? + } + None => { + let srgb = stage_io::word_color::srgb_table(cx); + stage_io::word_color::encode(fb, word, (form, part), srgb)? + } + }; + if sc.view.merges() { + let channels = [ + vk::ColorComponentFlags::R, + vk::ColorComponentFlags::G, + vk::ColorComponentFlags::B, + vk::ColorComponentFlags::A, + ]; + let field_bits = |f: crate::metal::format::WordField| ((1u32 << f.bits) - 1) << f.shift; + let keep = match sc.view.kept_at_draw { + // Bit `c` of the color's four in the draw's word keeps channel `c`'s field. + true => { + let draw = cx.push_field(fb, PushField::StorageKeptChannels)?; + let shift = fb.u32_const(4 * color)?; + let shift = fb.module().const_value(shift)?; + let bits = fb.binary(BinOp::ShiftRightLogical, draw, shift)?; + let zero = fb.u32_const(0)?; + let zero = fb.module().const_value(zero)?; + let mut keep = zero; + for (lane, field) in word.fields().into_iter().enumerate() { + let Some(field) = field else { + continue; + }; + let bit = fb.u32_const(1 << lane)?; + let bit = fb.module().const_value(bit)?; + let set = fb.binary(BinOp::BitwiseAnd, bits, bit)?; + let set = fb.binary(BinOp::INotEqual, set, zero)?; + let mask = fb.u32_const(field_bits(field))?; + let mask = fb.module().const_value(mask)?; + let mask = fb.select(set, mask, zero)?; + keep = fb.binary(BinOp::BitwiseOr, keep, mask)?; + } + keep + } + false => { + let mask = channels + .iter() + .zip(word.fields()) + .filter(|(c, _)| sc.view.kept.contains(**c)) + .filter_map(|(_, f)| f) + .fold(0u32, |m, f| m | field_bits(f)); + let mask = fb.u32_const(mask)?; + fb.module().const_value(mask)? + } + }; + let old = match read { + Some(old) => old, + None => { + let texel = read_texel(cx, fb, color, sc)?; + fb.composite_extract(texel, &[0])? + } + }; + let old = fb.binary(BinOp::BitwiseAnd, old, keep)?; + let write = fb.unary(UnOp::Not, keep)?; + let new = fb.binary(BinOp::BitwiseAnd, value, write)?; + value = fb.binary(BinOp::BitwiseOr, old, new)?; + } + let u32_ = fb.module().ty(SType::Int { + width: 32, + signed: false, + })?; + let uvec4 = fb.module().ty(SType::Vector { elem: u32_, len: 4 })?; + let zero = fb.u32_const(0)?; + let zero = fb.module().const_value(zero)?; + fb.composite_construct(uvec4, &[value, zero, zero, zero]) +} + /// The blend an extended-range attachment's write computes in the shader /// (`StorageView::blend`) of an output of four lanes of `output` (`None` for another output) /// of a function of math `math`, as Metal's model holds it: `None` for no blend; `Err` with the gap diff --git a/crates/metal2vulkan/src/lower/fragment/fetch/tests.rs b/crates/metal2vulkan/src/lower/fragment/fetch/tests.rs index 90c479629..2ac3cbb3a 100644 --- a/crates/metal2vulkan/src/lower/fragment/fetch/tests.rs +++ b/crates/metal2vulkan/src/lower/fragment/fetch/tests.rs @@ -956,3 +956,91 @@ fn an_extended_range_blend_follows_the_ordered_storage_form() { assert!(extended_range_blend(PixelFormat::BGRA10XR, &p) .is_err_and(|u| u.feature == Feature::FramebufferFetch)); } + +/// A packed 16-bit attachment the device samples but does not render (`A1BGR5Unorm`, +/// `ABGR4Unorm` on the RTX 5080 profiles) takes the storage form through a view of its words: the +/// view and declaration `R16_UINT`, `uint` texels the function reads as floats, and the word's +/// layout (`StorageView::word`), whose kept fields a partial write mask merges by the draw's word; +/// a replacing blend too. Another blend is the shader's (`StorageView::blend`), but one of the +/// second source, which is not built. A device that renders the format takes it directly, without +/// the word. +#[test] +fn a_word_attachment_takes_the_view_of_its_words() { + use crate::metal::format::WordAttachment; + let ni = Err(Unsupported::not_implemented(Feature::FramebufferFetch)); + for stem in ["nvidia-rtx5080-laptop", "nvidia-rtx50-linux"] { + let p = profile(stem, &[]); + assert!(interlock_orders(&p), "{stem}"); + for pf in [PixelFormat::A1BGR5Unorm, PixelFormat::ABGR4Unorm] { + let what = format!("{stem} {pf:?}"); + let word = WordAttachment::layout(pf); + assert_eq!(WordAttachment::of(pf, &p), word, "{what}"); + for mask in [ + ColorWriteMask::RED | ColorWriteMask::GREEN, + ColorWriteMask::ALPHA, + ColorWriteMask::ALL, + ] { + let view = form(&state(pf, |c| c.write_mask = mask), false, WRITES, &p) + .unwrap_or_else(|e| panic!("{what} {mask:?}: {e:?}")); + assert_eq!( + (view.format, view.declared, view.numeric, view.word), + ( + vk::Format::R16_UINT, + expected_declaration( + vk::Format::R16_UINT, + WRITES, + crate::spv::ImageFormat::R16ui, + &p + ), + SampledType::Uint, + word + ), + "{what} {mask:?}" + ); + assert_eq!(view.read_class(), SampledType::Float, "{what}"); + assert_eq!(view.uint_view.or(view.rgba_view), None, "{what}"); + let partial = mask != ColorWriteMask::ALL; + assert_eq!( + (view.merges(), view.kept_at_draw), + (partial, partial), + "{what}" + ); + } + let replacing = state(pf, |c| { + c.blending_enabled = true; + c.write_mask = ColorWriteMask::RED; + }); + assert!(form(&replacing, false, WRITES, &p).is_ok(), "{what}"); + let blended = state(pf, |c| { + c.blending_enabled = true; + c.destination_rgb_blend_factor = crate::metal::BlendFactor::One; + }); + let view = form(&blended, false, WRITES, &p) + .unwrap_or_else(|e| panic!("{what} blended: {e:?}")); + assert_eq!( + (view.word, view.format), + (word, vk::Format::R16_UINT), + "{what}" + ); + assert!(view.blend.is_some(), "{what}"); + let second = state(pf, |c| { + c.blending_enabled = true; + c.destination_rgb_blend_factor = crate::metal::BlendFactor::Source1Color; + }); + assert_eq!(form(&second, false, WRITES, &p), ni, "{what}"); + } + } + let radv = profile("amd-rdna3-radv", &[]); + let view = form( + &state(PixelFormat::ABGR4Unorm, |c| { + c.write_mask = ColorWriteMask::RED + }), + false, + WRITES, + &radv, + ); + if let Ok(view) = view { + assert_eq!(view.word, None); + assert_eq!(view.format, vk::Format::R4G4B4A4_UNORM_PACK16); + } +} diff --git a/crates/metal2vulkan/src/lower/fragment/input_blend.rs b/crates/metal2vulkan/src/lower/fragment/input_blend.rs index c883ff7c4..40180a245 100644 --- a/crates/metal2vulkan/src/lower/fragment/input_blend.rs +++ b/crates/metal2vulkan/src/lower/fragment/input_blend.rs @@ -72,8 +72,7 @@ const WRITE_WORDS: u64 = 120; /// where this module computes an extended-range blend (on one that orders it through the pixel /// interlock, the storage form does, `fetch::interlock_orders`). fn through_inputs(cx: &SelectCx<'_>) -> bool { - let f = cx.profile.fields().fragment; - f.rasterization_order_color_access && !fetch::interlock_orders(cx.profile) + fetch::inputs_order(cx.profile) } /// Plan the extended-range attachments the function writes through a first output where the diff --git a/crates/metal2vulkan/src/lower/fragment/mod.rs b/crates/metal2vulkan/src/lower/fragment/mod.rs index e7de1b4ec..67bdbfb82 100644 --- a/crates/metal2vulkan/src/lower/fragment/mod.rs +++ b/crates/metal2vulkan/src/lower/fragment/mod.rs @@ -63,6 +63,7 @@ mod input_blend; mod rog; mod snapshot; mod stencil; +mod word_input; use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet}; @@ -101,8 +102,8 @@ pub(crate) use depth_test::{ pub use discard::DiscardForm; pub(crate) use fetch::{ blends_half_in_shader, compiled_write_mask, extended_range_blend, half_blend_attachment, - half_float_format, half_output, interlock_orders, kept_channels, storage_form, ColorUse, - StorageSamples, + half_float_format, half_output, inputs_order, interlock_orders, kept_channels, storage_form, + ColorUse, StorageSamples, }; pub use fetch::{ select_output as select_storage_output, select_second_output as select_storage_second_output, @@ -116,6 +117,7 @@ pub(crate) use snapshot::{decode as snapshot_decode, encode as snapshot_encode}; pub(crate) use snapshot::{prepare as snapshot_prepare, read as snapshot_read}; pub(crate) use stencil::{face_word, SHADOW_FORMAT}; pub use stencil::{select_output as select_stencil_output, ShadowStencil}; +pub(crate) use word_input::merge as word_input_merge; fn not_lowered() -> Error { Unsupported::not_implemented(Feature::Lowering(LowerFamily::Fragment)).into() @@ -193,6 +195,10 @@ pub struct FragmentPlan { /// The extended-range attachments whose blend the function computes over their input /// attachments, on a device that orders fetch through them (`input_blend`), by index. pub input_blends: BTreeMap, + /// The word attachments whose word the function merges into the texel's over their input + /// attachments, on a device that orders fetch through them (`word_input`), by index: the bits + /// of the fields each write keeps from the texel. + pub word_merges: BTreeMap, /// The stage interface's `FragCoord` object, which gives the pixel of the storage form and /// of the shader-side stencil. pub fetch_coord: Option, @@ -398,6 +404,7 @@ pub fn finish(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<(), Error> { )) .saturating_add(stencil::words(cx, rets)) .saturating_add(input_blend::words(cx, returns(cx))) + .saturating_add(word_input::words(cx, returns(cx))) .saturating_add(depth_test::words(cx, rets)) .saturating_add(killing_rets.saturating_mul(RETURN_KILL_WORDS)) .saturating_add((quad_exits.len() as u64).saturating_mul(QUAD_EXIT_WORDS)) @@ -482,7 +489,7 @@ pub fn declare( d.attachments = color::declare( mb, &fp.colors, - (&fp.fetch, &fp.input_blends), + (&fp.fetch, &fp.input_blends, &fp.word_merges), fp.fetch_sample.is_some(), )?; for (&color, sc) in &fp.fetch { @@ -582,6 +589,7 @@ pub fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error pub fn plan_entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { fetch::plan(cx)?; input_blend::plan(cx)?; + word_input::plan(cx)?; coverage::plan(cx) } diff --git a/crates/metal2vulkan/src/lower/fragment/word_input.rs b/crates/metal2vulkan/src/lower/fragment/word_input.rs new file mode 100644 index 000000000..a47106343 --- /dev/null +++ b/crates/metal2vulkan/src/lower/fragment/word_input.rs @@ -0,0 +1,143 @@ +//! Metal's write of some of a word attachment's channels on a device that orders framebuffer fetch +//! through rasterization-order input attachments. +//! +//! An attachment the device renders through a view of its word (`metal::format::WordAttachment`) +//! has one component, which the device writes whole, so the device's write mask cannot keep a +//! field of it. On a device that orders fetch through the pixel interlock the storage form merges +//! the word (`fetch`); on one that orders it through input attachments with rasterization-order +//! access (lavapipe) the function reads the texel's word through the attachment's input attachment +//! at its first output's write (at the invocation's sample in a multisampled pipeline) and stores +//! Metal's word of the output (`stage_io::word_color::encode`) with the fields of the channels the +//! descriptor's write mask leaves out taken from the word read, as Metal's tile keeps them. Link +//! writes the whole word (`RuntimeFact::WordInputMerge`). Rasterization-order attachment access +//! orders each fragment's read after every earlier fragment's write of the pixel, so each merge +//! keeps what the fragments before it stored. +//! +//! The function compiles under the descriptor's mask (`LoweringInputs::framebuffer_fetch`), which +//! is the descriptor's own for the formats this merges, the 8-bit sRGB words +//! (`color_writes::merged_word`); a stage linked into a pipeline of another mask there was +//! compiled for another pipeline, `NeedsInput(FramebufferFetch)` (`link::fetch::word_merges`). + +use std::collections::BTreeMap; + +use crate::air::abi::{AbiInt, OutputRole}; +use crate::error::{Attachment, Error}; +use crate::lower::arith::{ops, Form, Held}; +use crate::lower::emit::EmitCx; +use crate::lower::select::SelectCx; +use crate::metal::format::WordAttachment; +use crate::metal::ColorWriteMask; +use crate::pipeline::facts::RuntimeFact; +use crate::pipeline::sym::Stage; +use crate::spirv::builder::FunctionBuilder; +use crate::spirv::error::BResult; +use crate::spirv::ids::Value as SValue; +use crate::spirv::ir::BinOp; + +use super::fetch; + +/// An upper estimate of the words one merge adds at a return: the input attachment's read, the +/// word's extraction, and the masks and merge. +const MERGE_WORDS: u64 = 48; + +/// The bits of `word`'s fields of the channels `kept`. +fn kept_bits(word: WordAttachment, kept: ColorWriteMask) -> u32 { + [ + ColorWriteMask::RED, + ColorWriteMask::GREEN, + ColorWriteMask::BLUE, + ColorWriteMask::ALPHA, + ] + .into_iter() + .zip(word.fields()) + .filter_map(|(channel, field)| field.filter(|_| kept.contains(channel))) + .fold(0, |bits, f| bits | ((1u32 << f.bits) - 1) << f.shift) +} + +/// Plan the word attachments the function writes through a first output under a write mask of +/// some of their channels, on a device that fetches through input attachments, before the stage +/// interface: each one the pipeline's state names (`FramebufferFetchInputs`) reads its input +/// attachment and keeps the fields of the channels the mask leaves out, and states +/// `RuntimeFact::WordInputMerge` (see the module docs). +pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> { + if cx.stage != Stage::Fragment || !fetch::inputs_order(cx.profile) { + return Ok(()); + } + let Some(inputs) = cx.inputs.framebuffer_fetch.clone() else { + return Ok(()); + }; + let written: Vec = cx + .entry + .ep + .outputs + .iter() + .filter_map(|o| match o.role { + OutputRole::RenderTarget { + attachment: AbiInt::Const(color), + index: 0, + .. + } => Some(color), + _ => None, + }) + .collect(); + let mut planned = BTreeMap::new(); + for color in written { + let Some(word) = cx.inputs.word_colors.get(&color).copied() else { + continue; + }; + let Some(a) = inputs.attachments.get(&color).copied().flatten() else { + continue; + }; + // A mask of every channel or none writes the word whole (`color_writes::word_color`). + let kept = fetch::kept_channels(a.pixel_format, a.write_mask, true); + if kept.is_empty() || kept == ColorWriteMask::ALL { + continue; + } + let flags = crate::metal::state::color_write_mask(kept) + .map_err(|e| e.at_attachment(Attachment::Color(color)))?; + cx.descriptors.input_attachments = cx.descriptors.input_attachments.saturating_add(1); + cx.facts.insert(RuntimeFact::FramebufferFetch { color }); + cx.facts + .insert(RuntimeFact::WordInputMerge { color, kept: flags }); + planned.insert(color, kept_bits(word, kept)); + } + let merges = !planned.is_empty(); + cx.families.fragment.word_merges = planned; + match merges { + true => fetch::plan_sample(cx), + false => Ok(()), + } +} + +/// The word a write stores to attachment `color`, whose fields `kept` (bits) it takes from the +/// texel's word read through the attachment's input attachment, and the rest from `word`, Metal's +/// word of the output (see the module docs). +pub(crate) fn merge( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + color: u32, + kept: u32, + word: SValue, +) -> BResult { + let u = Form { + held: Held::Int { + bits: 32, + container: 32, + }, + lanes: 1, + }; + let texel = super::color::input_texel(cx, fb, color)?; + let read = fb.composite_extract(texel, &[0])?; + let keep = ops::splat(fb, u, u64::from(kept))?; + let take = ops::splat(fb, u, u64::from(!kept))?; + let read = fb.binary(BinOp::BitwiseAnd, read, keep)?; + let word = fb.binary(BinOp::BitwiseAnd, word, take)?; + fb.binary(BinOp::BitwiseOr, read, word) +} + +/// The words the planned merges add at `rets` returns: one input attachment each, and at each +/// return the read and the merge. +pub(super) fn words(cx: &SelectCx<'_>, rets: u64) -> u64 { + let merges = cx.families.fragment.word_merges.len() as u64; + merges.saturating_mul(32u64.saturating_add(MERGE_WORDS.saturating_mul(rets.max(1)))) +} diff --git a/crates/metal2vulkan/src/lower/stage_io/mod.rs b/crates/metal2vulkan/src/lower/stage_io/mod.rs index 37e02102d..a2990a948 100644 --- a/crates/metal2vulkan/src/lower/stage_io/mod.rs +++ b/crates/metal2vulkan/src/lower/stage_io/mod.rs @@ -144,6 +144,7 @@ pub(crate) mod extended_color; pub mod fetch; mod plan; mod stage_in; +pub(crate) mod word_color; use std::collections::{BTreeMap, BTreeSet}; @@ -384,6 +385,9 @@ pub struct StageIoPlan { /// as the raw texel Metal stores (`extended_color::encode`), with the form each is held in /// (and, a bfloat one's rounding). pub extended: BTreeMap, + /// The word attachments whose `float` or `half` output each return stores as the word Metal + /// stores (`word_color::encode`), with each word's layout. + pub words_written: BTreeMap, /// A vertex function's viewport compensation (`LoweringInputs::viewport_compensation`). pub compensation: Option, /// A fragment function's depth output, which each return gives Metal's answer @@ -1966,9 +1970,23 @@ fn output_part( Some(color) if cx.plan.families.fragment.input_blends.contains_key(&color) => { input_blended(cx, fb, (x, returned), color, (o.link.form, part))? } - Some(color) => match cx.plan.families.stage_io.extended.get(&color).copied() { - Some(e) => extended_color::encode(cx, fb, e, o.link.form, part)?, - None => color_write::round(cx, fb, color, o.link.form, part)?, + Some(color) => match ( + cx.plan.families.stage_io.words_written.get(&color).copied(), + cx.plan.families.stage_io.extended.get(&color).copied(), + ) { + (Some(w), _) => { + let srgb = word_color::srgb_table(cx); + let word = word_color::encode(fb, w, (o.link.form, part), srgb)?; + // A write of some of the word's channels over the attachment's input attachment. + match cx.plan.families.fragment.word_merges.get(&color).copied() { + Some(kept) => { + crate::lower::fragment::word_input_merge(cx, fb, color, kept, word)? + } + None => word, + } + } + (None, Some(e)) => extended_color::encode(cx, fb, e, o.link.form, part)?, + (None, None) => color_write::round(cx, fb, color, o.link.form, part)?, }, None => part, }; diff --git a/crates/metal2vulkan/src/lower/stage_io/plan.rs b/crates/metal2vulkan/src/lower/stage_io/plan.rs index 98b8d44ca..070fb212c 100644 --- a/crates/metal2vulkan/src/lower/stage_io/plan.rs +++ b/crates/metal2vulkan/src/lower/stage_io/plan.rs @@ -2157,6 +2157,11 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> { if cx.stage == Stage::Fragment && cx.inputs.extended_range_colors.contains_key(&color) { continue; } + // A word attachment's write is unblended: a second output there is stored nowhere, + // as Metal's unblended write reads none. + if cx.stage == Stage::Fragment && cx.inputs.word_colors.contains_key(&color) { + continue; + } } // On a device without `multiViewport` a draw has one viewport, so the index selects // viewport 0 whatever it is: no `ViewportIndex` is stored, and the raw varying holds the @@ -2838,9 +2843,12 @@ fn output(cx: &mut SelectCx<'_>, o: &OutputBinding, ty: AirTypeId) -> Result IoType { bits: 16, ..io }, false => io, }; - // An extended-range attachment's raw texel, through a variable of its raw components; - // the interface keeps the Metal output's type. - let declared = super::extended_color::plan(cx, attachment, index, f)?.unwrap_or(io); + // An extended-range attachment's raw texel, through a variable of its raw components, + // and a word attachment's word; the interface keeps the Metal output's type. + let declared = match super::word_color::plan(cx, attachment, index, f)? { + Some(word) => word, + None => super::extended_color::plan(cx, attachment, index, f)?.unwrap_or(io), + }; let key = VaryingKey::color(attachment, index); let deco = IoDecor { index: (index == 1).then_some(1), @@ -3135,6 +3143,11 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { .saturating_mul(sp.halves.len() as u64), ) .saturating_add(super::extended_color::WORDS.saturating_mul(sp.extended.len() as u64)) + .saturating_add( + (sp.words_written.values()) + .map(|&w| super::word_color::encode_words(w)) + .fold(0u64, u64::saturating_add), + ) // A returned depth's code. .saturating_add(match sp.depth_clamp.is_some_and(|d| d.codes) { true => super::depth16::CODE_WORDS, diff --git a/crates/metal2vulkan/src/lower/stage_io/word_color.rs b/crates/metal2vulkan/src/lower/stage_io/word_color.rs new file mode 100644 index 000000000..2d7ff41ac --- /dev/null +++ b/crates/metal2vulkan/src/lower/stage_io/word_color.rs @@ -0,0 +1,285 @@ +//! A fragment function's color outputs to attachments the device renders through a word view +//! (`LoweringInputs::word_colors`, `metal::format::WordAttachment`). +//! +//! Such an attachment is a view of the texture's bits as the unsigned integer format of its word, +//! so the function writes each `float` or `half` output to one as the word Metal stores for it, +//! through an output variable of one unsigned 32-bit component ([`plan`], [`encode`]): each +//! channel's value rounded to `half` to nearest even, clamped to `[0, 1]` (a NaN 0), times the +//! channel's maximum code, rounded to nearest even, and the codes packed into their fields (the +//! measurement is `metal::format::WordAttachment`'s). The interface variable keeps the Metal +//! output's type (`StageIo::outputs`), which link checks against the attachment's format as for +//! any other color. +//! +//! The product of a `half` in `[0, 1]` and a maximum code of at most 6 bits is exact in `f32` +//! (eleven significant bits times six), so `RoundEven` of it is Metal's code: its only ties are +//! the products at one half, which Metal stores even. +//! +//! An `RGB9E5Float` word takes a `float` output's word: the mantissas truncated under the largest +//! channel's exponent (`texture::rgb9e5_word`, the rule of its kernel writes). A `half` output to +//! one is not built (Metal rounds the `float` the `half` came from, `WordAttachment`'s docs). +//! +//! An integer output to such an attachment is Metal's pipeline error: it is not encoded, and link +//! refuses it (`ColorAttachment`). +//! +//! The interlocked storage form writes such an attachment through the same encode where it blends +//! or keeps some channels (`lower::fragment::fetch`), and a blend there reads the word read first +//! as Metal's blend reads it ([`decode`]). + +use crate::air::intrinsics::{PackDir, PackFormat}; +use crate::error::{Error, Feature, Unsupported}; +use crate::lower::arith::color_write::half_rounded; +use crate::lower::arith::nan::NanTest; +use crate::lower::arith::ops::{fsplat, splat, ty}; +use crate::lower::arith::{FloatFmt, Form, Held}; +use crate::lower::select::SelectCx; +use crate::metal::format::WordAttachment; +use crate::pipeline::stage_io::{IoNumeric, IoType}; +use crate::pipeline::sym::Stage; +use crate::spirv::builder::FunctionBuilder; +use crate::spirv::error::BResult; +use crate::spirv::ids::{GlobalId, Value}; +use crate::spirv::ir::{BinOp, ConvOp, GlslOp, UnOp}; + +/// An upper estimate of the SPIR-V words of one output's [`encode`]: per channel the rounding to +/// `half`, the clamp, the product's rounding, the conversion, shift and merge. +pub(crate) const WORDS: u64 = 4 * (40 * 6 + 12 * 6); + +/// An upper estimate of the SPIR-V words of one output's [`encode`] into `word`: [`WORDS`], and +/// for an 8-bit sRGB word `math::pack`'s encode, the products and a search of Metal's table per +/// color channel. +pub(crate) fn encode_words(word: WordAttachment) -> u64 { + match word { + WordAttachment::Packed16 { .. } => WORDS, + WordAttachment::Srgb8 { .. } => { + WORDS + 4 * u64::from(crate::lower::arith::srgb::SEARCH_WORDS) + 400 + } + WordAttachment::Rgb9e5 => crate::lower::texture::RGB9E5_WORDS + 6 * 8, + } +} + +/// Plan output `f` (dual-source `index`) of a fragment function to color attachment `color`: +/// where `LoweringInputs::word_colors` lists the attachment and the output is `float` or `half` of +/// dual-source index 0, record the attachment on the interface (`StageIo::word_colors`) and the +/// encode each return stores (`StageIoPlan::words_written`), and give the word's type the output +/// variable is declared with (`StageIo::declared_type`). `None` where the output is stored as it +/// is: another attachment's, or an integer output (link refuses it). A `half` output to an +/// `RGB9E5Float` word is `NotImplemented(Format)`. +pub(super) fn plan( + cx: &mut SelectCx<'_>, + color: u32, + index: u32, + f: Form, +) -> Result, Error> { + if cx.stage != Stage::Fragment || index != 0 { + return Ok(None); + } + let Some(word) = cx.inputs.word_colors.get(&color).copied() else { + return Ok(None); + }; + if !matches!(f.float_fmt(), Some(FloatFmt::F32 | FloatFmt::Half)) { + return Ok(None); + } + if word == WordAttachment::Rgb9e5 && f.float_fmt() != Some(FloatFmt::F32) { + return Err(Unsupported::not_implemented(Feature::Format).into()); + } + cx.families + .stage_io + .interface + .word_colors + .insert(color, word); + cx.families.stage_io.words_written.insert(color, word); + // An 8-bit sRGB word encodes through Metal's table. + if let WordAttachment::Srgb8 { .. } = word { + cx.families.arith.srgb.get_or_insert(PackDir::Pack); + } + Ok(Some(IoType { + numeric: IoNumeric::Uint, + components: 1, + source_bits: 32, + bits: 32, + })) +} + +/// The module's sRGB table and NaN test, which an 8-bit sRGB word's [`encode`] reads, where the +/// plan declares the table. +pub(crate) fn srgb_table(cx: &crate::lower::emit::EmitCx<'_>) -> Option<(GlobalId, NanTest)> { + let test = NanTest::for_modes(&cx.plan.families.arith.modes); + cx.decl.families.arith.srgb.map(|table| (table, test)) +} + +/// The word Metal stores for output `x` (form `f`, `float` or `half` lanes held in 32-bit +/// containers) to a word attachment `word` (the module docs), as a `u32`. A channel the output +/// lacks is 0, a missing alpha 1. An 8-bit sRGB word encodes through Metal's table `srgb` (the +/// module's sRGB table, `ArithPlan::srgb`, and its NaN test), as `math::pack`'s +/// `unorm4x8_srgb` encodes a color channel; `None` there is malformed. An `RGB9E5Float` word +/// takes a `float` output's red, green and blue (`texture::rgb9e5_word`). +pub(crate) fn encode( + fb: &mut FunctionBuilder<'_>, + word: WordAttachment, + (f, x): (Form, Value), + srgb: Option<(GlobalId, NanTest)>, +) -> BResult { + let s = Form { + held: Held::Float(FloatFmt::F32), + lanes: 1, + }; + if let WordAttachment::Rgb9e5 = word { + let mut lanes = Vec::with_capacity(3); + for lane in 0..3u8 { + lanes.push(match lane < f.lanes { + true if f.lanes == 1 => x, + true => fb.composite_extract(x, &[u32::from(lane)])?, + false => fsplat(fb, s, 0.0)?, + }); + } + let f3 = Form { + held: Held::Float(FloatFmt::F32), + lanes: 3, + }; + let t = ty(fb, f3)?; + let x3 = fb.composite_construct(t, &lanes)?; + return crate::lower::texture::rgb9e5_word(fb, x3); + } + if let WordAttachment::Srgb8 { .. } = word { + let Some((table, test)) = srgb else { + return Err(crate::spirv::error::BuildError::Operand { + op: crate::spv::Op::ExtInst, + rule: crate::spirv::error::OperandRule::Arity, + }); + }; + // The output's four lanes (a lane it lacks 0), packed by Metal's sRGB encode: red's byte + // first, then green's; the word keeps the format's. + let mut lanes = Vec::with_capacity(4); + for lane in 0..4u8 { + lanes.push(match lane < f.lanes { + true if f.lanes == 1 => x, + true => fb.composite_extract(x, &[u32::from(lane)])?, + false => fsplat(fb, s, 0.0)?, + }); + } + let f4 = Form { + held: Held::Float(FloatFmt::F32), + lanes: 4, + }; + let t = ty(fb, f4)?; + let x4 = fb.composite_construct(t, &lanes)?; + let packed = crate::lower::arith::math::pack( + fb, + PackFormat::Unorm4x8Srgb, + f4, + x4, + Some(table), + test, + )?; + let u = Form { + held: Held::Int { + bits: 32, + container: 32, + }, + lanes: 1, + }; + let mask = match word.word_format() { + crate::vk::Format::R8_UINT => 0xff, + _ => 0xffff, + }; + let mask = splat(fb, u, mask)?; + return fb.binary(BinOp::BitwiseAnd, packed, mask); + } + let u = Form { + held: Held::Int { + bits: 32, + container: 32, + }, + lanes: 1, + }; + let ut = ty(fb, u)?; + let mut out = splat(fb, u, 0)?; + for (lane, field) in word.fields().iter().enumerate() { + let Some(field) = field else { + continue; + }; + let v = match u8::try_from(lane).is_ok_and(|l| l < f.lanes) { + true if f.lanes == 1 => x, + true => fb.composite_extract(x, &[lane as u32])?, + false => fsplat(fb, s, if lane == 3 { 1.0 } else { 0.0 })?, + }; + // The `half` nearest the value (a `half` output is one already), a NaN 0, in `[0, 1]`. + let h = half_rounded(fb, s, v)?; + let is_nan = fb.unary(UnOp::IsNan, h)?; + let zero = fsplat(fb, s, 0.0)?; + let h = fb.select(is_nan, zero, h)?; + let one = fsplat(fb, s, 1.0)?; + let h = fb.glsl(GlslOp::NClamp, &[h, zero, one])?; + let m = fsplat(fb, s, f64::from((1u32 << field.bits) - 1))?; + let p = fb.binary_no_contraction(BinOp::FMul, h, m)?; + let c = fb.glsl(GlslOp::RoundEven, &[p])?; + let c = fb.convert(ConvOp::ConvertFToU, c, ut)?; + let c = match field.shift { + 0 => c, + shift => { + let shift = splat(fb, u, u64::from(shift))?; + fb.binary(BinOp::ShiftLeftLogical, c, shift)? + } + }; + out = fb.binary(BinOp::BitwiseOr, out, c)?; + } + Ok(out) +} + +/// An upper estimate of the SPIR-V words of one [`decode`]: per channel the shift, mask, +/// conversion, product and rounding to `half`, and the vector's construction. +pub(crate) const DECODE_WORDS: u64 = 4 * (12 * 6 + 40 * 6) + 12; + +/// The four channels Metal's blend reads from word `x` (a `u32`) of packed 16-bit word attachment +/// `word` (`WordAttachment::Packed16`), as a +/// `vec4` of `f32`, red first: each channel's code over its maximum code rounded to `half`, nearest +/// even, a channel the format lacks 0, alpha 1 (measured: the packed 16-bit blend sweep, +/// `extended_range::Blend::packed16`). The code times the `f32` nearest the maximum's reciprocal +/// lies within two `f32` steps of the quotient, whose `half` it rounds to: the quotient of a code +/// by `2^k - 1` repeats `k` bits without end (or is 0 or 1), which keeps it far from a `half` +/// midpoint, more than `2^-(k+1)` of a `half` step for `k` up to 6. +pub(crate) fn decode( + fb: &mut FunctionBuilder<'_>, + word: WordAttachment, + x: Value, +) -> BResult { + let s = Form { + held: Held::Float(FloatFmt::F32), + lanes: 1, + }; + let u = Form { + held: Held::Int { + bits: 32, + container: 32, + }, + lanes: 1, + }; + let st = ty(fb, s)?; + let mut lanes = Vec::with_capacity(4); + for (lane, field) in word.fields().iter().enumerate() { + let Some(field) = field else { + lanes.push(fsplat(fb, s, if lane == 3 { 1.0 } else { 0.0 })?); + continue; + }; + let max = (1u32 << field.bits) - 1; + let code = match field.shift { + 0 => x, + shift => { + let shift = splat(fb, u, u64::from(shift))?; + fb.binary(BinOp::ShiftRightLogical, x, shift)? + } + }; + let mask = splat(fb, u, u64::from(max))?; + let code = fb.binary(BinOp::BitwiseAnd, code, mask)?; + let c = fb.convert(ConvOp::ConvertUToF, code, st)?; + let r = fsplat(fb, s, f64::from(1.0f32 / max as f32))?; + let v = fb.binary_no_contraction(BinOp::FMul, c, r)?; + lanes.push(half_rounded(fb, s, v)?); + } + let v4 = Form { + held: Held::Float(FloatFmt::F32), + lanes: 4, + }; + let t = ty(fb, v4)?; + fb.composite_construct(t, &lanes) +} diff --git a/crates/metal2vulkan/src/lower/texture/emit.rs b/crates/metal2vulkan/src/lower/texture/emit.rs index bbd3549b2..dec5af92b 100644 --- a/crates/metal2vulkan/src/lower/texture/emit.rs +++ b/crates/metal2vulkan/src/lower/texture/emit.rs @@ -1892,6 +1892,8 @@ fn shared_exponent_texel( /// The `uvec4` a `SharedExponentBits` slot stores for held texel `x` (`f32` lanes of `form`, a /// `half` texel's widened exactly): the `RGB9E5Float` word Metal stores in its first lane +/// (`StorageImageClass::SharedExponentBits`, [`rgb9e5_word`]); alpha is not stored. An integer +/// texel is not one the format takes. fn shared_exponent_word( fb: &mut FunctionBuilder<'_>, form: TexelForm, @@ -1902,6 +1904,24 @@ fn shared_exponent_word( crate::spirv::error::TypeRule::FunctionSignature, )); } + let u = u32_ty(fb)?; + let word = rgb9e5_word(fb, x)?; + let zero = fb.u32_const(0)?; + let zero = fb.module().const_value(zero)?; + let v4 = vec(fb, u, 4)?; + fb.composite_construct(v4, &[word, zero, zero, zero]) +} + +/// An upper estimate of the SPIR-V words of one [`rgb9e5_word`]. +pub(crate) const RGB9E5_WORDS: u64 = 3 * 8 * 7 + 3 * 7 * 7 + 16 * 7; + +/// The `RGB9E5Float` word, a `u32`, Metal stores for the red, green and blue `f32` lanes of `x` (a +/// vector of at least three; a kernel's write, a `float` output's store into a word attachment, +/// `metal::format::WordAttachment::Rgb9e5`): each clamped to `[0, 65408]` on its bits (a NaN, a +/// negative value and `-0` 0; an infinity 65408), the exponent `e = max(⌊log2 m⌋, -16) + 16` from +/// the largest clamped channel `m`'s exponent field, and each mantissa the clamped channel times +/// `2^(24 - e)` (exact: a power of two, the product below 512) converted toward zero. +pub(crate) fn rgb9e5_word(fb: &mut FunctionBuilder<'_>, x: SValue) -> BResult { let u = u32_ty(fb)?; let f = f32_ty(fb)?; let constant = |fb: &mut FunctionBuilder<'_>, v: u32| -> BResult { @@ -1952,6 +1972,7 @@ fn shared_exponent_word( let m = fb.binary(BinOp::ShiftLeftLogical, m, shift)?; word = fb.binary(BinOp::BitwiseOr, word, m)?; } + Ok(word) } /// The `f32` NaN a written `float`'s NaN becomes under `HalfTowardZero` and `HalfQuietNan` diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index 0083eb9d3..3ed80361e 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -131,10 +131,11 @@ pub use atomic::TexAtomic; pub(crate) use emit::{ constant_lanes, constant_lanes_by, dispatch, extended_table, float_class, half_by_class, half_class, heap_element, heap_float_class, heap_half_class, heap_raw_form, heap_raw_image, - live_or_zero, metal_texel_nans, reinterpret, resident_access, slot_image, sparse_spec, - srgb_raw_gather, srgb_raw_tap, srgb_raw_texel, swizzled_float, swizzled_gather, swizzled_held, - texel_format_const, tile_map, tiled_word, with_word, HalfClass, NullLeaf, TileLevel, - SRGB_RAW_WORDS, SRGB_TAP_WORDS, SRGB_TEXEL, + live_or_zero, metal_texel_nans, reinterpret, resident_access, rgb9e5_word, slot_image, + sparse_spec, srgb_filtered_texel, srgb_raw_gather, srgb_raw_tap, srgb_raw_texel, + swizzled_float, swizzled_gather, swizzled_held, texel_format_const, tile_map, tiled_word, + with_word, HalfClass, NullLeaf, TileLevel, RGB9E5_WORDS, SRGB_FILTERED_WORDS, SRGB_RAW_WORDS, + SRGB_TAP_WORDS, SRGB_TEXEL, }; pub use emit::{emit, held_texel, to_image}; pub(crate) use slot::depth_comparison; diff --git a/crates/metal2vulkan/src/metal/format/mod.rs b/crates/metal2vulkan/src/metal/format/mod.rs index 77f053a02..4bc8ead89 100644 --- a/crates/metal2vulkan/src/metal/format/mod.rs +++ b/crates/metal2vulkan/src/metal/format/mod.rs @@ -36,6 +36,8 @@ use crate::vk; pub(crate) mod extended_srgb; pub(crate) mod padded_srgb; +mod word; +pub use word::{WordAttachment, WordField}; /// How a Metal pixel format is represented on a device, for a set of usages. #[non_exhaustive] diff --git a/crates/metal2vulkan/src/metal/format/word.rs b/crates/metal2vulkan/src/metal/format/word.rs new file mode 100644 index 000000000..0a4705854 --- /dev/null +++ b/crates/metal2vulkan/src/metal/format/word.rs @@ -0,0 +1,338 @@ +//! Color attachments a device renders through an unsigned integer view of the texture's words. +//! +//! A device may hold a format's image, and sample it, but not render into it: the RTX 5080 has +//! `R5G5B5A1_UNORM_PACK16` and `R4G4B4A4_UNORM_PACK16` images without `COLOR_ATTACHMENT`, and +//! `R8_SRGB` and `E5B9G9R9_UFLOAT_PACK32` without it (`R8G8_SRGB` it holds no image of: the runtime +//! holds such a texture in its UNORM twin). Such a texture's image is made mutable, with extended +//! usage, and its attachment is a view of the same bits as the unsigned integer format of its word +//! ([`WordAttachment::word_format`]), which every Vulkan device renders. The fragment function +//! writes the word Metal stores for its output (`LoweringInputs::word_colors`), and a clear writes +//! the word of Metal's clear (the runtime's clear values): both are exact, and the texture's other +//! views read the same bits. +//! +//! Metal's store into a packed 16-bit format (measured on an Apple M3 Max under macOS 27.0.1: +//! every texel of 65,536 `float` and `half` outputs and 4,096 clear colors into each of +//! `B5G6R5Unorm`, `A1BGR5Unorm`, `ABGR4Unorm` and `BGR5A1Unorm`): each channel's value rounded to +//! `half` to nearest even (a NaN 0), clamped to `[0, 1]`, times the channel's maximum code, rounded +//! to nearest even; the only ties are at one half, which store the even code (an `A1BGR5Unorm` +//! alpha of 0.5 is 0). That is `ChannelWrite::HalfUnorm`'s rule. +//! +//! Metal's store into an 8-bit sRGB format (`R8Unorm_sRGB`, `RG8Unorm_sRGB`; the lane's rule, +//! `runtime_lane::color_writes`, and its in-guest probe's clears and draws on the M3 Max): each +//! channel's value clamped to `[0, 1]` (a NaN 0), times 4095 exactly, rounded to nearest, encoded +//! by Metal's twelve-bit table, as `pack_float_to_srgb_unorm4x8` encodes a color channel. A write +//! of some of its channels merges the word into the texel's: in the pixel interlock +//! (`color_writes::stored_word`), or over the attachment's input attachment on a device that orders +//! fetch through rasterization-order input attachments (`color_writes::merged_word`). A blend of +//! such an attachment, other than one and zero, is not built. +//! +//! Metal's store of a `float` output into `RGB9E5Float` (measured on the M3 Max: 65,536 draws and +//! clears, and the format scout's draws): each of red, green and blue clamped to `[0, 65408]` (a +//! NaN 0), the shared exponent from the largest, and every mantissa truncated (the rule of its +//! kernel writes). Its store of a `half` output rounds the mantissas half up, raising the exponent +//! where the largest reaches 512, from the `float` the `half` was converted from (Metal's compiler +//! folds the conversion into the store): that store is not built. +//! +//! A blend of factors one and zero, added, stores the same (Metal's draws through it matched too). +//! A write mask of some of the format's channels keeps the other fields: where the device orders +//! fetch through the pixel interlock, the fragment function stores the word in the interlocked +//! storage form, merging the kept fields of the word it reads first (`lower::fragment::fetch`), +//! which hold their codes as Metal's tile holds them. The device blends no such view otherwise, +//! resolves none, and reads none as the format's input attachment: a pipeline that blends a word +//! attachment, covers by its alpha, or writes some of its channels on a device without that +//! interlock is refused as the device lacking the format's attachment, as without the view; a +//! color input of one, and a pass's resolve of one, are `NotImplemented(Format)`. + +use crate::device::requirements::FormatUsage; +use crate::device::DeviceProfile; +use crate::metal::PixelFormat; +use crate::vk; + +/// A color format whose attachment a device renders through an unsigned integer view of its words +/// (the module docs). +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum WordAttachment { + /// A packed 16-bit unsigned normalized format (`B5G6R5Unorm`, `A1BGR5Unorm`, `ABGR4Unorm`, + /// `BGR5A1Unorm`), held as `R16_UINT`: each channel's field in the little-endian word, red, + /// green, blue and alpha, as its lowest bit and its width; `None` for a channel the format + /// lacks. + Packed16 { + /// The fields of red, green, blue and alpha. + fields: [Option; 4], + }, + /// An 8-bit sRGB format of one or two channels (`R8Unorm_sRGB`, `RG8Unorm_sRGB`), held as + /// `R8_UINT` or `R16_UINT`: each channel's byte in the little-endian word, red then green, + /// Metal's twelve-bit encode of the channel's value. + Srgb8 { + /// The fields of red, green, blue and alpha. + fields: [Option; 4], + }, + /// `RGB9E5Float`, held as `R32_UINT`: red's, green's and blue's nine-bit mantissas from bit + /// 0, under the exponent in bits 27 to 31. Its fields are the mantissas, which no write mask + /// keeps apart: a write of some of its channels is not built. + Rgb9e5, +} + +/// One channel's bits in a [`WordAttachment`]'s word. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct WordField { + /// The field's lowest bit. + pub shift: u8, + /// The field's width in bits. + pub bits: u8, +} + +impl WordAttachment { + /// The word layout of `pf`, whatever the device: `Some` for the formats a word view can + /// render. + pub fn layout(pf: PixelFormat) -> Option { + let f = |shift: u8, bits: u8| Some(WordField { shift, bits }); + // Metal names a packed format from its least significant bit. + let fields = match pf { + PixelFormat::B5G6R5Unorm => [f(11, 5), f(5, 6), f(0, 5), None], + PixelFormat::A1BGR5Unorm => [f(11, 5), f(6, 5), f(1, 5), f(0, 1)], + PixelFormat::ABGR4Unorm => [f(12, 4), f(8, 4), f(4, 4), f(0, 4)], + PixelFormat::BGR5A1Unorm => [f(10, 5), f(5, 5), f(0, 5), f(15, 1)], + PixelFormat::R8UnormSRGB => { + let fields = [f(0, 8), None, None, None]; + return Some(WordAttachment::Srgb8 { fields }); + } + PixelFormat::RG8UnormSRGB => { + let fields = [f(0, 8), f(8, 8), None, None]; + return Some(WordAttachment::Srgb8 { fields }); + } + PixelFormat::RGB9E5Float => return Some(WordAttachment::Rgb9e5), + _ => return None, + }; + Some(WordAttachment::Packed16 { fields }) + } + + /// How profile `p`'s device renders an attachment of `pf` through a word view: `Some` where + /// `pf` has a word layout ([`layout`](Self::layout)), the device holds the texture (it samples + /// `pf`'s own Vulkan format, or an 8-bit sRGB format's UNORM twin, in which the runtime holds + /// it, `srgb_raw_twin`) but does not render `pf`'s format, and renders the word's format. + /// `None` where it renders `pf` itself, or does not hold it. + pub fn of(pf: PixelFormat, p: &DeviceProfile) -> Option { + let word = WordAttachment::layout(pf)?; + let direct = super::direct_format(pf)?; + let twin = super::srgb_raw_twin(pf).and_then(super::direct_format); + let held = [Some(direct), twin] + .into_iter() + .flatten() + .any(|f| p.supports_format(f, FormatUsage::SampledImage)); + (held + && !p.supports_format(direct, FormatUsage::ColorAttachment) + && p.supports_format(word.word_format(), FormatUsage::ColorAttachment)) + .then_some(word) + } + + /// The unsigned integer format of the word, the attachment view's. + pub fn word_format(self) -> vk::Format { + match self { + WordAttachment::Packed16 { .. } => vk::Format::R16_UINT, + WordAttachment::Srgb8 { fields } if fields[1].is_none() => vk::Format::R8_UINT, + WordAttachment::Srgb8 { .. } => vk::Format::R16_UINT, + WordAttachment::Rgb9e5 => vk::Format::R32_UINT, + } + } + + /// The channels' fields: red, green, blue and alpha (`RGB9E5Float`'s mantissas). + pub fn fields(self) -> [Option; 4] { + let f = |shift: u8| Some(WordField { shift, bits: 9 }); + match self { + WordAttachment::Packed16 { fields } | WordAttachment::Srgb8 { fields } => fields, + WordAttachment::Rgb9e5 => [f(0), f(9), f(18), None], + } + } + + /// The word of the channels' codes `codes` (red, green, blue, alpha; a channel the format + /// lacks ignored, each code masked to its field). + pub fn pack(self, codes: [u32; 4]) -> u32 { + self.fields() + .iter() + .zip(codes) + .filter_map(|(f, c)| f.map(|f| (c & ((1u32 << f.bits) - 1)) << f.shift)) + .fold(0, |w, c| w | c) + } + + /// The word Metal stores for a `float` (or `half`) output `rgba`: a packed 16-bit format's + /// channel by `ChannelWrite::HalfUnorm`'s rule, an 8-bit sRGB format's by Metal's twelve-bit + /// encode (the module docs), a channel the format lacks ignored; `RGB9E5Float`'s word of a + /// `float` output (the module docs). The reference of the fragment function's encode. + pub fn output_word(self, rgba: [f32; 4]) -> u32 { + if self == WordAttachment::Rgb9e5 { + return rgb9e5_word([rgba[0], rgba[1], rgba[2]]); + } + let fields = self.fields(); + let mut codes = [0u32; 4]; + for (code, (f, x)) in codes.iter_mut().zip(fields.iter().zip(rgba)) { + if let Some(f) = f { + *code = match self { + WordAttachment::Packed16 { .. } => half_unorm_code(x, f.bits), + WordAttachment::Srgb8 { .. } => srgb_code(f64::from(x)), + WordAttachment::Rgb9e5 => 0, + }; + } + } + self.pack(codes) + } +} + +/// Metal's byte of an 8-bit sRGB channel's value `x`: clamped to `[0, 1]` (a NaN 0), the exact +/// product with 4095 rounded to nearest (no `float` meets a tie: 4095 is odd), and the byte of the +/// largest first index at most that (Metal's twelve-bit table, `lower::arith::srgb`'s, which its +/// render writes and clears share with `pack_float_to_srgb_unorm4x8`). +pub(crate) fn srgb_code(x: f64) -> u32 { + let x = if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0) }; + let i = (x * 4095.0).round_ties_even() as u16; + let first = &crate::lower::arith::srgb::SRGB_ENCODE_FIRST; + (1..256).rev().find(|&b| first[b] <= i).unwrap_or(0) as u32 +} + +/// The `RGB9E5Float` word Metal stores for `float` channels `rgb` (a draw's output, a clear's +/// color through `float`, a kernel's write): each clamped to `[0, 65408]` (a NaN, a negative value +/// and `-0` 0), the exponent `e = max(floor(log2 m), -16) + 16` of the largest clamped channel +/// `m`, and each mantissa the clamped channel times `2^(24 - e)` (exact) truncated, at most 511. +pub(crate) fn rgb9e5_word(rgb: [f32; 3]) -> u32 { + let clamped = rgb.map(|x| match x.is_nan() || x.is_sign_negative() { + true => 0.0, + false => x.min(65408.0), + }); + let largest = clamped.iter().copied().fold(0.0, f32::max); + // The exponent field of the largest: `floor(log2 m)` + 127 for a normal `m`. + let field = (largest.to_bits() >> 23).max(111); + let e = field - 111; + let scale = f64::from(2.0f32).powi(24 - e as i32); + clamped + .iter() + .enumerate() + .map(|(c, &x)| (((f64::from(x) * scale) as u32).min(511)) << (9 * c)) + .fold(e << 27, |w, m| w | m) +} + +/// The code of `x` in a unorm channel of `bits` bits that Metal reads through a `half`: `x` +/// rounded to `half`, nearest even (a NaN 0), clamped to `[0, 1]`, times `2^bits - 1`, rounded to +/// nearest even (the product of a `half` and a code of at most 16 bits is exact in `f64`). +pub(crate) fn half_unorm_code(x: f32, bits: u8) -> u32 { + let h = f64::from(crate::float16::f16_bits_to_f32( + crate::float16::f32_to_f16_bits(x), + )); + let h = if h.is_nan() { 0.0 } else { h.clamp(0.0, 1.0) }; + let m = f64::from((1u32 << bits) - 1); + (h * m).round_ties_even() as u32 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_layouts_are_metals_least_significant_first() { + let w = WordAttachment::layout(PixelFormat::A1BGR5Unorm).unwrap(); + // Alpha in bit 0, blue in 1..=5, green in 6..=10, red in 11..=15. + assert_eq!(w.pack([31, 0, 0, 0]), 0xf800); + assert_eq!(w.pack([0, 31, 0, 0]), 0x07c0); + assert_eq!(w.pack([0, 0, 31, 0]), 0x003e); + assert_eq!(w.pack([0, 0, 0, 1]), 0x0001); + let w = WordAttachment::layout(PixelFormat::ABGR4Unorm).unwrap(); + assert_eq!(w.pack([1, 2, 3, 4]), 0x1234); + let w = WordAttachment::layout(PixelFormat::B5G6R5Unorm).unwrap(); + assert_eq!(w.pack([31, 63, 31, 1]), 0xffff); + let w = WordAttachment::layout(PixelFormat::BGR5A1Unorm).unwrap(); + assert_eq!(w.pack([0, 0, 0, 1]), 0x8000); + assert_eq!(WordAttachment::layout(PixelFormat::RGBA8Unorm), None); + } + + /// The probe's answers: just below a half the `half` rounds to the half, which the code's + /// tie takes to even; a half itself is even; NaN and negatives are 0, past one the maximum. + #[test] + fn output_words_round_through_half_then_to_even() { + let below_half = f32::from_bits(0.5f32.to_bits() - 1); + assert_eq!(half_unorm_code(below_half, 5), 16); + assert_eq!(half_unorm_code(below_half, 4), 8); + assert_eq!(half_unorm_code(0.5, 6), 32); + assert_eq!(half_unorm_code(0.5, 1), 0); + assert_eq!(half_unorm_code(f32::NAN, 5), 0); + assert_eq!(half_unorm_code(-1.0, 5), 0); + assert_eq!(half_unorm_code(7.0, 4), 15); + // `half` 0.09998 times 15 is 1.4997: an ABGR4 alpha of 0.1 is 1. + assert_eq!(half_unorm_code(0.1, 4), 1); + let w = WordAttachment::layout(PixelFormat::A1BGR5Unorm).unwrap(); + assert_eq!(w.output_word([1.0, 0.0, 1.0, 0.5]), 0xf83e); + } + + /// The M3 Max's clears of the in-guest probe: an `R8Unorm_sRGB` clear of 0.2 stores 0x7c, an + /// `RG8Unorm_sRGB` one of (0.2, 0.4) 0x7c then 0xaa; NaN and negatives are 0, past one 0xff. + #[test] + fn srgb_words_take_metals_encode() { + assert_eq!(srgb_code(f64::from(0.2f32)), 0x7c); + assert_eq!(srgb_code(f64::from(0.4f32)), 0xaa); + assert_eq!(srgb_code(f64::NAN), 0); + assert_eq!(srgb_code(-1.0), 0); + assert_eq!(srgb_code(2.0), 0xff); + let r8 = WordAttachment::layout(PixelFormat::R8UnormSRGB).unwrap(); + assert_eq!(r8.word_format(), vk::Format::R8_UINT); + assert_eq!(r8.output_word([0.2, 0.4, 0.6, 0.8]), 0x7c); + let rg8 = WordAttachment::layout(PixelFormat::RG8UnormSRGB).unwrap(); + assert_eq!(rg8.word_format(), vk::Format::R16_UINT); + assert_eq!(rg8.output_word([0.2, 0.4, 0.6, 0.8]), 0xaa7c); + } + + /// The format scout's draw on the M3 Max: (2.5, 0.375, -0.75) stores `0x88006140`; the + /// probe's clear of (0.25, 0, 1.125) `0x84800040`; past 65408 is 65408, NaN and negatives 0, + /// and a channel below the exponent's step truncates to 0. + #[test] + fn rgb9e5_words_truncate_under_the_largest_exponent() { + let w = WordAttachment::layout(PixelFormat::RGB9E5Float).unwrap(); + assert_eq!(w.word_format(), vk::Format::R32_UINT); + assert_eq!(w.output_word([2.5, 0.375, -0.75, 0.5]), 0x8800_6140); + assert_eq!(rgb9e5_word([0.25, 0.0, 1.125]), 0x8480_0040); + assert_eq!(rgb9e5_word([70000.0, f32::NAN, -0.0]), (31 << 27) | 511); + assert_eq!(rgb9e5_word([0.0; 3]), 0); + // 1 + 2^-9 under the exponent of 1 (a step of 2^-8) truncates to 1; 2^-10 is 0 there. + assert_eq!( + rgb9e5_word([1.0 + 2f32.powi(-9), 2f32.powi(-10), 0.0]), + (16 << 27) | 256 + ); + // The smallest exponent: 2^-24 is mantissa 1 under exponent 0. + assert_eq!(rgb9e5_word([2f32.powi(-24), 0.0, 0.0]), 1); + } + + #[test] + fn a_word_view_serves_where_the_device_holds_but_cannot_render_the_format() { + use crate::pipeline::testing::{profile, EXACT_SAMPLING}; + let nvidia = profile("nvidia-rtx5080-laptop", EXACT_SAMPLING).unwrap(); + let lavapipe = profile("lavapipe", EXACT_SAMPLING).unwrap(); + for pf in [PixelFormat::A1BGR5Unorm, PixelFormat::ABGR4Unorm] { + assert_eq!( + WordAttachment::of(pf, &nvidia), + WordAttachment::layout(pf), + "{pf:?}" + ); + assert_eq!(WordAttachment::of(pf, &lavapipe), None, "{pf:?}"); + } + // The 5080 renders neither `R8_SRGB` nor `R8G8_SRGB` (it holds the latter in its twin). + for pf in [PixelFormat::R8UnormSRGB, PixelFormat::RG8UnormSRGB] { + assert_eq!( + WordAttachment::of(pf, &nvidia), + WordAttachment::layout(pf), + "{pf:?}" + ); + } + // The 5080 samples `E5B9G9R9_UFLOAT_PACK32` and does not render it; RADV renders it. + assert_eq!( + WordAttachment::of(PixelFormat::RGB9E5Float, &nvidia), + Some(WordAttachment::Rgb9e5) + ); + let radv = profile("amd-rdna3-radv", EXACT_SAMPLING).unwrap(); + assert_eq!(WordAttachment::of(PixelFormat::RGB9E5Float, &radv), None); + // Vulkan makes `R5G6B5` and `A1R5G5B5` attachments mandatory. + for pf in [PixelFormat::B5G6R5Unorm, PixelFormat::BGR5A1Unorm] { + assert_eq!(WordAttachment::of(pf, &nvidia), None, "{pf:?}"); + } + assert_eq!(WordAttachment::of(PixelFormat::RGBA8Unorm, &nvidia), None); + } +} diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index 45e9644c2..7b583978b 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -389,6 +389,11 @@ mod serde_round_trips { true, ), )]), + word_colors: BTreeMap::from([( + 5, + crate::metal::format::WordAttachment::layout(metal::PixelFormat::ABGR4Unorm) + .expect("a word layout"), + )]), srgb_fetches: BTreeSet::from([0, 2]), zeroed_colors: BTreeMap::from([(2, metal::PixelFormat::RGBA32Sint)]), dropped_colors: BTreeSet::from([3]), diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 3c756c01b..900e72406 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -1078,6 +1078,19 @@ pub enum PrecisionNote { /// such a buffer may hold a 1-bit alpha). Every other `float` texel write to a normalized /// storage texture rounds to Metal's code in the shader. /// + /// Also: a blend into a packed 16-bit unorm attachment (`B5G6R5Unorm`, `A1BGR5Unorm`, + /// `ABGR4Unorm`, `BGR5A1Unorm`) reads what the device's attachment holds, its channels' codes, + /// where Metal's tile memory holds the pass's clear and each earlier blend's result finer than + /// those codes until the store (measured on an Apple M3 Max under macOS 27.0.1: in a pass that + /// clears and blends, and over two blends in one pass, every channel where the two readings + /// store different codes stored the finer one's, `half` precision fitting all of them, + /// single-sampled and 4x alike; a pass that loads what an earlier pass stored blends against + /// the codes). Such a blend may store a code one apart from Metal's. So does the blend the + /// function computes into such an attachment the device renders through its word view + /// (`metal::format::WordAttachment`), which under fast math also sums a few states otherwise + /// than Metal (3,527 of 94,732,288 channels measured a code apart, none further). `RGBA8Unorm` + /// and `RGB10A2Unorm` hold their codes there, as the device does. + /// /// Validation derives no tolerance and no explanation from it: a difference stays a /// mismatch for review. DeviceColorConversion, diff --git a/crates/metal2vulkan/src/pipeline/color_writes.rs b/crates/metal2vulkan/src/pipeline/color_writes.rs index 0f3570cf4..50eddad9c 100644 --- a/crates/metal2vulkan/src/pipeline/color_writes.rs +++ b/crates/metal2vulkan/src/pipeline/color_writes.rs @@ -102,6 +102,10 @@ pub(crate) fn exact_writes( let Some(c) = colors.get(attachment as usize).copied().flatten() else { continue; }; + // A word attachment's output is the word the function encodes (`word_colors`). + if word_color(attachment, &c, alpha_to_coverage, p).is_some() { + continue; + } let coverage_alpha = attachment == 0 && alpha_to_coverage; let write = match metal { true => metal_stored(&c), @@ -377,6 +381,7 @@ pub(crate) fn check( }); if writes_hold(fragment, colors, (alpha_to_coverage, rounding), p) && wanted_extended_range(fragment, colors, rounding) == io.extended_range_colors + && wanted_word_colors(fragment, colors, alpha_to_coverage, p) == io.word_colors && wanted_srgb_fetches(fragment, colors) == io.srgb_fetches && wanted_rotated(fragment, colors) == io.rotated_colors && wanted_rotated_factors(fragment, colors, p) == io.rotated_factors @@ -447,6 +452,166 @@ pub(crate) fn extended_range_colors( .collect() } +/// The word view through which profile `p`'s device renders color attachment `index` of a +/// render pipeline, described by `c`, that covers by alpha where `alpha_to_coverage` +/// (`LoweringInputs::word_colors`): `metal::format::WordAttachment::of` the attachment's format, +/// where the pipeline writes it unblended (or blended with factors one and zero, added, which +/// Metal stores alike), under a write mask of all of the format's channels or none, or of some of +/// them where the function merges the word into the texel over its input attachment +/// ([`merged_word`]), and it is not attachment 0 under alpha-to-coverage (whose coverage reads the +/// output's alpha as computed). `None` for every other attachment: one the function stores in the +/// interlocked storage form ([`stored_word`]), or one that takes its format's own attachment, as +/// the device has it or not. +pub(crate) fn word_color( + index: u32, + c: &ColorAttachmentDescriptor, + alpha_to_coverage: bool, + p: &DeviceProfile, +) -> Option { + let word = metal::format::WordAttachment::of(c.pixel_format, p)?; + let kept = c.write_mask & word_channels(word); + let whole = kept.is_empty() || kept == word_channels(word); + let merged = merges_over_input(c, word, p); + let unblended = !c.blending_enabled || replaces(c); + (unblended && (whole || merged) && !(index == 0 && alpha_to_coverage)).then_some(word) +} + +/// The channels of `word`'s fields: Metal's red, green, blue and alpha, in its field order. +fn word_channels(word: metal::format::WordAttachment) -> metal::ColorWriteMask { + use metal::ColorWriteMask as M; + [M::RED, M::GREEN, M::BLUE, M::ALPHA] + .into_iter() + .zip(word.fields()) + .filter(|(_, f)| f.is_some()) + .fold(M::NONE, |m, (bit, _)| m | bit) +} + +/// Whether the fragment function merges its word of attachment `c` (a `word` attachment) into the +/// texel over the attachment's input attachment: a write mask of some of the word's channels, on a +/// device that orders framebuffer fetch through rasterization-order input attachments +/// (`lower::fragment`'s `word_input`), for a format whose mask the function compiles as the +/// descriptor sets it (`lower::fragment::fetch::kept_at_draw` false: the 8-bit sRGB words, where a +/// packed 16-bit or `RGB9E5Float` word's mask stands for its class). +fn merges_over_input( + c: &ColorAttachmentDescriptor, + word: metal::format::WordAttachment, + p: &DeviceProfile, +) -> bool { + let channels = word_channels(word); + let kept = c.write_mask & channels; + let partial = !kept.is_empty() && kept != channels; + partial + && !crate::lower::fragment::fetch::kept_at_draw(c.pixel_format) + && crate::lower::fragment::inputs_order(p) +} + +/// The channels the fragment function keeps from the texel of color attachment `index` of a +/// render pipeline, described by `c`, that covers by alpha where `alpha_to_coverage`, where it +/// merges its word into the texel over the attachment's input attachment ([`word_color`], +/// `lower::fragment`'s `word_input`): those of the word's channels the write mask leaves out. +/// `None` for every other attachment. +pub(crate) fn merged_word( + index: u32, + c: &ColorAttachmentDescriptor, + alpha_to_coverage: bool, + p: &DeviceProfile, +) -> Option { + let word = word_color(index, c, alpha_to_coverage, p)?; + merges_over_input(c, word, p).then(|| word_channels(word).difference(c.write_mask)) +} + +/// The word view of color attachment `c` of a render pipeline on profile `p` whose writes the +/// fragment function stores in the interlocked storage form (`lower::fragment::fetch`), reading +/// the word first inside the interlock: a packed 16-bit word attachment +/// (`metal::format::WordAttachment::of`) written under a blend other than one and zero, added, +/// whose factors read no second source (Metal's packed 16-bit blend, which the function computes +/// over the word, `extended_range::Blend::packed16`), or a word attachment other than +/// `RGB9E5Float`'s written unblended under a write mask of some of the format's channels (the +/// function merges the fields of the channels the mask keeps), on a device that orders fetch +/// through the pixel interlock alone. +/// `None` for every other attachment, and for a write mask of none of the format's channels. +pub(crate) fn stored_word( + c: &ColorAttachmentDescriptor, + p: &DeviceProfile, +) -> Option { + use metal::{BlendFactor as F, ColorWriteMask as M}; + let word = metal::format::WordAttachment::of(c.pixel_format, p)?; + let channels = [M::RED, M::GREEN, M::BLUE, M::ALPHA] + .into_iter() + .zip(word.fields()) + .filter(|(_, f)| f.is_some()) + .fold(M::NONE, |m, (bit, _)| m | bit); + let kept = c.write_mask & channels; + let partial = !kept.is_empty() && kept != channels; + let unblended = !c.blending_enabled || replaces(c); + let second = [ + c.source_rgb_blend_factor, + c.destination_rgb_blend_factor, + c.source_alpha_blend_factor, + c.destination_alpha_blend_factor, + ] + .iter() + .any(|f| { + matches!( + f, + F::Source1Color | F::OneMinusSource1Color | F::Source1Alpha | F::OneMinusSource1Alpha + ) + }); + // Metal's blend of a packed 16-bit word is built; an 8-bit sRGB word's is not, nor is an + // `RGB9E5Float` word's blend or partial mask (its mantissas share the exponent). + let packed = matches!(word, metal::format::WordAttachment::Packed16 { .. }); + let fielded = word != metal::format::WordAttachment::Rgb9e5; + let stored = match unblended { + true => partial && fielded, + false => packed && !kept.is_empty() && !second, + }; + (stored && crate::lower::fragment::interlock_orders(p)).then_some(word) +} + +/// The word attachments of a render pipeline whose color attachments are `colors` (covering by +/// alpha where `alpha_to_coverage`) on `p`, by color index ([`word_color`]). +pub(crate) fn word_colors( + colors: &[Option], + alpha_to_coverage: bool, + p: &DeviceProfile, +) -> BTreeMap { + colors + .iter() + .enumerate() + .filter_map(|(i, c)| { + let word = word_color(i as u32, c.as_ref()?, alpha_to_coverage, p)?; + Some((i as u32, word)) + }) + .collect() +} + +/// The word attachments the fragment stage `fragment` writes through output variables of +/// dual-source index 0 in a render pipeline whose color attachments are `colors` (covering by +/// alpha where `alpha_to_coverage`) on `p`: [`word_colors`]'s, for those attachments. +pub(crate) fn wanted_word_colors( + fragment: &FunctionArtifact, + colors: &[Option], + alpha_to_coverage: bool, + p: &DeviceProfile, +) -> BTreeMap { + let written: BTreeSet = fragment + .interface + .io + .outputs + .iter() + .filter_map(|v| match v.role { + IoRole::Color { + attachment, + index: 0, + } => Some(attachment), + _ => None, + }) + .collect(); + let mut out = word_colors(colors, alpha_to_coverage, p); + out.retain(|a, _| written.contains(a)); + out +} + /// The color attachments of a render pipeline whose color attachments are `colors` held with /// their channels rotated, by color index (`LoweringInputs::rotated_colors`): every attachment /// of a format `metal::format::rotated_channels` names (`ARGB8Unorm`). diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 25217aeed..294d86505 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -1627,7 +1627,9 @@ pub(crate) fn unattached_colors_written( /// (`VariantKey::interlocked_colors`); `None` on another device or for an entry that declares none /// of them. On a device that orders fetch through rasterization-order input attachments, the state /// of every extended-range attachment the entry writes that the pass blends (whose blend the -/// function computes over its input attachment, `lower::fragment`'s `input_blend`). Where the +/// function computes over its input attachment, `lower::fragment`'s `input_blend`), and of every +/// word attachment it writes under a mask of some of the word's channels (whose word the function +/// merges into its input attachment's, `color_writes::merged_word`). Where the /// profile asks for Metal's 16-bit float blend of a `half4` output (`DevicePolicy::half_blend`) on /// a device that orders fetch through the interlock, also every such attachment the entry writes, /// those it names for that alone in `FramebufferFetchInputs::half_blends`. @@ -1638,7 +1640,7 @@ pub(crate) fn fetch_inputs( p: &DeviceProfile, ) -> Option { let interlock = crate::lower::fragment::interlock_orders(p); - let inputs = !interlock && p.fields().fragment.rasterization_order_color_access; + let inputs = crate::lower::fragment::inputs_order(p); if !matches!(spec.ep.stage, AbiStage::Fragment { .. }) || !(interlock || inputs) { return None; } @@ -1673,6 +1675,27 @@ pub(crate) fn fetch_inputs( && crate::metal::format::ExtendedRange::of(c.pixel_format).is_some() }) }; + // A word attachment whose writes the function blends over, or merges into, the word it reads. + let stored_word = |color: u32| { + d.color_attachments + .get(color as usize) + .copied() + .flatten() + .and_then(|c| crate::pipeline::color_writes::stored_word(&c, p)) + .is_some() + }; + // A word attachment whose writes the function merges into the word its input attachment + // holds. + let merged_word = |color: u32| { + d.color_attachments + .get(color as usize) + .copied() + .flatten() + .and_then(|c| { + crate::pipeline::color_writes::merged_word(color, &c, d.alpha_to_coverage, p) + }) + .is_some() + }; let read: BTreeSet = spec .ep .params @@ -1689,7 +1712,12 @@ pub(crate) fn fetch_inputs( attachment: AbiInt::Const(color), index: 0, .. - } if blended(color) => Some(color), + } if blended(color) + || (interlock && stored_word(color)) + || (inputs && merged_word(color)) => + { + Some(color) + } // A color the draw's instance keeps out of its subpass, written through the storage // form as a fetched one is. OutputRole::RenderTarget { @@ -1760,7 +1788,8 @@ pub(crate) fn fragment_inputs( d.color_attachments, d.texture_write_rounding_mode, ); - out.rotated_colors = crate::pipeline::color_writes::rotated_colors(d.color_attachments); + out.word_colors = + crate::pipeline::color_writes::word_colors(d.color_attachments, d.alpha_to_coverage, p); out.rotated_factors = crate::pipeline::color_writes::rotated_factors(d.color_attachments, p); out.rotated_blends = crate::pipeline::color_writes::rotated_blends(d.color_attachments, p); out.sample_mask = d.sample_mask; diff --git a/crates/metal2vulkan/src/pipeline/compile/key.rs b/crates/metal2vulkan/src/pipeline/compile/key.rs index 0b3264211..ee69c538c 100644 --- a/crates/metal2vulkan/src/pipeline/compile/key.rs +++ b/crates/metal2vulkan/src/pipeline/compile/key.rs @@ -225,6 +225,11 @@ pub fn function_key( .bytes(format!("{:?}", inputs.extended_range_colors).as_bytes()); } // Appended only when set, as `storage_view_slots`. + if !inputs.word_colors.is_empty() { + h.bytes(b"word-colors") + .bytes(format!("{:?}", inputs.word_colors).as_bytes()); + } + // Appended only when set, as `storage_view_slots`. if !inputs.srgb_fetches.is_empty() { h.bytes(b"srgb-fetches") .bytes(format!("{:?}", inputs.srgb_fetches).as_bytes()); diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index 6ca0d6254..f3320c5ef 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -662,6 +662,7 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() { .replace(", folded_groups: false", "") .replace(", extended_range: {}", "") .replace(", extended_range_colors: {}", "") + .replace(", word_colors: {}", "") .replace(", srgb_fetches: {}", "") .replace(", zeroed_colors: {}", "") .replace(", dropped_colors: {}", "") diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 3442b579a..a95218b58 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -636,6 +636,18 @@ pub enum RuntimeFact { blend: crate::pipeline::lower_inputs::BlendEquation, kept: crate::vk::ColorComponentFlags, }, + /// On a device that orders framebuffer fetch through rasterization-order input attachments, + /// the function writes color attachment `color`, which renders through a view of its word + /// (`metal::format::WordAttachment`, an 8-bit sRGB one), under a write mask of some of the + /// word's channels: it reads the texel's word through the attachment's input attachment + /// (`RuntimeFact::FramebufferFetch`) and writes Metal's word of its output with the fields of + /// the channels `kept` (those of the word the descriptor's write mask leaves out) taken from + /// the word read. Link writes the whole word, and a pipeline of another write mask there is + /// `NeedsInput(FramebufferFetch)`. + WordInputMerge { + color: u32, + kept: crate::vk::ColorComponentFlags, + }, /// The function reads, samples or gathers the sampled color texture (not a texture buffer, /// a multisampled or a depth texture) bound to the slot only with `float`, `half` or 32-bit /// integer results: bound to a texture of a color format whose numeric class is not the diff --git a/crates/metal2vulkan/src/pipeline/link.rs b/crates/metal2vulkan/src/pipeline/link.rs index 511d6ab58..25bb02580 100644 --- a/crates/metal2vulkan/src/pipeline/link.rs +++ b/crates/metal2vulkan/src/pipeline/link.rs @@ -484,6 +484,9 @@ fn render_state( // The extended-range blends the fragment computes over input attachments, against this // pipeline's attachments. let input_blends = fetch::input_blends(r, fragment, p)?; + // The word merges the fragment computes over input attachments, against this pipeline's + // write masks. + fetch::word_merges(r, fragment, p)?; let fs = fragment.map(|f| &f.interface); let mut gs = graphics::graphics_state(r, (geometry, fs), vi, ts, &input_blends, p)?; // The color writes the fragment rounds against this pipeline's attachments, once the diff --git a/crates/metal2vulkan/src/pipeline/link/fetch.rs b/crates/metal2vulkan/src/pipeline/link/fetch.rs index fbd0aadfb..97c630ce6 100644 --- a/crates/metal2vulkan/src/pipeline/link/fetch.rs +++ b/crates/metal2vulkan/src/pipeline/link/fetch.rs @@ -30,6 +30,10 @@ //! attachment of the subpass, which `graphics_state` gives no Vulkan blend and a write of every raw //! component, the function merging the channels the descriptor's mask keeps; a stage compiled under //! another blend or mask there was compiled for another pipeline, `NeedsInput(FramebufferFetch)`. +//! There too the function merges its word of a word attachment written under a mask of some of +//! the word's channels into the word its input attachment holds (`RuntimeFact::WordInputMerge`, +//! [`word_merges`]); `graphics_state` writes the whole word, and a stage compiled under another +//! mask there, or without the merge, was compiled for another pipeline. use std::collections::BTreeMap; @@ -40,13 +44,14 @@ use crate::error::{ }; use crate::library::FunctionArtifact; use crate::lower::fragment::{ - interlock_orders, kept_channels, storage_form, ColorUse, StorageSamples, + inputs_order, interlock_orders, kept_channels, storage_form, ColorUse, StorageSamples, }; use crate::metal::state::color_write_mask; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::graphics::{StorageAttachmentUse, StorageAttachmentView}; use crate::pipeline::link::RenderLinkInputs; use crate::pipeline::lower_inputs::{BlendEquation, FramebufferFetchInputs}; +use crate::pipeline::stage_io::IoRole; /// The attachments the fragment stage `fragment` of render inputs `r` reads in the storage form /// on `p`, by color index (see the module docs). @@ -182,7 +187,7 @@ pub fn input_blends( let RuntimeFact::ExtendedRangeInputBlend { color, blend, kept } = *fact else { continue; }; - if interlock_orders(p) || !p.fields().fragment.rasterization_order_color_access { + if !inputs_order(p) { return Err(Error::Internal(InternalError::new( InternalKind::Invariant, "an extended-range blend over an input attachment on a device that fetches \ @@ -200,3 +205,55 @@ pub fn input_blends( } Ok(out) } + +/// The word merges the fragment stage `fragment` computes over input attachments +/// (`RuntimeFact::WordInputMerge`), against the attachments of render inputs `r` on `p`: each +/// attachment the stage writes through a first output whose word the pipeline's state merges +/// (`color_writes::merged_word`) needs the stage's merge keeping the channels the mask leaves out, +/// and each merge the stage states needs that state. A stage compiled under another mask there, +/// or without the merge, is `NeedsInput(FramebufferFetch)`. +pub fn word_merges( + r: &RenderLinkInputs, + fragment: Option<&FunctionArtifact>, + p: &DeviceProfile, +) -> Result<(), Error> { + let Some(f) = fragment else { + return Ok(()); + }; + let stated: BTreeMap = f + .facts + .iter() + .filter_map(|fact| match *fact { + RuntimeFact::WordInputMerge { color, kept } => Some((color, kept)), + _ => None, + }) + .collect(); + if !stated.is_empty() && !inputs_order(p) { + return Err(Error::Internal(InternalError::new( + InternalKind::Invariant, + "a word merge over an input attachment on a device that fetches otherwise", + ))); + } + let mut wanted = BTreeMap::new(); + for o in &f.interface.io.outputs { + let IoRole::Color { + attachment: color, + index: 0, + } = o.role + else { + continue; + }; + let Some(a) = r.color_attachments.get(color as usize).copied().flatten() else { + continue; + }; + if let Some(kept) = + crate::pipeline::color_writes::merged_word(color, &a, r.alpha_to_coverage, p) + { + wanted.insert(color, color_write_mask(kept)?); + } + } + match stated == wanted { + true => Ok(()), + false => Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)), + } +} diff --git a/crates/metal2vulkan/src/pipeline/link/graphics.rs b/crates/metal2vulkan/src/pipeline/link/graphics.rs index 40358a4d4..700f94664 100644 --- a/crates/metal2vulkan/src/pipeline/link/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/link/graphics.rs @@ -340,6 +340,36 @@ pub fn graphics_state( Some(_) if storage.contains(&(index as u32)) => None, Some(a) => { let state = || -> Result { + // A word attachment renders through the view of its word, which the function + // writes whole and unblended (`color_writes::word_color`): its one component, + // where the function writes the attachment and the mask keeps some of the + // format's channels (all of them, or some where the function merges the word + // into its input attachment's, `fetch::word_merges`). + if let Some(word) = + color_writes::word_color(index as u32, a, r.alpha_to_coverage, p) + { + let channels = [ + vk::ColorComponentFlags::R, + vk::ColorComponentFlags::G, + vk::ColorComponentFlags::B, + vk::ColorComponentFlags::A, + ] + .into_iter() + .zip(word.fields()) + .filter(|(_, f)| f.is_some()) + .fold(vk::ColorComponentFlags::empty(), |m, (c, _)| m | c); + let kept = color_write_mask(a.write_mask)? & channels; + let write_mask = match written.contains(&(index as u32)) && !kept.is_empty() + { + true => vk::ColorComponentFlags::R, + false => vk::ColorComponentFlags::empty(), + }; + return Ok(ColorAttachmentState { + format: word.word_format(), + write_mask, + blend: None, + }); + } // The fragment function writes what Metal's blend of one and zero stores, // so the attachment takes no Vulkan blend, nor the format's blend support: // one it rounds, and one it writes as a half's bits. But not a 16-bit float @@ -489,9 +519,13 @@ pub fn graphics_state( return Err(refused.at_attachment(Attachment::Color(color)).into()); } // An extended-range attachment's input reads its raw texels, the raw format's - // `uint`s, which a stage compiled for the attachment decodes (`color_writes::check`). + // `uint`s, which a stage compiled for the attachment decodes (`color_writes::check`); + // a word attachment's reads its word, which a stage merges (`fetch::word_merges`). + let word = + color_writes::word_color(color, &attachment, r.alpha_to_coverage, p).is_some(); let format_class = match ExtendedRange::of(attachment.pixel_format) { Some(_) => SampledType::Uint, + None if word => SampledType::Uint, None => sampled_type(attachment.pixel_format).unwrap_or(SampledType::Float), }; input_attachments.push(InputAttachmentUse { diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index ebc2339f4..300652809 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -378,6 +378,21 @@ pub struct LoweringInputs { /// one compiled under another as `NeedsInput(ColorWrites)`. Empty for any other function. #[cfg_attr(feature = "serde", serde(default))] pub extended_range_colors: BTreeMap, + /// The color attachments the device renders through a word view + /// (`metal::format::WordAttachment`), by color index: an attachment the pipeline writes + /// unblended (or blended with factors one and zero, added), under a write mask of all of the + /// format's channels or none, and that is not attachment 0 under alpha-to-coverage, of a format + /// the device samples but does not render (one written under a mask of some of its channels + /// is stored in the interlocked storage form instead, named in + /// [`framebuffer_fetch`](Self::framebuffer_fetch)). The function writes such an attachment + /// through an output variable of the word's unsigned integer, the word Metal stores for its + /// `float` or `half` output (`ChannelWrite::HalfUnorm`'s rule per channel); a dual-source + /// second output there is stored nowhere, as Metal's unblended write reads none, and a color + /// input of one is `NotImplemented(Format)`. `Device::compile_render_pipeline` sets it for a + /// `Function` fragment stage from the pipeline's color attachments, and link refuses a fragment + /// compiled under another map as `NeedsInput(ColorWrites)`. Empty for any other function. + #[cfg_attr(feature = "serde", serde(default))] + pub word_colors: BTreeMap, /// The color attachments the fragment function reads (`[[color(n)]]`) that its render /// pipeline gives an 8-bit four-channel sRGB format (`RGBA8Unorm_sRGB`, `BGRA8Unorm_sRGB`), /// by color index. Read through an input attachment, such an attachment's value is the diff --git a/crates/metal2vulkan/src/pipeline/stage_io.rs b/crates/metal2vulkan/src/pipeline/stage_io.rs index 404ecccbb..ff5b6a39b 100644 --- a/crates/metal2vulkan/src/pipeline/stage_io.rs +++ b/crates/metal2vulkan/src/pipeline/stage_io.rs @@ -217,6 +217,15 @@ pub struct StageIo { /// stage compiled for another map than the pipeline's (`NeedsInput(ColorWrites)`). #[cfg_attr(feature = "serde", serde(default))] pub extended_range_colors: BTreeMap, + /// The word attachments the fragment function writes a `float` or `half` output to through + /// output variables of dual-source index 0 (`LoweringInputs::word_colors`), by color index: + /// each output variable there is declared as the word's unsigned integer and holds the word + /// Metal stores ([`StageIo::declared_type`]; the variable's `ty` stays the Metal output's, + /// which link checks against the attachment's format), and link gives the attachment the + /// word's format and refuses a stage compiled for another map than the pipeline's + /// (`NeedsInput(ColorWrites)`). + #[cfg_attr(feature = "serde", serde(default))] + pub word_colors: BTreeMap, /// The input attachments the fragment function reads through Metal's decode of their bytes /// (`LoweringInputs::srgb_fetches`): each read snaps the device's sRGB decode back to its /// byte and decodes that by Metal's table. Link refuses a stage compiled for another set @@ -514,7 +523,8 @@ impl StageIo { /// The type variable `v` is declared with: its `ty`, but for a color output of dual-source /// index 0 to an attachment among `extended_range_colors` the raw texel's, the raw format's - /// unsigned 32-bit components. + /// unsigned 32-bit components, and to one among `word_colors` the word's, one unsigned 32-bit + /// component. pub(crate) fn declared_type(&self, v: &IoVariable) -> IoType { let IoRole::Color { attachment, @@ -523,6 +533,14 @@ impl StageIo { else { return v.ty; }; + if self.word_colors.contains_key(&attachment) { + return IoType { + numeric: IoNumeric::Uint, + components: 1, + source_bits: 32, + bits: 32, + }; + } match self.extended_range_colors.get(&attachment) { Some(e) => IoType { numeric: IoNumeric::Uint, diff --git a/crates/metal2vulkan/src/pipeline/testing.rs b/crates/metal2vulkan/src/pipeline/testing.rs index fd147fbbf..4bc0363ad 100644 --- a/crates/metal2vulkan/src/pipeline/testing.rs +++ b/crates/metal2vulkan/src/pipeline/testing.rs @@ -205,7 +205,8 @@ pub fn fragment_inputs( &r.color_attachments, r.texture_write_rounding_mode, ); - inputs.rotated_colors = crate::pipeline::color_writes::rotated_colors(&r.color_attachments); + inputs.word_colors = + crate::pipeline::color_writes::word_colors(&r.color_attachments, r.alpha_to_coverage, p); inputs.half_output_lanes = crate::pipeline::color_writes::half_output_lanes(&r.color_attachments); inputs.rotated_factors = diff --git a/crates/metal2vulkan/src/tests/engine_word_attachments.rs b/crates/metal2vulkan/src/tests/engine_word_attachments.rs new file mode 100644 index 000000000..28b7c4783 --- /dev/null +++ b/crates/metal2vulkan/src/tests/engine_word_attachments.rs @@ -0,0 +1,566 @@ +//! Color attachments a device renders through the view of their word +//! (`metal::format::WordAttachment`, `LoweringInputs::word_colors`). +//! +//! - On the RTX 5080's profile, which samples `R5G5B5A1_UNORM_PACK16` and `R4G4B4A4_UNORM_PACK16` +//! but renders neither, a fragment function compiled for a pipeline with an `A1BGR5Unorm` or +//! `ABGR4Unorm` attachment (`rt6_fill_rgba32float`, `rt6_fill_rgba16float`) records the +//! attachment (`StageIo::word_colors`), keeps its interface variable's Metal type, declares the +//! output variable as one `uint`, bounds its emission by the plan's estimate, and links: the +//! attachment takes `R16_UINT`, a write of its one component under a full mask and of none under +//! an empty one, no blend, and both modules pass L3. +//! - Where the device renders the format (lavapipe), the attachment takes the format itself. +//! - A mask of some of the format's channels, or a blend, on the 5080, which orders fetch through +//! the pixel interlock: the whole render pipeline, made on the profile's device, writes the +//! attachment in the interlocked storage form (`color_writes::stored_word`), a written storage +//! attachment of `R16_UINT` without a view alias, keeping the channels the mask leaves out, and +//! no color attachment of the subpass; a blended one's fragment notes `DeviceColorConversion`; +//! its stages pass L3. Compiled without the pipeline's fetch state, such a mask or blend is the +//! device's lack of the format. +//! - The 8-bit sRGB formats the 5080 renders through their words (`R8Unorm_sRGB`, +//! `RG8Unorm_sRGB`) write the word too, and merge a partial mask in the interlock; a blend of one +//! is the device's lack of the format. +//! - On lavapipe, which renders neither `R8_SRGB` nor `R8G8_SRGB` and orders fetch through +//! rasterization-order input attachments, an `RG8Unorm_sRGB` attachment written under a mask of +//! some of its channels keeps its `R16_UINT` color attachment, written whole, and its fragment +//! merges the word into its input attachment's (`lower::fragment`'s `word_input`), stating the +//! channels it keeps (`RuntimeFact::WordInputMerge`); a fragment compiled under another mask, or +//! under a full one, does not link there (`NeedsInput(FramebufferFetch)`). +//! - `RGB9E5Float`, which the 5080 samples and does not render, takes a `float` output's word +//! through `R32_UINT`; a `half` output is `NotImplemented(Format)`, and a partial mask or a +//! blend the device's lack of the format. +//! - A fragment compiled without the pipeline's attachments does not link +//! (`NeedsInput(ColorWrites)`). +//! +//! The encode's and the blend's words are `lower::arith`'s tests' +//! (`word_attachments_store_metals_words`, `a_packed_word_attachment_blend_stores_metals_words`). + +use std::collections::BTreeMap; + +use std::path::Path; + +use crate::budget::Budget; +use crate::device::{Device, DeviceDescription, DevicePolicy}; +use crate::error::{Error, Feature, Needs, RuntimeInput}; +use crate::library::{FunctionConstantValues, Library}; +use crate::lower::select::LowerInputs; +use crate::metal::format::WordAttachment; +use crate::metal::{self, ColorWriteMask, PixelFormat}; +use crate::pipeline::artifact::PrecisionNote; +use crate::pipeline::compile::{plan_bitcode, EntryRef}; +use crate::pipeline::descriptor::{ + ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource, +}; +use crate::pipeline::link::{link, LinkInputs, RenderLinkInputs}; +use crate::pipeline::relocate::relocate; +use crate::pipeline::stage_io::{IoNumeric, IoRole}; +use crate::pipeline::testing::{ + compile, compile_with, engine_dir, fragment_inputs, llvm_assemble, meter, profile, + AssembleError, +}; +use crate::spirv::testing::{check_words_valid, spirv_dis}; +use crate::vk; + +const FORMATS: [PixelFormat; 2] = [PixelFormat::A1BGR5Unorm, PixelFormat::ABGR4Unorm]; + +/// The 8-bit sRGB formats the 5080 renders through their words. +const SRGB: [PixelFormat; 2] = [PixelFormat::R8UnormSRGB, PixelFormat::RG8UnormSRGB]; + +const ENTRIES: [&str; 2] = ["rt6_fill_rgba32float", "rt6_fill_rgba16float"]; + +fn fixture() -> Option> { + match llvm_assemble(&engine_dir().join("rt6_samples.ll")) { + Ok(b) => Some(b), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected rt6_samples.ll: {why}"), + } +} + +fn venue(stem: &str) -> crate::device::profile::DeviceProfile { + profile(stem, DevicePolicy::default()).expect("committed profile") +} + +/// A render pipeline of one color attachment, `pf`, written under `mask` and blended where +/// `blended` (adding the source to the destination). +fn pipeline_of(pf: PixelFormat, mask: ColorWriteMask, blended: bool) -> RenderLinkInputs { + let mut a = ColorAttachmentDescriptor::new(pf); + a.write_mask = mask; + if blended { + a.blending_enabled = true; + a.destination_rgb_blend_factor = metal::BlendFactor::One; + a.destination_alpha_blend_factor = metal::BlendFactor::One; + } + let mut r = RenderLinkInputs::new(); + r.color_attachments[0] = Some(a); + r +} + +fn render(r: &RenderLinkInputs) -> LinkInputs { + LinkInputs::Render(Box::new(r.clone())) +} + +/// The device's lack of a format as a color attachment (blended or not). +fn lacks_attachment(e: &Error) -> bool { + matches!(e, Error::Unsupported(u) if u.feature == Feature::Format && u.needs != Needs::NotImplemented) +} + +/// The fixture's `float4` and `half4` fills write each format's word through one `uint` on the +/// RTX 5080's profile and link with `R16_UINT` (the module docs). +#[test] +fn fragment_outputs_to_word_attachments_write_the_word() { + let Some(bc) = fixture() else { + return; + }; + let consts = FunctionConstantValues::defaults(); + let p = venue("nvidia-rtx5080-laptop"); + let v = compile(&bc, "rt6_fill_vertex", &p).expect("vertex"); + for pf in FORMATS.into_iter().chain(SRGB) { + let word = WordAttachment::of(pf, &p).expect("a word attachment on the 5080"); + let channels = [ + ColorWriteMask::RED, + ColorWriteMask::GREEN, + ColorWriteMask::BLUE, + ColorWriteMask::ALPHA, + ] + .into_iter() + .zip(word.fields()) + .filter(|(_, f)| f.is_some()) + .fold(ColorWriteMask::NONE, |m, (c, _)| m.union(c)); + for entry in ENTRIES { + for (mask, written) in [ + (ColorWriteMask::ALL, true), + (ColorWriteMask::NONE, false), + (ColorWriteMask::RED, true), + ] { + let what = format!("{entry} {pf:?} {mask:?}"); + let r = pipeline_of(pf, mask, false); + let inputs = fragment_inputs(&r, &p); + let f = + compile_with(&bc, entry, &p, &inputs).unwrap_or_else(|e| panic!("{what}: {e}")); + let linked = link(&[&v, &f], &render(&r), &p); + // Without the pipeline's fetch state, a mask of some of the format's channels is + // the device's lack of the format. + let kept = mask.intersection(channels); + if !kept.is_empty() && kept != channels { + assert!(inputs.word_colors.is_empty(), "{what}"); + let e = linked.expect_err(&what); + assert!(lacks_attachment(&e), "{what}: {e}"); + continue; + } + let l = linked.unwrap_or_else(|e| panic!("{what}: link: {e}")); + assert_eq!( + f.interface.io.word_colors, + BTreeMap::from([(0, word)]), + "{what}" + ); + assert!(f.interface.io.color_writes.is_empty(), "{what}"); + let color = f + .interface + .io + .outputs + .iter() + .find(|o| { + matches!( + o.role, + IoRole::Color { + attachment: 0, + index: 0 + } + ) + }) + .expect("color output"); + assert_eq!( + (color.ty.numeric, color.ty.components), + (IoNumeric::Float, 4), + "{what}" + ); + let plan = plan_bitcode( + &bc, + EntryRef::Name(entry), + &consts, + &p, + &inputs, + &mut meter(), + ) + .unwrap_or_else(|e| panic!("{what}: {e}")); + assert!( + plan.estimate.words >= f.module.words.len() as u64, + "{what}: estimate {} < emitted {}", + plan.estimate.words, + f.module.words.len() + ); + let g = l.graphics.as_ref().expect("graphics"); + let a = g.color_attachments[0].expect("attachment"); + assert_eq!(a.format, word.word_format(), "{what}"); + assert_eq!( + a.write_mask, + match written { + true => vk::ColorComponentFlags::R, + false => vk::ColorComponentFlags::empty(), + }, + "{what}" + ); + assert!(a.blend.is_none(), "{what}"); + let words: Vec> = [&*v, &*f] + .iter() + .map(|s| { + let w = relocate(s, &l.table).expect("relocate"); + check_words_valid(&w, &s.requirements, &p) + .unwrap_or_else(|e| panic!("{what}: L3: {e}")); + w + }) + .collect(); + let text = spirv_dis(&words[1]); + assert!( + text.contains("%_ptr_Output_uint = OpTypePointer Output %uint"), + "{what}\n{text}" + ); + } + } + } +} + +/// The device of committed profile `stem`. +fn device(stem: &str) -> Device { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/profiles") + .join(format!("{stem}.json")); + let text = std::fs::read_to_string(path).expect("profile"); + let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); + Device::new(desc, DevicePolicy::default()).expect("device") +} + +/// A word attachment written under a mask of some of its channels, or blended, takes the +/// interlocked storage form in the whole pipeline on the 5080's device, a blended one noting +/// `DeviceColorConversion` (the module docs). +#[test] +fn masked_and_blended_word_attachments_take_the_interlock() { + let Some(bc) = fixture() else { + return; + }; + let dev = device("nvidia-rtx5080-laptop"); + let library = Library::from_air(&bc).expect("library"); + let function = |name: &str| { + StageSource::Function(FunctionDescriptor::new( + library.function(name).expect("function"), + )) + }; + let note = PrecisionNote::DeviceColorConversion; + let mut checked = 0; + for pf in FORMATS { + for entry in ENTRIES { + for mask in [ + ColorWriteMask::RED | ColorWriteMask::GREEN, + ColorWriteMask::ALPHA, + ColorWriteMask::RED | ColorWriteMask::GREEN | ColorWriteMask::BLUE, + ColorWriteMask::ALL, + ] { + for blended in [false, true] { + if mask == ColorWriteMask::ALL && !blended { + continue; + } + let what = format!("{entry} {pf:?} {mask:?} blended {blended}"); + let mut d = RenderPipelineDescriptor::new(function("rt6_fill_vertex")); + d.fragment = Some(function(entry)); + d.color_attachments[0] = pipeline_of(pf, mask, blended).color_attachments[0]; + let pipe = dev + .compile_render_pipeline(&d, &Budget::standard()) + .unwrap_or_else(|e| panic!("{what}: {e}")); + let storage: Vec<_> = (pipe.graphics.storage_attachments.iter()) + .map(|u| (u.color_index, u.format, u.writes, u.view_alias)) + .collect(); + assert_eq!(storage, [(0, vk::Format::R16_UINT, true, None)], "{what}"); + let kept = vk::ColorComponentFlags::known_bits() + .difference(crate::metal::state::color_write_mask(mask).expect("mask")); + assert_eq!(pipe.graphics.storage_attachments[0].kept, kept, "{what}"); + assert!(pipe.graphics.color_attachments[0].is_none(), "{what}"); + let fragment = (pipe.stages.iter()) + .find(|s| s.stage == vk::ShaderStage::FRAGMENT) + .expect("a fragment stage"); + assert_eq!( + fragment.precision_notes.contains(¬e), + blended, + "{what}: {:?}", + fragment.precision_notes + ); + for s in &pipe.stages { + check_words_valid(&s.spirv, &pipe.requirements, dev.profile()) + .unwrap_or_else(|e| panic!("{what}: L3: {e}")); + } + checked += 1; + } + } + } + } + assert_eq!(checked, 28); +} + +/// An 8-bit sRGB word attachment written under a mask of some of its channels takes the +/// interlocked storage form in the whole pipeline on the 5080's device, without a note; blended, +/// it is the device's lack of the format (Metal's sRGB blend over the word is not built). +#[test] +fn srgb_word_attachments_merge_but_do_not_blend() { + let Some(bc) = fixture() else { + return; + }; + let dev = device("nvidia-rtx5080-laptop"); + let library = Library::from_air(&bc).expect("library"); + let function = |name: &str| { + StageSource::Function(FunctionDescriptor::new( + library.function(name).expect("function"), + )) + }; + for entry in ENTRIES { + for (pf, mask, blended) in [ + (PixelFormat::RG8UnormSRGB, ColorWriteMask::RED, false), + (PixelFormat::RG8UnormSRGB, ColorWriteMask::GREEN, false), + (PixelFormat::RG8UnormSRGB, ColorWriteMask::ALL, true), + (PixelFormat::R8UnormSRGB, ColorWriteMask::ALL, true), + ] { + let what = format!("{entry} {pf:?} {mask:?} blended {blended}"); + let mut d = RenderPipelineDescriptor::new(function("rt6_fill_vertex")); + d.fragment = Some(function(entry)); + d.color_attachments[0] = pipeline_of(pf, mask, blended).color_attachments[0]; + let made = dev.compile_render_pipeline(&d, &Budget::standard()); + if blended { + let e = made.expect_err(&what); + assert!(lacks_attachment(&e), "{what}: {e}"); + continue; + } + let pipe = made.unwrap_or_else(|e| panic!("{what}: {e}")); + let storage: Vec<_> = (pipe.graphics.storage_attachments.iter()) + .map(|u| (u.color_index, u.format, u.writes, u.view_alias)) + .collect(); + assert_eq!(storage, [(0, vk::Format::R16_UINT, true, None)], "{what}"); + assert!(pipe.graphics.color_attachments[0].is_none(), "{what}"); + for s in &pipe.stages { + assert!( + !s.precision_notes + .contains(&PrecisionNote::DeviceColorConversion), + "{what}: {:?}", + s.precision_notes + ); + check_words_valid(&s.spirv, &pipe.requirements, dev.profile()) + .unwrap_or_else(|e| panic!("{what}: L3: {e}")); + } + } + } +} + +/// On lavapipe's device an `RG8Unorm_sRGB` attachment written under a mask of some of its channels +/// keeps its color attachment of `R16_UINT`, written whole and unblended, and reads its input +/// attachment as `uint`s; its fragment, compiled under the pipeline's fetch state, states the merge +/// of the channels the mask leaves out and passes L3. Under a full mask the pipeline reads no input +/// attachment. A fragment compiled under another partial mask, or under the full one, does not +/// link into a pipeline of a partial mask (the module docs). +#[test] +fn srgb_word_attachments_merge_over_input_attachments() { + use crate::pipeline::facts::RuntimeFact; + use crate::pipeline::lower_inputs::FramebufferFetchInputs; + use crate::pipeline::sym::SampledType; + let Some(bc) = fixture() else { + return; + }; + let dev = device("lavapipe"); + let pf = PixelFormat::RG8UnormSRGB; + assert!(WordAttachment::of(pf, dev.profile()).is_some()); + let library = Library::from_air(&bc).expect("library"); + let function = |name: &str| { + StageSource::Function(FunctionDescriptor::new( + library.function(name).expect("function"), + )) + }; + let p = dev.profile(); + let v = compile(&bc, "rt6_fill_vertex", p).expect("vertex"); + // The fragment compiled for pipeline `r`, as the pipeline compile hands it the fetch state. + let fragment = |entry: &str, r: &RenderLinkInputs| { + let mut inputs = fragment_inputs(r, p); + inputs.framebuffer_fetch = Some(FramebufferFetchInputs::of( + [0], + &r.color_attachments, + false, + false, + 1, + )); + compile_with(&bc, entry, p, &inputs).expect("fragment") + }; + for entry in ENTRIES { + for (mask, kept) in [ + (ColorWriteMask::RED, vk::ColorComponentFlags::G), + (ColorWriteMask::GREEN, vk::ColorComponentFlags::R), + ( + ColorWriteMask::GREEN | ColorWriteMask::ALPHA, + vk::ColorComponentFlags::R, + ), + (ColorWriteMask::ALL, vk::ColorComponentFlags::empty()), + ] { + let what = format!("{entry} {mask:?}"); + let mut d = RenderPipelineDescriptor::new(function("rt6_fill_vertex")); + d.fragment = Some(function(entry)); + d.color_attachments[0] = pipeline_of(pf, mask, false).color_attachments[0]; + let pipe = dev + .compile_render_pipeline(&d, &Budget::standard()) + .unwrap_or_else(|e| panic!("{what}: {e}")); + let a = pipe.graphics.color_attachments[0].expect("a color attachment"); + assert_eq!( + (a.format, a.write_mask, a.blend), + (vk::Format::R16_UINT, vk::ColorComponentFlags::R, None), + "{what}" + ); + assert!(pipe.graphics.storage_attachments.is_empty(), "{what}"); + let inputs: Vec<_> = (pipe.graphics.input_attachments.iter()) + .map(|u| (u.color_index, u.input_attachment_index, u.format_class)) + .collect(); + let merged = !kept.is_empty(); + let want = match merged { + true => vec![(0, 0, SampledType::Uint)], + false => Vec::new(), + }; + assert_eq!(inputs, want, "{what}"); + for s in &pipe.stages { + check_words_valid(&s.spirv, &pipe.requirements, p) + .unwrap_or_else(|e| panic!("{what}: L3: {e}")); + } + let r = pipeline_of(pf, mask, false); + let f = fragment(entry, &r); + let stated: Vec<_> = (f.facts.iter()) + .filter(|f| matches!(f, RuntimeFact::WordInputMerge { .. })) + .copied() + .collect(); + let want = match merged { + true => vec![RuntimeFact::WordInputMerge { color: 0, kept }], + false => Vec::new(), + }; + assert_eq!(stated, want, "{what}"); + link(&[&v, &f], &render(&r), p).unwrap_or_else(|e| panic!("{what}: link: {e}")); + } + // Compiled under another mask, or the full one, for a pipeline of a partial mask. + let red = pipeline_of(pf, ColorWriteMask::RED, false); + for other in [ColorWriteMask::GREEN, ColorWriteMask::ALL] { + let f = fragment(entry, &pipeline_of(pf, other, false)); + let e = link(&[&v, &f], &render(&red), p).expect_err(entry); + assert!( + matches!(e, Error::NeedsInput(RuntimeInput::FramebufferFetch)), + "{entry} compiled under {other:?}: {e}" + ); + } + } +} + +/// An `RGB9E5Float` attachment on the 5080's device renders a `float` output through an +/// `R32_UINT` view, no storage form and no conversion note; a `half` output is `NotImplemented(Format)`, and +/// a mask of some of its channels, or a blend, the device's lack of the format (the module docs). +#[test] +fn an_rgb9e5_attachment_takes_a_float_outputs_word() { + let Some(bc) = fixture() else { + return; + }; + let dev = device("nvidia-rtx5080-laptop"); + let library = Library::from_air(&bc).expect("library"); + let function = |name: &str| { + StageSource::Function(FunctionDescriptor::new( + library.function(name).expect("function"), + )) + }; + let pf = PixelFormat::RGB9E5Float; + for entry in ENTRIES { + let half = entry == "rt6_fill_rgba16float"; + for (mask, blended) in [ + (ColorWriteMask::ALL, false), + ( + ColorWriteMask::RED | ColorWriteMask::GREEN | ColorWriteMask::BLUE, + false, + ), + (ColorWriteMask::RED, false), + (ColorWriteMask::ALL, true), + ] { + let what = format!("{entry} {mask:?} blended {blended}"); + let mut d = RenderPipelineDescriptor::new(function("rt6_fill_vertex")); + d.fragment = Some(function(entry)); + d.color_attachments[0] = pipeline_of(pf, mask, blended).color_attachments[0]; + let made = dev.compile_render_pipeline(&d, &Budget::standard()); + let whole = + mask.contains(ColorWriteMask::RED | ColorWriteMask::GREEN | ColorWriteMask::BLUE); + if blended || !whole { + let e = made.expect_err(&what); + assert!(lacks_attachment(&e), "{what}: {e}"); + continue; + } + if half { + let e = made.expect_err(&what); + assert!( + matches!(&e, Error::Unsupported(u) if u.feature == Feature::Format && u.needs == Needs::NotImplemented), + "{what}: {e}" + ); + continue; + } + let pipe = made.unwrap_or_else(|e| panic!("{what}: {e}")); + assert!(pipe.graphics.storage_attachments.is_empty(), "{what}"); + let a = pipe.graphics.color_attachments[0].expect("attachment"); + assert_eq!(a.format, vk::Format::R32_UINT, "{what}"); + assert_eq!(a.write_mask, vk::ColorComponentFlags::R, "{what}"); + assert!(a.blend.is_none(), "{what}"); + for s in &pipe.stages { + assert!( + !s.precision_notes + .contains(&PrecisionNote::DeviceColorConversion), + "{what}: {:?}", + s.precision_notes + ); + check_words_valid(&s.spirv, &pipe.requirements, dev.profile()) + .unwrap_or_else(|e| panic!("{what}: L3: {e}")); + } + } + } +} + +/// A blended word attachment compiled without the pipeline's fetch state is refused as the +/// device's lack of the format, and a fragment compiled without the pipeline's attachments does +/// not link; where the device renders the format, the attachment takes it (the module docs). +#[test] +fn word_attachments_refuse_blends_and_other_maps() { + let Some(bc) = fixture() else { + return; + }; + let nvidia = venue("nvidia-rtx5080-laptop"); + let lavapipe = venue("lavapipe"); + for pf in FORMATS { + for entry in ENTRIES { + let what = format!("{entry} {pf:?}"); + // Blended: no word view, and the device has no attachment of the format. + let v = compile(&bc, "rt6_fill_vertex", &nvidia).expect("vertex"); + let r = pipeline_of(pf, ColorWriteMask::ALL, true); + let inputs = fragment_inputs(&r, &nvidia); + assert!(inputs.word_colors.is_empty(), "{what}"); + let f = compile_with(&bc, entry, &nvidia, &inputs) + .unwrap_or_else(|e| panic!("{what}: {e}")); + let e = link(&[&v, &f], &render(&r), &nvidia).expect_err(&what); + assert!(lacks_attachment(&e), "{what}: blended: {e}"); + // Compiled without the pipeline's attachments. + let r = pipeline_of(pf, ColorWriteMask::ALL, false); + let f = compile_with(&bc, entry, &nvidia, &LowerInputs::new()) + .unwrap_or_else(|e| panic!("{what}: {e}")); + let e = link(&[&v, &f], &render(&r), &nvidia).expect_err(&what); + assert!( + matches!(e, Error::NeedsInput(RuntimeInput::ColorWrites)), + "{what}: another map: {e}" + ); + // A device that renders the format takes it. + let v = compile(&bc, "rt6_fill_vertex", &lavapipe).expect("vertex"); + let inputs = fragment_inputs(&r, &lavapipe); + assert!(inputs.word_colors.is_empty(), "{what}"); + let f = compile_with(&bc, entry, &lavapipe, &inputs) + .unwrap_or_else(|e| panic!("{what}: {e}")); + let l = link(&[&v, &f], &render(&r), &lavapipe) + .unwrap_or_else(|e| panic!("{what}: lavapipe: {e}")); + let a = l.graphics.as_ref().expect("graphics").color_attachments[0].expect("color"); + assert_eq!( + Some(a.format), + crate::metal::format::direct_format(pf), + "{what}" + ); + } + } +} diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index a2aee32d8..8245a3208 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -161,6 +161,7 @@ mod engine_vertex_fetch; mod engine_viewport_compensation; mod engine_volatile; mod engine_wide; +mod engine_word_attachments; mod engine_zeroed_colors; mod env_registry; mod fast_paths; diff --git a/crates/metal2vulkan/tests/air_input/wm_samples.txt b/crates/metal2vulkan/tests/air_input/wm_samples.txt new file mode 100644 index 000000000..9bca689fe --- /dev/null +++ b/crates/metal2vulkan/tests/air_input/wm_samples.txt @@ -0,0 +1,210 @@ +target triple = "air64_v28-apple-macosx26.0.0" +source_filename = "-" +; datalayout DataLayout { endian: Little, pointers: {0: PointerSpec { size_bits: 64, abi_bits: 64, pref_bits: 64, index_bits: 64 }}, ints: {1: AlignSpec { abi_bits: 8, pref_bits: 8 }, 8: AlignSpec { abi_bits: 8, pref_bits: 8 }, 16: AlignSpec { abi_bits: 16, pref_bits: 16 }, 32: AlignSpec { abi_bits: 32, pref_bits: 32 }, 64: AlignSpec { abi_bits: 64, pref_bits: 64 }}, floats: {16: AlignSpec { abi_bits: 16, pref_bits: 16 }, 32: AlignSpec { abi_bits: 32, pref_bits: 32 }, 64: AlignSpec { abi_bits: 64, pref_bits: 64 }, 128: AlignSpec { abi_bits: 128, pref_bits: 128 }}, vectors: {16: AlignSpec { abi_bits: 16, pref_bits: 16 }, 24: AlignSpec { abi_bits: 32, pref_bits: 32 }, 32: AlignSpec { abi_bits: 32, pref_bits: 32 }, 48: AlignSpec { abi_bits: 64, pref_bits: 64 }, 64: AlignSpec { abi_bits: 64, pref_bits: 64 }, 96: AlignSpec { abi_bits: 128, pref_bits: 128 }, 128: AlignSpec { abi_bits: 128, pref_bits: 128 }, 192: AlignSpec { abi_bits: 256, pref_bits: 256 }, 256: AlignSpec { abi_bits: 256, pref_bits: 256 }, 512: AlignSpec { abi_bits: 512, pref_bits: 512 }, 1024: AlignSpec { abi_bits: 1024, pref_bits: 1024 }}, aggregate: AlignSpec { abi_bits: 0, pref_bits: 64 }, native_ints: [8, 16, 32], stack_align_bits: None, alloca_space: 0, program_space: 0, globals_space: 0, mangling: None, fn_ptr_align: None, non_integral: [] } +%t3 = type <{ <4 x float> }> +%t5 = type %t3 (i32) +%t6 = type float (i32) +%t8 = type <4 x float> (<4 x float>, ptr addrspace(2)) +%t12 = type void (ptr addrspace(1), ptr addrspace(1), <2 x i32>) +%t13 = type ptr addrspace(2) () +%t15 = type { <4 x float>, i8 } +%t16 = type %t15 (ptr addrspace(1), ptr addrspace(2), <2 x i32>, i32, i32) +%t17 = type %t15 (ptr addrspace(1), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) +%t19 = type [2 x i32] +c12 = %t19 [27, 0] +c26 = <2 x float> [0x40000000, 0x40000000] +c27 = <2 x float> [0xBF800000, 0xBF800000] +c30 = <4 x i32> [0, 1, poison, poison] +c34 = <4 x float> [poison, poison, 0x0, 0x3F800000] +c35 = <4 x i32> [0, 1, 6, 7] + +define %t5 @f0 "wm_vertex" memory(NoModRef, NoModRef, NoModRef) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" { +bb0: + %i0 = shl i32 %a0, i32 1 + %i1 = and i32 %i0, i32 2 + %i2 = tail call reassoc nnan ninf nsz arcp contract afn float @f1 [air Convert(Convert { dst: NumTy { elem: F32, lanes: 1 }, dst_kind: Float, src: NumTy { elem: I32, lanes: 1 }, src_kind: Unsigned, src_fp8: None })](%i1) + %i3 = insertelement <2 x float> undef, %i2, i64 0 + %i4 = and i32 %a0, i32 2 + %i5 = tail call reassoc nnan ninf nsz arcp contract afn float @f1 [air Convert(Convert { dst: NumTy { elem: F32, lanes: 1 }, dst_kind: Float, src: NumTy { elem: I32, lanes: 1 }, src_kind: Unsigned, src_fp8: None })](%i4) + %i6 = insertelement %i3, %i5, i64 1 + %i7 = fmul reassoc nnan ninf nsz arcp contract afn <2 x float> %i6, <2 x float> c26 + %i8 = fadd reassoc nnan ninf nsz arcp contract afn <2 x float> %i7, <2 x float> c27 + %i9 = shufflevector <4 x float> %i8, <2 x float> poison, <0, 1, poison, poison> + %i10 = shufflevector <4 x float> %i9, <4 x float> c34, <0, 1, 6, 7> + %i11 = insertvalue %t3 undef %i10, 0 + ret %i11 +} + +declare %t6 @f1 "air.convert.f.f32.u.i32" memory(NoModRef, NoModRef, NoModRef) + +define %t5 @f2 "wm_half_vertex" memory(NoModRef, NoModRef, NoModRef) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" { +bb0: + %i0 = icmp eq %a0, i32 1 + %i1 = select reassoc nnan ninf nsz arcp contract afn float %i0, float 0x3F800000, float 0xBF800000 + %i2 = icmp eq %a0, i32 2 + %i3 = select reassoc nnan ninf nsz arcp contract afn float %i2, float 0x3F800000, float 0xBF800000 + %i4 = insertelement <4 x float> c34, %i1, i64 0 + %i5 = insertelement %i4, %i3, i64 1 + %i6 = insertvalue %t3 undef %i5, 0 + ret %i6 +} + +define %t8 @f3 "wm_fill" memory(NoModRef, NoModRef, NoModRef) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a1( Ref nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = load <4 x float>, %a1, align 16 + ret %i0 +} + +define %t12 @f4 "wm_read_samples" "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a1( Mod nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = extractelement %a2, i64 1 + %i1 = shl i32 %i0, i32 3 + %i2 = extractelement %a2, i64 0 + %i3 = add i32 %i1, %i2 + %i4 = shl i32 %i3, i32 2 + br bb2 +bb1: + ret void +bb2: + %i7 = phi i32 [i32 0, bb0], [%i15, bb2] + %i8 = tail call ptr addrspace(2) @f6 [air Sampler(GetReadSampler)]() + %i9 = tail call %t15 @f7 [air Texture(Texture { op: Read, image: ImageShape { dim: D2, array: false, ms: true, depth: false }, texel: Some(Texel { ty: NumTy { elem: F32, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(Read) })](%a0, %i8, %a2, %i7, i32 1) arg0( Ref nocapture ) + %i10 = extractvalue <4 x float> %i9, 0 + %i11 = add nuw nsw i32 %i7, %i4 + %i12 = zext %i11 to i64 + %i13 = getelementptr inbounds <4 x float>, %a1, %i12 + store %i10, %i13, align 16 + %i15 = add nuw nsw i32 %i7, i32 1 + %i16 = icmp eq %i15, i32 4 + br %i16, bb1, bb2, !llvm.loop LoopHints { unroll: Default, must_progress: true } +} + +define %t12 @f5 "wm_read" "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins"="" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" %a0( Ref nocapture ) %a1( Mod nocapture "air-buffer-no-alias"="" ) { +bb0: + %i0 = tail call ptr addrspace(2) @f6 [air Sampler(GetReadSampler)]() + %i1 = tail call %t15 @f8 [air Texture(Texture { op: Read, image: ImageShape { dim: D2, array: false, ms: false, depth: false }, texel: Some(Texel { ty: NumTy { elem: F32, lanes: 4 }, sign: None }), coord16: false, form: Current, access: Some(Read) })](%a0, %i0, %a2, <2 x i32> zeroinitializer, i32 0, i32 1) arg0( Ref nocapture ) + %i2 = extractvalue <4 x float> %i1, 0 + %i3 = extractelement %a2, i64 1 + %i4 = shl i32 %i3, i32 3 + %i5 = extractelement %a2, i64 0 + %i6 = add i32 %i4, %i5 + %i7 = zext %i6 to i64 + %i8 = getelementptr inbounds <4 x float>, %a1, %i7 + store %i2, %i8, align 16 + ret void +} + +declare %t13 @f6 "air.get_read_sampler" memory(NoModRef, Ref, NoModRef) + +declare %t16 @f7 "air.read_texture_2d_ms.v4f32" memory(Ref, NoModRef, NoModRef) %a0( Ref nocapture ) + +declare %t17 @f8 "air.read_texture_2d.v4f32" memory(Ref, NoModRef, NoModRef) %a0( Ref nocapture ) +!md0 = !"SDK Version" +!md1 = !"wchar_size" +!md2 = !"frame-pointer" +!md3 = !"air.max_device_buffers" +!md4 = !"air.max_constant_buffers" +!md5 = !"air.max_threadgroup_buffers" +!md6 = !"air.max_textures" +!md7 = !"air.max_read_write_textures" +!md8 = !"air.max_samplers" +!md9 = !"air.position" +!md10 = !"air.arg_type_name" +!md11 = !"float4" +!md12 = !"air.arg_name" +!md13 = !"position" +!md14 = !"air.vertex_id" +!md15 = !"uint" +!md16 = !"id" +!md17 = !"air.render_target" +!md18 = !"air.center" +!md19 = !"air.no_perspective" +!md20 = !"air.arg_unused" +!md21 = !"air.buffer" +!md22 = !"air.location_index" +!md23 = !"air.read" +!md24 = !"air.address_space" +!md25 = !"air.arg_type_size" +!md26 = !"air.arg_type_align_size" +!md27 = !"color" +!md28 = !"air.texture" +!md29 = !"texture2d_ms" +!md30 = !"t" +!md31 = !"air.read_write" +!md32 = !"out" +!md33 = !"air.thread_position_in_grid" +!md34 = !"uint2" +!md35 = !"g" +!md36 = !"texture2d" +!md37 = !"air.compile.denorms_disable" +!md38 = !"air.compile.fast_math_enable" +!md39 = !"air.compile.framebuffer_fetch_enable" +!md40 = !"Apple metal version 32023.921 (metalfe-32023.921.6)" +!md41 = !"Metal" +!md42 = !"omnipotent char" +!md43 = !"Simple C++ TBAA" +!md44 = !"air-alias-scope-arg(1)" +!md45 = !"air-alias-scope-textures" +!md46 = i32 2 +!md47 = %t19 c12 +!md48 = i32 1 +!md49 = i32 4 +!md50 = i32 7 +!md51 = i32 31 +!md52 = i32 128 +!md53 = i32 8 +!md54 = i32 16 +!md55 = ptr addrspace(0) @f0 +!md56 = i32 0 +!md57 = ptr addrspace(0) @f2 +!md58 = ptr addrspace(0) @f3 +!md59 = ptr addrspace(0) @f4 +!md60 = ptr addrspace(0) @f5 +!md61 = i64 0 +!md62 = !{!md46, !md0, !md47} +!md63 = !{!md48, !md1, !md49} +!md64 = !{!md50, !md2, !md46} +!md65 = !{!md50, !md3, !md51} +!md66 = !{!md50, !md4, !md51} +!md67 = !{!md50, !md5, !md51} +!md68 = !{!md50, !md6, !md52} +!md69 = !{!md50, !md7, !md53} +!md70 = !{!md50, !md8, !md54} +!md71 = !{!md9, !md10, !md11, !md12, !md13} +!md72 = !{!md71} +!md73 = !{!md56, !md14, !md10, !md15, !md12, !md16} +!md74 = !{!md73} +!md75 = !{!md55, !md72, !md74} +!md76 = !{!md57, !md72, !md74} +!md77 = !{!md17, !md56, !md56, !md10, !md11} +!md78 = !{!md77} +!md79 = !{!md56, !md9, !md18, !md19, !md10, !md11, !md12, !md13, !md20} +!md80 = !{!md48, !md21, !md22, !md56, !md48, !md23, !md24, !md46, !md25, !md54, !md26, !md54, !md10, !md11, !md12, !md27} +!md81 = !{!md79, !md80} +!md82 = !{!md58, !md78, !md81} +!md83 = !{} +!md84 = !{!md56, !md28, !md22, !md56, !md48, !md23, !md10, !md29, !md12, !md30} +!md85 = !{!md48, !md21, !md22, !md48, !md48, !md31, !md24, !md48, !md25, !md54, !md26, !md54, !md10, !md11, !md12, !md32} +!md86 = !{!md46, !md33, !md10, !md34, !md12, !md35} +!md87 = !{!md84, !md85, !md86} +!md88 = !{!md59, !md83, !md87} +!md89 = !{!md56, !md28, !md22, !md56, !md48, !md23, !md10, !md36, !md12, !md30} +!md90 = !{!md89, !md85, !md86} +!md91 = !{!md60, !md83, !md90} +!md92 = !{!md37} +!md93 = !{!md38} +!md94 = !{!md39} +!md95 = !{!md40} +!md96 = !{!md46, !md53, !md56} +!md97 = !{!md41, !md49, !md56, !md56} +!md98 = !{!md43} +!md99 = !{!md42, !md98, !md61} +!md100 = !{!md99, !md99, !md61} +!"llvm.module.flags" = !{!md62, !md63, !md64, !md65, !md66, !md67, !md68, !md69, !md70} +!"air.vertex" = !{!md75, !md76} +!"air.fragment" = !{!md82} +!"air.kernel" = !{!md88, !md91} +!"air.compile_options" = !{!md92, !md93, !md94} +!"llvm.ident" = !{!md95} +!"air.version" = !{!md96} +!"air.language_version" = !{!md97} diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 498b2863a..49c05b2c7 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -822,6 +822,8 @@ surface! { struct FormatMapping N; enum FormatEmulation N; enum ExtendedRange N; + enum WordAttachment N; + struct WordField E; enum ClearRoute N; fn vk_format; fn swizzle_over; diff --git a/docs/API.md b/docs/API.md index 0d8841226..3e1f9b9a7 100644 --- a/docs/API.md +++ b/docs/API.md @@ -356,6 +356,36 @@ Where Metal's rules differ from Vulkan's, the pipeline gives Metal's answer: outputs at one attachment are `InvalidDescriptor(DuplicateColorOutput)`. - On a device without `independentBlend`, attachments the function does not write copy the blend state of those it does; where those differ the pipeline is refused, naming the feature. +- A packed 16-bit attachment (`A1BGR5Unorm`, `ABGR4Unorm`) of a format the device samples but does + not render (the RTX 5080) renders through an `R16_UINT` view of its texture + (`metal::format::WordAttachment`, `LoweringInputs::word_colors`): the fragment function writes + the word Metal stores and `graphics` gives the attachment that format; a pass clears it to the + word of Metal's clear. Exact, for a write unblended (or blended one and zero); under a mask of + some of its channels the function merges the word into the texel in the interlocked storage + form (a `GraphicsState::storage_attachments` entry of `R16_UINT`) where the device orders fetch + through the pixel interlock. Blended otherwise, there too the function computes Metal's blend of + a `half4` or `float4` output over the word it reads, within one code of Metal's + (`PrecisionNote::DeviceColorConversion`: the attachment holds codes where Metal's tile holds a + clear's or an earlier blend's result in the pass as a `half`, and under fast math Metal sums a + few states otherwise; `docs/FAST-PATHS.md`). A blend of the second source, and a blend or + partial mask on a device without the interlock, is refused as the device lacking the format; a + color input or resolve of one, and a blend of an output of fewer lanes, is `NotImplemented`. +- An 8-bit sRGB attachment of one or two channels (`R8Unorm_sRGB`, `RG8Unorm_sRGB`) the device + does not render (the RTX 5080: it renders neither `R8_SRGB` nor `R8G8_SRGB`, and holds the + latter in its UNORM twin) renders through an `R8_UINT` or `R16_UINT` view of its texture the + same way: the fragment function writes Metal's bytes (its twelve-bit encode), a pass clears it + to the bytes of Metal's clear, and a partial mask merges the word in the interlock, or over the + attachment's input attachment on a device that orders fetch through rasterization-order input + attachments (lavapipe; `RuntimeFact::WordInputMerge`). Exact. A blend of one + other than one and zero is refused as the device lacking the format; a color input or resolve + of one is `NotImplemented(Format)`. +- An `RGB9E5Float` attachment the device does not render (the RTX 5080) renders through an + `R32_UINT` view of its texture: the fragment function writes Metal's word of a `float` output + (each channel clamped to `[0, 65408]`, a NaN 0, the exponent of the largest, every mantissa + truncated), and a pass clears it to the word of Metal's clear. Exact. A `half` output to one + is `NotImplemented(Format)` (Metal rounds the `float` the `half` was converted from, half up); + a blend, or a mask of some of its channels, is refused as the device lacking the format; a + color input or resolve of one is `NotImplemented(Format)`. - A fragment function that reads a color attachment (framebuffer fetch) reads it in an ordered form wherever the device has one: rasterization-order attachment access, or the interlocked storage form, which binds the attachment as a storage image viewed in @@ -1589,6 +1619,11 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. pass would change. Not on a driver whose pass stores the codes as Metal's (`DriverFact::TileStoreIsMetals`: MoltenVK on Apple's GPUs, whose pass is a Metal pass), nor under `TileStorePolicy::Exact` for an attachment the load pass rewrites as Metal's store leaves it. +- `metal2vulkan-degrade-shared-exponent-kept` (precision). `SharedExponentKept`: A draw in a render + pass that loads a single-sampled `RGB9E5Float` color attachment and does not discard it at the + store. Cost: the texels the pass's draws do not write keep their words; Metal's pass normalizes a + word whose largest mantissa is below 256 (its exponent above 0) in each tile a draw reaches: a + texel whose bytes no Metal write left (uploaded or copied words) keeps a word Metal's pass would change, of the same value. Not on a driver whose pass stores the words as Metal's (`DriverFact::TileStoreIsMetals`), nor under `TileStorePolicy::Exact` for an attachment the load pass rewrites as Metal's store leaves it. diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 713a0592c..276002887 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -43,6 +43,7 @@ a cell that names another source took its numbers there. | A fragment function without fast math returns a `half` color to a blended attachment: the device blends in its own arithmetic and rounds once, where Metal blends a 16-bit float attachment in `half` arithmetic (each factor, product and sum rounded to `half`). | `half_blend = HalfBlendPolicy::Device` | `half_blend = HalfBlendPolicy::Exact`: the function computes Metal's blend in the interlocked storage form, for a `half` output of one to four lanes into `R16Float`, `RG16Float` or `RGBA16Float` where that form is exact for the pipeline (RADV, ANV, NVIDIA, MoltenVK); elsewhere, and for lavapipe, 32-bit float, 8-bit, a module naming no math mode or a blend of the second source, the device's blend and its note stay | 2.5 `half` ulps at the largest operand on NVIDIA (the blend color and one minus it), two on RADV, ANV and lavapipe (16-bit float); two `float` ulps (32-bit float, one on NVIDIA); one or two codes (8-bit, extended range); MoltenVK stores Metal's bytes. Measured with and without the factors' magnitudes at 0bcc0163e5. `HalfOutputPrecision` (`half-output-precision`) | A probe at 924fc11603 (a `half4` over a 1920x1080 `RGBA16Float` target, One / OneMinusSourceAlpha): making 11.1 → 24.0 ms; GPU 25 → 82 us one draw, 506 → 2291 us 32 overlapping draws (the interlock orders them). RTX 3090 (the same draw at 50a065eb98): making 12.9 → 27.4 ms; GPU 45 → 115 us one draw, 648 → 3268 us 32 overlapping draws | | A texture over a buffer whose rows (or an array's slices) lie with bytes between them, and which only reads (its usage, as Metal reports it, holds no `RenderTarget`, `ShaderWrite`, `ShaderAtomic` or block writes; `Unknown` holds them all), is an image over the buffer's bytes at Metal's row pitch, as one of packed rows is: the driver's own linear image, a `DRM_FORMAT_MOD_LINEAR` image at that pitch, or one over a dma-buf of the pages. Its subresources hold the bytes between its rows, which Metal never writes, and its first move reaches them. The runtime's choice: no pipeline differs. | `padded_reads = PaddedReadsPolicy::Alias` | `padded_reads = PaddedReadsPolicy::Shadow`: the runtime's shadow image of the texels, copied in from the buffer before each use (`shadowed-texture`), whose copies address the texels alone | The host keeps the bytes the image is bound to, the bytes between the rows among them, across its first move (the known gap below): a CPU write to them within one submission's round trip of the commit that makes the move is undone, once per image, unannounced, where Metal keeps it; no byte outside them is touched. `runtime_lane::pitched_surfaces::a_texture_that_only_reads_keeps_every_byte_of_its_pages` fails on a device whose move changes one past the keep | ANV (Iris Xe; `surface_texture_costs::read_only_padded_costs`), a frame sampling four `BGRA8Unorm` tiles over no-copy pages: textures made once, aliases and shadows about level (3.0-6.1 against 3.2-5.3 ms); a new texture over the pages each frame, aliases 4.6-8.6 ms (their first moves kept on the host) against shadows 3.4-7.1 ms | | A computed `half` or `float` color blended into an extended-range attachment (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`) rounds the blend's source as a loaded one; Metal's compiler rounds it by how it computed it. Every device. | The in-shader blend's loaded rounding (no switch) | **Not built yet:** Metal's rounding per shape is probed, not modelled | One code. `ExtendedRangeBlendSource` (`extended-range-blend-source`), `ExtendedRangeFloatBlendSource` (`extended-range-float-blend-source`) | Not measured | +| A blend into a packed 16-bit attachment the device renders through its word view (`A1BGR5Unorm`, `ABGR4Unorm` on the RTX 5080; `WordAttachment`), which the function computes in the interlocked storage form, reads the attachment's codes, where Metal's tile holds the pass's clear and each earlier blend's result as a `half`, finer; under fast math it also sums a few states otherwise than Metal. Every device rendering such an attachment. | The in-shader blend over the codes (no switch) | **Not built yet:** the extended-range attachments' `half` shadow (`render/extended_shadow.rs`, `VariantKey::extended_shadows`) taken by word attachments: the runtime's shadow start and end, its load of the codes and the clear's halves, and the word's shadowed variant in `lower::fragment::fetch`, for a single-sampled pass (a multisampled one keeps the codes, as an extended-range one does). Fast math's regrouped sums have no model | One code: without fast math exact over a loaded attachment (the 2,891 states of the M3 sweep, every channel), under fast math 3,527 of 94,732,288 channels a code apart; after a clear or an earlier blend in the pass, a code apart where the two readings store different codes. `DeviceColorConversion` (`device-color-conversion`) | Not measured. Expected from the shadow's form: an `R16G16B16A16_SFLOAT` image of the pass's extent per such color (8 bytes a pixel, 16.6 MB at 1920x1080), set at the draw it starts by a fill or a load dispatch, and an 8-byte storage read and write per blended fragment inside the interlock beside the word's | | A bicubic sample of an 8- or 16-bit normalized texture sums its taps exactly and rounds half up; Metal truncates its row terms, row sums and column terms first. Every device. | The exact sum (no switch) | **Not built yet:** Metal's datapath is pinned (17.75M lanes measured, no miss); its emitter is not written | One grid step (1/4080 at 8 bits) within about 2^-21 of a tie. `BicubicFilterArithmetic` (`bicubic-filter-arithmetic`) | Not measured (Metal's form is expected no larger) | | A bicubic sample of an extended-range texture (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10` and their sRGB twins) sums its taps' steps exactly, rounds half up and clamps into the format's decoded endpoints; within 0.014 of a grid step of a rounding tie Metal may round the other way. Every device. | The exact sum (no switch) | **None known:** no model of Metal's datapath tried fits; 3,317,760 lanes measured on the M3 Max (macOS 26.7) | One grid step (1/8160 a color lane, 1/8192 an sRGB color lane, 1/4080 alpha), 4,050 of the lanes measured, each within 0.014 of a step of a tie. `BicubicFilterArithmetic` (`bicubic-filter-arithmetic`) | No accurate form | | A texture of an ASTC LDR format on a device without that ASTC format reads a decoded twin of 8-bit codes, each channel the code nearest Metal's 12-bit value (`C >> 4` over 4095). (An sRGB form's twin holds Metal's own 8-bit codes under either value, which its slots decode through Metal's table: exact.) A texture of an EAC 11-bit format (`R11`, `RG11`, unsigned and signed) on a device without ETC2 reads one of 16-bit normalized codes, each nearest Metal's value (`c / 2047`, signed `c / 1023`). The runtime's choice: no pipeline differs. | `decoded_texels = DecodedTexelsPolicy::Compact` | `decoded_texels = DecodedTexelsPolicy::Exact`: Metal's values in an `R32G32B32A32_SFLOAT` twin (an EAC 11-bit one's in `R32_SFLOAT` or `R32G32_SFLOAT`) | Within 1/510 of Metal's value. An EAC 11-bit channel within half a 16-bit step (1/131070, signed 1/65534). `decoded-texel-precision`, announced where such a texture is made; `runtime_lane::astc_textures`, `runtime_lane::etc_textures` | The twin's memory, 16 bytes a texel against 4 (a 2048 x 2048 texture's chain: 85 MiB against 21 MiB), and as much again for a second twin once the texture is viewed in its other colour space; an EAC 11-bit twin's 4 bytes a channel against 2. The CPU decode of that chain of 8 x 8 blocks on one core of the Iris Xe host: 79 ms against 68 ms. Sampling not measured | @@ -184,6 +185,23 @@ driver's. Each is open work. the function does not know the bound sampler's filter, and a variant keyed on a nearest sampler's word is not built. Under `SamplingPolicy::Exact` a sample the linear emulation takes (not a cube's) reads the code through the slot's raw view there and decodes it exactly. +- **A fetched or resolved packed 16-bit attachment on a device that does not render the format** + (`A1BGR5Unorm`, `ABGR4Unorm` on the RTX 5080). Its word view (`WordAttachment`) takes writes + (blended and partly masked ones through the pixel interlock, the row above); a color input or + resolve is `NotImplemented(Format)`, a blend of an output of fewer than four lanes + `NotImplemented`, and a blend of the second source, or a blend or partial mask on a device + without the interlock, is refused as the device lacking the format. +- **A blended, fetched or resolved one- or two-channel 8-bit sRGB attachment on a device that + does not render the format** (`R8Unorm_sRGB`, `RG8Unorm_sRGB` on the RTX 5080). Its word view + takes writes (partly masked ones through the pixel interlock, or over the attachment's input + attachment on a device that orders fetch through them, lavapipe); a blend other than one and zero + is refused as the device lacking the format, and a color input or resolve is + `NotImplemented(Format)`. +- **A half output, blend, partial mask, color input or resolve of an `RGB9E5Float` attachment on + a device that does not render the format** (the RTX 5080). Its word view takes a `float` + output's writes and clears; a `half` output, a color input and a resolve are + `NotImplemented(Format)`, and a blend or a mask of some of its channels is refused as the + device lacking the format. - **ASTC textures on a device without ASTC.** A heap's or a sparse heap's such texture (`RuntimeGap::DecodedHeapTexture`) and a view of another decode (its HDR form) are refused. - **PVRTC textures on a device without PVRTC.** One without a decoded twin (a sparse heap's, or a