diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 3726b9395..9e946b6a0 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1273,6 +1273,7 @@ codec_enum! { PrivateList, YCbCrInPlace { slot, samplers, device }, PartialObjectThreadgroups, + RotatedInputBlend { color, blend, kept }, } UniformViewChoice { Viewed, Spare, Kept } Mechanism { diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index b2d74e978..d220e6683 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 1984; +pub const SEMANTICS_VERSION: u32 = 1985; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 1984; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 490; +pub const ARTIFACT_FORMAT_VERSION: u32 = 491; /// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding /// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index d902f4143..d28b5a12f 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -230,6 +230,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 gives the rotated attachment no Vulkan blend and its input attachment, which the + // consumer binds as `GraphicsState::input_attachments` states. + RuntimeFact::RotatedInputBlend { .. } => 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, diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 32202de25..97f3dfef5 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -209,6 +209,18 @@ fn every_fact() -> Vec { }, kept: crate::vk::ColorComponentFlags::empty(), }, + RuntimeFact::RotatedInputBlend { + color: 0, + blend: { + let mut c = crate::pipeline::ColorAttachmentDescriptor::new( + crate::metal::PixelFormat::ARGB8Unorm, + ); + c.blending_enabled = true; + c.destination_rgb_blend_factor = crate::metal::BlendFactor::DestinationAlpha; + crate::pipeline::lower_inputs::BlendEquation::of(&c).expect("a blend") + }, + kept: crate::vk::ColorComponentFlags::empty(), + }, RuntimeFact::WordInputMerge { color: 1, kept: crate::vk::ColorComponentFlags::G, @@ -357,6 +369,7 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::MeshLastFirst => 71, RuntimeFact::YCbCrInPlace { .. } => 65, RuntimeFact::PartialObjectThreadgroups => 89, + RuntimeFact::RotatedInputBlend { .. } => 90, } } @@ -364,7 +377,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..90).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..91).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -482,6 +495,7 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::ShaderStencilTest { .. } | RuntimeFact::TileImageblock { .. } | RuntimeFact::ExtendedRangeInputBlend { .. } + | RuntimeFact::RotatedInputBlend { .. } | RuntimeFact::WordInputMerge { .. } => Mechanism::RenderPassContract, RuntimeFact::ExecutionStatus => match f.buffer_access { crate::device::profile::BufferAccess::Addressed => Mechanism::PushConstant, diff --git a/crates/metal2vulkan/src/lower/arith/extended_range/blend.rs b/crates/metal2vulkan/src/lower/arith/extended_range/blend.rs index e0efaa889..3730412d3 100644 --- a/crates/metal2vulkan/src/lower/arith/extended_range/blend.rs +++ b/crates/metal2vulkan/src/lower/arith/extended_range/blend.rs @@ -1209,7 +1209,8 @@ impl Blend { use BlendFactor as F; let has_alpha = match pf { PixelFormat::R8Unorm | PixelFormat::RG8Unorm => false, - PixelFormat::RGBA8Unorm | PixelFormat::BGRA8Unorm => true, + // `ARGB8Unorm` blends as `RGBA8Unorm`, its channels rotated (`fetch::unorm8_format`). + PixelFormat::RGBA8Unorm | PixelFormat::BGRA8Unorm | PixelFormat::ARGB8Unorm => true, _ => return Err(Unsupported::not_implemented(Feature::FramebufferFetch).into()), }; let factors = [ diff --git a/crates/metal2vulkan/src/lower/fragment/color.rs b/crates/metal2vulkan/src/lower/fragment/color.rs index 640d505dd..c144e2228 100644 --- a/crates/metal2vulkan/src/lower/fragment/color.rs +++ b/crates/metal2vulkan/src/lower/fragment/color.rs @@ -194,7 +194,13 @@ pub(super) fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result, &BTreeMap, ), + rotated: &BTreeMap, multisampled: bool, ) -> BResult> { let mut out = BTreeMap::new(); @@ -376,6 +385,13 @@ pub(super) fn declare( e.insert(input_attachment(mb, color, false, multisampled)?); } } + // An attachment held with its channels rotated, whose 8-bit unorm texels its blend reads as + // `float`s. + for (&color, _) in rotated.iter().filter(|(_, rb)| rb.reads()) { + if let std::collections::btree_map::Entry::Vacant(e) = out.entry(color) { + e.insert(input_attachment(mb, color, true, multisampled)?); + } + } Ok(out) } diff --git a/crates/metal2vulkan/src/lower/fragment/fetch.rs b/crates/metal2vulkan/src/lower/fragment/fetch.rs index 442684510..76360d795 100644 --- a/crates/metal2vulkan/src/lower/fragment/fetch.rs +++ b/crates/metal2vulkan/src/lower/fragment/fetch.rs @@ -69,7 +69,11 @@ //! to Metal's `(0, 0, 0, r)` and every one written to it holding Metal's alpha in red //! ([`metal_order`], [`image_order`]), so a read, a merge of the channels a write mask keeps //! (in Metal's channels, of which only alpha is stored) and the per-sample forms are Metal's -//! (probe `a8`'s uses on an M3 Max under macOS 27.0.1); an +//! (probe `a8`'s uses on an M3 Max under macOS 27.0.1); an `ARGB8Unorm` attachment through its +//! `R8G8B8A8_UNORM` image, whose red, green, blue and alpha hold Metal's alpha, red, green and +//! blue (`StorageView::rotated`), every texel read from it rotated into Metal's order and every +//! one written to it out of it ([`metal_order`], [`image_order`]), blended as `RGBA8Unorm` +//! (below; Metal stores the format as `RGBA8Unorm` with its channels rotated); an //! 8-bit sRGB format the device renders (`R8Unorm_sRGB`, `RG8Unorm_sRGB`, `RGBA8Unorm_sRGB`, //! `BGRA8Unorm_sRGB`) through a view of the attachment in the unsigned integer format of its //! texel (`R8_UINT`, `R16_UINT`, `R32_UINT`; `StorageView::uint_view`), whose bytes the function @@ -241,7 +245,8 @@ //! storage form (`VariantKey::interlocked_colors`) and its blend is exact; elsewhere the variant //! is refused and the render pass splits around the draw, whose blend is the device's. //! -//! **An 8-bit unorm attachment's blend** (`R8Unorm`, `RG8Unorm`, `RGBA8Unorm`, `BGRA8Unorm`) of a +//! **An 8-bit unorm attachment's blend** (`R8Unorm`, `RG8Unorm`, `RGBA8Unorm`, `BGRA8Unorm`, and +//! `ARGB8Unorm` as `RGBA8Unorm` in Metal's channel order) of a //! `half4` or `float4` output the shader computes as Metal does ([`unorm8_blended`]): the write //! reads the texel at the pixel inside the interlock in Metal's channel order, clamps the output to //! `[0, 1]` (a NaN to 0), reads each code `c` as `h(c / 255)` (`f(c / 255)` for a `float4` output) @@ -261,7 +266,12 @@ //! value), so the blend is Metal's wherever the module states its math (`HalfOutputPrecision` for //! one naming none). A format without alpha's fast-math lerp, common factor or contracted pair //! (Metal sums those in forms of their own) and an output of fewer lanes take the generic blend -//! (below), as do a factor of the second source and a second (index 1) output. +//! (below), as do a factor of the second source and a second (index 1) output. An `ARGB8Unorm` +//! attachment whose blend no Vulkan state on its image gives (`color_writes::shader_rotated_blend`) +//! takes this form whether or not the function reads it, as the device blends it in no other: the +//! pipeline's state names it (`LoweringInputs::framebuffer_fetch`): Metal's blend where the module +//! states its math, else the same arithmetic, noted as a module stating none is +//! (`output_precision::half_output_note`). //! //! **A 32-bit float attachment's blend** (`R32Float`, `RG32Float`, `RGBA32Float`) takes the generic //! blend below where the function reads the attachment. Every device the translation targets blends @@ -382,11 +392,16 @@ pub(crate) fn half_float_format(pf: crate::metal::PixelFormat) -> bool { matches!(pf, P::R16Float | P::RG16Float | P::RGBA16Float) } -/// Whether `pf` is an 8-bit unorm color format held directly, whose blend Metal computes in the -/// arithmetic of the output's type over the clamped output ([`extended_range::Blend::unorm8`]). +/// Whether `pf` is an 8-bit unorm color format, whose blend Metal computes in the arithmetic of +/// the output's type over the clamped output ([`extended_range::Blend::unorm8`]): one held +/// directly, or `ARGB8Unorm`, which Metal blends as `RGBA8Unorm` with its channels rotated and +/// whose image the function reads and writes in Metal's order ([`StorageView::rotated`]). pub(crate) fn unorm8_format(pf: crate::metal::PixelFormat) -> bool { use crate::metal::PixelFormat as P; - matches!(pf, P::R8Unorm | P::RG8Unorm | P::RGBA8Unorm | P::BGRA8Unorm) + matches!( + pf, + P::R8Unorm | P::RG8Unorm | P::RGBA8Unorm | P::BGRA8Unorm | P::ARGB8Unorm + ) } /// Whether `pf` is an 8-bit sRGB color format, whose blend Metal computes as its unorm twin's over @@ -784,6 +799,11 @@ pub struct StorageView { /// `R8_UNORM`'s, a texel read from the image, `(r, 0, 0, 1)`, is Metal's `(0, 0, 0, r)`, and a /// texel written to it holds Metal's alpha in red ([`metal_order`], [`image_order`]). pub alpha_in_red: bool, + /// The attachment's image holds Metal's channels rotated (`ARGB8Unorm` in `R8G8B8A8_UNORM`, + /// `metal::format::FormatEmulation::RotatedView`): its red, green, blue and alpha are Metal's + /// alpha, red, green and blue, so a texel read from the image is rotated into Metal's order and + /// one written to it out of it ([`metal_order`], [`image_order`]). + pub rotated: bool, } impl StorageView { @@ -1122,11 +1142,14 @@ pub(crate) fn storage_form( let alpha_in_red = emulation == FormatEmulation::AlphaInRed && crate::metal::format::alpha_in_red(pf, p) && word.is_none(); + // An `ARGB8Unorm` attachment is read and written through its `R8G8B8A8_UNORM` image, the + // function rotating Metal's channels into and out of the image's. + let rotated = emulation == FormatEmulation::RotatedView; // An unblended write of every channel stores Metal's write of the output. A padded 10-bit // attachment's tile value and blends are not measured: no storage form. let not_modelled = inputs.amplified || extended.is_some_and(ExtendedRange::padded) - || (emulation != FormatEmulation::Direct && extended.is_none() && !alpha_in_red) + || (emulation != FormatEmulation::Direct && extended.is_none() && !alpha_in_red && !rotated) || (extended.is_some() && stores && !shader_blends && attachment.blending_enabled) || (srgb && uint_view.is_none()) // An `RGB9E5Float` word's mantissas share its exponent: no field is kept apart. @@ -1229,6 +1252,7 @@ pub(crate) fn storage_form( rgba_view, word, alpha_in_red, + rotated, })), _ => { // A BGRA-order format no declaration reaches, whose RGBA-order twin lacks something @@ -1713,6 +1737,15 @@ pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> { sixteen_exact = false; Ok((view, None)) } + // A blend into an attachment held with its channels rotated + // (`StorageView::rotated`), which no Vulkan state on its image may give + // (`color_writes::shader_rotated_blend`): Metal's 8-bit unorm blend wherever + // the module states its math, else a near-equivalent the function notes, + // taken whether or not the function reads the attachment. + (Some(Ok(_)), Some((_, 4))) if view.rotated => { + sixteen_exact = cx.entry.compile.fast_math.is_some(); + 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 @@ -2484,27 +2517,33 @@ fn read_texel( } /// Texel `texel` of storage-form attachment `sc`'s image, in Metal's channel order: an attachment -/// viewed in its RGBA-order twin ([`StorageView::rgba_view`]) has red and blue exchanged, and one +/// viewed in its RGBA-order twin ([`StorageView::rgba_view`]) has red and blue exchanged, one /// whose image holds Metal's alpha in red ([`StorageView::alpha_in_red`]) reads `(r, 0, 0, 1)` as -/// Metal's `(0, 0, 0, r)`; any other is as it is. Every texel read from the attachment's image -/// goes through here ([`read_texel`]), and every one written to it through [`image_order`]. +/// Metal's `(0, 0, 0, r)`, and one holding Metal's channels rotated ([`StorageView::rotated`]) +/// reads Metal's red, green, blue and alpha from the image's green, blue, alpha and red; any other +/// is as it is. Every texel read from the attachment's image goes through here ([`read_texel`]), +/// and every one written to it through [`image_order`]. fn metal_order(fb: &mut FunctionBuilder<'_>, sc: &StorageColor, texel: SValue) -> BResult { - match (sc.view.rgba_view, sc.view.alpha_in_red) { - (Some(_), _) => fb.vector_shuffle(texel, texel, &[2, 1, 0, 3]), - (None, true) => super::color::alpha_in_red(fb, texel), - (None, false) => Ok(texel), + match (sc.view.rgba_view, sc.view.alpha_in_red, sc.view.rotated) { + (Some(_), _, _) => fb.vector_shuffle(texel, texel, &[2, 1, 0, 3]), + (None, true, _) => super::color::alpha_in_red(fb, texel), + (None, false, true) => fb.vector_shuffle(texel, texel, &[1, 2, 3, 0]), + (None, false, false) => Ok(texel), } } /// Metal-ordered texel `texel` of storage-form attachment `sc`, in its image's channel order: -/// [`metal_order`]'s exchange of red and blue, which is its own inverse, and for an image holding -/// Metal's alpha in red, Metal's alpha in every lane (the image keeps its red). Every texel -/// written to the attachment's image goes through here ([`emit_return`]). +/// [`metal_order`]'s exchange of red and blue, which is its own inverse, for an image holding +/// Metal's alpha in red, Metal's alpha in every lane (the image keeps its red), and for one holding +/// Metal's channels rotated, Metal's alpha, red, green and blue as the image's red, green, blue +/// and alpha (the inverse of [`metal_order`]'s rotation). Every texel written to the attachment's +/// image goes through here ([`emit_return`]). fn image_order(fb: &mut FunctionBuilder<'_>, sc: &StorageColor, texel: SValue) -> BResult { - match (sc.view.rgba_view, sc.view.alpha_in_red) { - (Some(_), _) => fb.vector_shuffle(texel, texel, &[2, 1, 0, 3]), - (None, true) => fb.vector_shuffle(texel, texel, &[3, 3, 3, 3]), - (None, false) => Ok(texel), + match (sc.view.rgba_view, sc.view.alpha_in_red, sc.view.rotated) { + (Some(_), _, _) => fb.vector_shuffle(texel, texel, &[2, 1, 0, 3]), + (None, true, _) => fb.vector_shuffle(texel, texel, &[3, 3, 3, 3]), + (None, false, true) => fb.vector_shuffle(texel, texel, &[3, 0, 1, 2]), + (None, false, false) => Ok(texel), } } diff --git a/crates/metal2vulkan/src/lower/fragment/input_blend.rs b/crates/metal2vulkan/src/lower/fragment/input_blend.rs index ea7856b26..89a82c2ea 100644 --- a/crates/metal2vulkan/src/lower/fragment/input_blend.rs +++ b/crates/metal2vulkan/src/lower/fragment/input_blend.rs @@ -30,6 +30,19 @@ //! (`extended_range::encode_keeping`), as Metal's tile keeps a masked channel's code; it states //! `RuntimeFact::WordInputMerge`, and link writes every raw component. //! +//! An attachment held with its channels rotated (`ARGB8Unorm` in `R8G8B8A8_UNORM`) whose blend no +//! Vulkan state on its image gives (`color_writes::shader_rotated_blend`) takes Metal's blend there +//! too ([`RotatedInputBlend`]): Metal blends the format as `RGBA8Unorm` with its channels rotated, so +//! the first output's write reads the pixel's texel through the input attachment, rotates it into +//! Metal's order, computes Metal's 8-bit unorm blend of the clamped output over it +//! (`extended_range::Blend::unorm8`, `extended_range::blend::blend_unorm8`, as the storage form +//! computes it), and writes the result through the output variable, which the stage interface +//! rotates into the image's order as every output to such an attachment +//! (`stage_io::output_part`); the device's conversion stores its code +//! (`PrecisionNote::DeviceColorConversion`), and the descriptor's write mask, rotated, keeps the +//! channels it leaves out. It states `RuntimeFact::RotatedInputBlend`, and link gives the +//! attachment no Vulkan blend. +//! //! The blend takes a `half4` or `float4` output under every factor, operation and write mask, as //! the storage form does (another output is refused, `Feature::ExtendedRangeBlend` `Output`); its //! second source is the function's index-1 output, read from the returned value and stored nowhere @@ -44,11 +57,12 @@ use crate::air::ir::TypeId as AirTypeId; use crate::error::{ Attachment, DescriptorError, Error, ExtendedRangeBlend, Feature, RuntimeInput, Unsupported, }; -use crate::lower::arith::{extended_range, Form}; +use crate::lower::arith::{extended_range, FloatFmt, Form}; use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; use crate::metal::format::ExtendedRange; -use crate::metal::ColorWriteMask; +use crate::metal::{ColorWriteMask, PixelFormat}; +use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::facts::RuntimeFact; use crate::pipeline::lower_inputs::BlendEquation; use crate::pipeline::sym::{PushField, Stage}; @@ -92,6 +106,24 @@ impl InputBlend { } } +/// An attachment held with its channels rotated (`ARGB8Unorm`) whose blend the function computes +/// over its input attachment (see the module docs). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RotatedInputBlend { + /// The pipeline's blend at the attachment. + pub equation: BlendEquation, + /// Metal's channels the write stores: those the descriptor's write mask covers, none where it + /// covers none (the write then reads and blends nothing). + pub written: ColorWriteMask, +} + +impl RotatedInputBlend { + /// Whether the write reads the attachment's input attachment: it stores some channel. + pub fn reads(&self) -> bool { + !self.written.is_empty() + } +} + /// An upper estimate of the words one blended write adds beside its blend's arithmetic: the /// input attachment's read, its decode, the encode, and a merge of kept channels. const WRITE_WORDS: u64 = 120; @@ -202,8 +234,11 @@ pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> { ); } merged(cx, &inputs, &mut planned)?; - let reads = planned.values().any(InputBlend::reads); + let rotated = rotated(cx, &inputs)?; + let reads = + planned.values().any(InputBlend::reads) || rotated.values().any(RotatedInputBlend::reads); cx.families.fragment.input_blends = planned; + cx.families.fragment.rotated_blends = rotated; match reads { true => fetch::plan_sample(cx), false => Ok(()), @@ -272,6 +307,99 @@ fn merged( Ok(()) } +/// Plan the attachments held with their channels rotated that the function writes through a first +/// output and the pipeline's state `inputs` names (`color_writes::shader_rotated_blend`, the only +/// reason such an attachment is named on this device): each one whose write stores some of its +/// channels reads its input attachment and computes Metal's 8-bit unorm blend there, and each +/// states `RuntimeFact::RotatedInputBlend` (see the module docs). +fn rotated( + cx: &mut SelectCx<'_>, + inputs: &crate::pipeline::lower_inputs::FramebufferFetchInputs, +) -> Result, Error> { + let mut planned = BTreeMap::new(); + let outputs: Vec<(u32, AirTypeId)> = cx + .entry + .ep + .outputs + .iter() + .zip(crate::lower::stage_io::output_types(cx)?.1) + .filter_map(|(o, ty)| match o.role { + OutputRole::RenderTarget { + attachment: AbiInt::Const(color), + index: 0, + .. + } => Some((color, ty)), + _ => None, + }) + .collect(); + for (color, ty) in outputs { + let Some(a) = inputs.attachments.get(&color).copied().flatten() else { + continue; + }; + if !crate::metal::format::rotated_channels(a.pixel_format) + || !cx.inputs.rotated_colors.contains(&color) + { + continue; + } + let tied = |e: Error| e.at_attachment(Attachment::Color(color)); + let Some(eq) = a.equation.filter(|_| a.blending_enabled) else { + // Compiled under the state of a pipeline for another function. + return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)); + }; + let kept = fetch::kept_channels(a.pixel_format, a.write_mask, true); + let written = ColorWriteMask::ALL.difference(kept); + let kept = crate::metal::state::color_write_mask(kept).map_err(tied)?; + cx.facts.insert(RuntimeFact::RotatedInputBlend { + color, + blend: eq, + kept, + }); + let rb = RotatedInputBlend { + equation: eq, + written: match kept == vk::ColorComponentFlags::known_bits() { + true => ColorWriteMask::NONE, + false => written, + }, + }; + if rb.reads() { + let f = super::color::form(cx, ty).map_err(tied)?; + let arith = match (f.lanes, f.float_fmt()) { + (4, Some(FloatFmt::Half)) => extended_range::blend::BlendArith::Half, + (4, Some(FloatFmt::F32)) => extended_range::blend::BlendArith::Float, + // An output of fewer lanes to a rotated attachment (`stage_io`). + _ => { + let refused = Unsupported::not_implemented(Feature::Format); + return Err(tied(refused.into())); + } + }; + let math = fetch::blend_math(cx); + let b = extended_range::Blend::unorm8( + &eq, + PixelFormat::ARGB8Unorm, + rb.written, + (math, arith), + ) + .map_err(tied)?; + if b.reads_constant() { + cx.push.insert(PushField::HalfBlendColor); + } + // The attachment's input attachment. + cx.descriptors.input_attachments = cx.descriptors.input_attachments.saturating_add(1); + cx.facts.insert(RuntimeFact::FramebufferFetch { color }); + // The result is the device's to convert to its code; the blend is Metal's where the + // module states its math (Metal clamps the output first, so none of the output's + // arithmetic folds into it), as the storage form's is. + cx.precision.insert(PrecisionNote::DeviceColorConversion); + if cx.entry.compile.fast_math.is_none() { + let note = crate::lower::arith::output_precision::half_output_note(cx); + cx.precision.insert(note); + } + } + planned.insert(color, rb); + } + Ok(planned) +} + /// Whether the function's second (index-1) output to `color` is the second source of the blend /// the function computes over the attachment's input attachment ([`select_second_output`]). pub(super) fn blends_second(cx: &SelectCx<'_>, color: u32) -> bool { @@ -358,22 +486,70 @@ pub(crate) fn texel( extended_range::encode_keeping(fb, ib.form, v, (codes, kept)) } +/// The Metal-ordered value a write of first output `part` (of `form`: four `half` or `float` +/// lanes held as `f32`s) to attachment `color`, held with its channels rotated, stores, whose blend +/// the function computes over its input attachment (`rb`; see the module docs): the texel read +/// there, rotated into Metal's order, and Metal's 8-bit unorm blend of the output over it +/// (`extended_range::blend::blend_unorm8`), the blend color from `PushField::HalfBlendColor` where +/// the blend reads it. For a write that stores none of the format's channels, the output. +pub(crate) fn rotated_texel( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + (color, rb): (u32, &RotatedInputBlend), + (form, part): (Form, SValue), +) -> BResult { + if !rb.reads() { + return Ok(part); + } + let arith = match (form.lanes, form.float_fmt()) { + (4, Some(FloatFmt::Half)) => extended_range::blend::BlendArith::Half, + (4, Some(FloatFmt::F32)) => extended_range::blend::BlendArith::Float, + _ => return Err(cx.fail("an 8-bit unorm blend of another output")), + }; + let math = extended_range::blend::BlendMath::of(cx.entry.compile.fast_math); + let pf = PixelFormat::ARGB8Unorm; + let Ok(b) = extended_range::Blend::unorm8(&rb.equation, pf, rb.written, (math, arith)) else { + return Err(cx.fail("an 8-bit unorm blend outside Metal's model")); + }; + let texel = super::color::input_texel(cx, fb, color)?; + // The image's red, green, blue and alpha hold Metal's alpha, red, green and blue. + let texel = fb.vector_shuffle(texel, texel, &[1, 2, 3, 0])?; + let constant = match b.reads_constant() { + true => { + let field = cx.push_field(fb, PushField::HalfBlendColor)?; + Some(fb.composite_extract(field, &[0])?) + } + false => None, + }; + extended_range::blend::blend_unorm8(fb, &b, arith, (part, texel), constant) +} + /// The words the planned blends add at `rets` returns: one input attachment each beside the /// reads `color` counts, and at each return the read, decode, blend and encode. pub(super) fn words(cx: &SelectCx<'_>, rets: u64) -> u64 { - cx.families - .fragment - .input_blends + let fp = &cx.families.fragment; + let extended = fp.input_blends.values().filter(|ib| ib.reads()).map(|ib| { + let blend = ib.blend.as_ref().map_or(0, |b| b.words()); + let each = WRITE_WORDS + .saturating_add(u64::from(blend)) + .saturating_add(u64::from( + extended_range::DECODE_WORDS + extended_range::ENCODE_WORDS, + )); + each.saturating_mul(rets.max(1)) + }); + let math = fetch::blend_math(cx); + let rotated = fp + .rotated_blends .values() - .filter(|ib| ib.reads()) - .map(|ib| { - let blend = ib.blend.as_ref().map_or(0, |b| b.words()); - let each = WRITE_WORDS + .filter(|rb| rb.reads()) + .map(|rb| { + let half = extended_range::blend::BlendArith::Half; + let pf = PixelFormat::ARGB8Unorm; + let blend = extended_range::Blend::unorm8(&rb.equation, pf, rb.written, (math, half)) + .map_or(0, |b| b.words()); + WRITE_WORDS .saturating_add(u64::from(blend)) - .saturating_add(u64::from( - extended_range::DECODE_WORDS + extended_range::ENCODE_WORDS, - )); - each.saturating_mul(rets.max(1)) - }) - .fold(0u64, u64::saturating_add) + .saturating_mul(rets.max(1)) + }); + extended.chain(rotated).fold(0u64, u64::saturating_add) } diff --git a/crates/metal2vulkan/src/lower/fragment/mod.rs b/crates/metal2vulkan/src/lower/fragment/mod.rs index 22d3c68d0..53bb08606 100644 --- a/crates/metal2vulkan/src/lower/fragment/mod.rs +++ b/crates/metal2vulkan/src/lower/fragment/mod.rs @@ -114,8 +114,10 @@ pub use fetch::{ StorageColor, }; pub use imageblock::{select_output as select_imageblock_output, ImageblockPlan}; -pub(crate) use input_blend::texel as input_blend_texel; -pub use input_blend::{select_second_output as select_input_second_output, InputBlend}; +pub(crate) use input_blend::{rotated_texel as rotated_input_texel, texel as input_blend_texel}; +pub use input_blend::{ + select_second_output as select_input_second_output, InputBlend, RotatedInputBlend, +}; pub use input_shadow::InputShadow; pub(crate) use input_shadow::{shadows as input_shadow, store as input_shadow_store}; #[cfg(test)] @@ -207,6 +209,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 attachments held with their channels rotated whose blend the function computes over + /// their input attachments, on a device that orders fetch through them (`input_blend`), by + /// index. + pub rotated_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. @@ -521,6 +527,7 @@ pub fn declare( mb, &fp.colors, (&fp.fetch, &fp.input_blends, &fp.word_merges), + &fp.rotated_blends, fp.fetch_sample.is_some(), )?; for (&color, sc) in &fp.fetch { diff --git a/crates/metal2vulkan/src/lower/stage_io/mod.rs b/crates/metal2vulkan/src/lower/stage_io/mod.rs index 8d9fe4945..99d55fcf2 100644 --- a/crates/metal2vulkan/src/lower/stage_io/mod.rs +++ b/crates/metal2vulkan/src/lower/stage_io/mod.rs @@ -2189,6 +2189,30 @@ 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))? } + // An attachment held with its channels rotated whose blend the function computes over its + // input attachment, in Metal's order: the rotation below takes it into the image's. + Some(color) + if cx + .plan + .families + .fragment + .rotated_blends + .contains_key(&color) => + { + let plan = cx.plan; + let Some(rb) = plan.families.fragment.rotated_blends.get(&color) else { + return Err( + cx.fail("a rotated input blend of an attachment the plan does not name") + ); + }; + let v = crate::lower::fragment::rotated_input_texel( + cx, + fb, + (color, rb), + (o.link.form, part), + )?; + color_write::round(cx, fb, color, o.link.form, v)? + } Some(color) => match ( cx.plan.families.stage_io.words_written.get(&color).copied(), cx.plan.families.stage_io.extended.get(&color).copied(), diff --git a/crates/metal2vulkan/src/metal/format/mod.rs b/crates/metal2vulkan/src/metal/format/mod.rs index 4761a52c3..95b187da4 100644 --- a/crates/metal2vulkan/src/metal/format/mod.rs +++ b/crates/metal2vulkan/src/metal/format/mod.rs @@ -156,8 +156,9 @@ pub enum FormatEmulation { /// rotated (`LoweringInputs::rotated_colors`), whose clear color and write mask the consumer /// rotates too; Metal stores, clears, masks, resolves and blends the format as `RGBA8Unorm` /// with its channels rotated. Admitted for those usages, and for blending - /// through the factors `pipeline::rotated_blend` finds Metal's blend in, which refuses the - /// rest. + /// through the factors `pipeline::rotated_blend` finds Metal's blend in; a blend no such + /// factor gives the fragment function computes over the texel where the device orders + /// framebuffer fetch (`pipeline::color_writes::shader_rotated_blend`). RotatedView, /// A render pass's color attachment of a two-plane YCbCr format whose store Metal's planes /// are matched for ([`ycbcr_renders`]): `R32G32B32A32_SFLOAT` of the values the pass leaves diff --git a/crates/metal2vulkan/src/pipeline/color_writes.rs b/crates/metal2vulkan/src/pipeline/color_writes.rs index cba0d16cc..fe67f72b0 100644 --- a/crates/metal2vulkan/src/pipeline/color_writes.rs +++ b/crates/metal2vulkan/src/pipeline/color_writes.rs @@ -665,6 +665,55 @@ pub(crate) fn wanted_alpha_in_red( out } +/// Whether the fragment function computes Metal's blend into color attachment `c` of a render +/// pipeline on `p` itself, over the texel it reads: an attachment held with its channels rotated +/// (`ARGB8Unorm` in `R8G8B8A8_UNORM`, `metal::format::rotated_channels`) whose blend no Vulkan +/// state on the rotated image gives (`rotated_blend` refuses it `NotImplemented(Format)`: Metal's +/// destination alpha in a color factor, the saturated source alpha, the blend color's red, green +/// or blue, different color and alpha operations), whose factors read no second source, on a +/// device that orders framebuffer fetch (`lower::fragment::fetch`). Metal blends the format as +/// `RGBA8Unorm` with its channels rotated, so the function computes Metal's 8-bit unorm blend +/// (`extended_range::Blend::unorm8`, which takes every factor and operation but the second +/// source's) over the texel rotated into Metal's order: in the interlocked storage form where the +/// device orders fetch through the pixel interlock (`lower::fragment::fetch`), over the +/// attachment's input attachment where it orders it through rasterization-order input attachments +/// (`lower::fragment`'s `input_blend`). A device that orders fetch in neither form refuses the +/// pipeline (`fetch::unordered_extended_fetch`, at link). +pub(crate) fn shader_rotated_blend(c: &ColorAttachmentDescriptor, p: &DeviceProfile) -> bool { + rotated_blend_in_shader(c, p) && !crate::lower::fragment::fetch::fetch_unordered(p) +} + +/// Whether the blend of color attachment `c` of a render pipeline on `p` is one the fragment +/// function computes over the texel where the device orders framebuffer fetch +/// ([`shader_rotated_blend`]'s, whatever the device's orderings). +pub(crate) fn rotated_blend_in_shader(c: &ColorAttachmentDescriptor, p: &DeviceProfile) -> bool { + use metal::BlendFactor as F; + if !metal::format::rotated_channels(c.pixel_format) || !c.blending_enabled { + return false; + } + let refused = Error::from(crate::error::Unsupported::not_implemented( + crate::error::Feature::Format, + )); + if rotated_blend(c, p).err() != Some(refused) { + return false; + } + let c = c.specialized(); + 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 + ) + }); + !second +} + /// The second outputs of the attachments of `colors` held with their channels rotated, on `p` /// (`LoweringInputs::rotated_factors`): every such attachment whose blend Vulkan's factors read /// from a second output the rotation needs (`rotated_blend::RotatedBlend::Synthesized`). An diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 37019b0bd..042105b45 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -2097,7 +2097,9 @@ pub(crate) fn unattached_colors_written( /// interlock, the state of every attachment the entry declares a `[[color(n)]]` input of a constant /// index for, of every extended-range attachment it writes that the pass blends (whose blend the /// function computes from the texel it reads) or writes unblended under a mask of some of the codes -/// one word holds (`color_writes::merged_extended`), and of every attachment variant `v`'s instance keeps +/// one word holds (`color_writes::merged_extended`), of every attachment held with its channels +/// rotated whose blend the function computes (`color_writes::shader_rotated_blend`, in either form +/// below), and of every attachment variant `v`'s instance keeps /// out of its subpass that the entry writes through its first output /// (`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 @@ -2164,6 +2166,15 @@ pub(crate) fn fetch_inputs( }) .is_some() }; + // An attachment held with its channels rotated whose blend the function computes over the + // texel it reads, in either form (`color_writes::shader_rotated_blend`). + let rotated_blend = |color: u32| { + d.color_attachments + .get(color as usize) + .copied() + .flatten() + .is_some_and(|c| crate::pipeline::color_writes::shader_rotated_blend(&c, p)) + }; let read: BTreeSet = spec .ep .params @@ -2181,6 +2192,7 @@ pub(crate) fn fetch_inputs( index: 0, .. } if blended(color) + || rotated_blend(color) || (interlock && (stored_word(color) || merged_extended(color))) || (inputs && (merged_word(color) || merged_extended(color))) => { diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 39fc130c7..6ed17c458 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -614,6 +614,21 @@ pub enum RuntimeFact { kept: crate::vk::ColorComponentFlags, }, /// On a device that orders framebuffer fetch through rasterization-order input attachments, + /// the function computes Metal's blend `blend` into color attachment `color`, held with its + /// channels rotated (`ARGB8Unorm` in `R8G8B8A8_UNORM`), where no Vulkan state on that image + /// gives it (`color_writes::shader_rotated_blend`): it reads the texel through the + /// attachment's input attachment (`RuntimeFact::FramebufferFetch`), blends its output over it + /// in Metal's channel order by Metal's 8-bit unorm blend, and writes the result through its + /// first output, rotated as every output there is. `kept` is the format's channels the + /// descriptor's write mask leaves out, which the attachment's write mask keeps. Link gives the + /// attachment no Vulkan blend, and a pipeline of another blend or write mask there is + /// `NeedsInput(FramebufferFetch)`. + RotatedInputBlend { + color: u32, + 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 diff --git a/crates/metal2vulkan/src/pipeline/link/fetch.rs b/crates/metal2vulkan/src/pipeline/link/fetch.rs index 8c05262e2..3da898f5b 100644 --- a/crates/metal2vulkan/src/pipeline/link/fetch.rs +++ b/crates/metal2vulkan/src/pipeline/link/fetch.rs @@ -30,6 +30,9 @@ //! 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 computes the blend of an attachment held with its channels rotated that +//! no Vulkan state on its image gives (`RuntimeFact::RotatedInputBlend`, [`input_blends`]), which +//! `graphics_state` gives no Vulkan blend and the descriptor's write mask, rotated. //! 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 @@ -177,7 +180,9 @@ pub fn storage_attachments( /// The extended-range attachments whose blend fragment stage `fragment` computes over their /// input attachments (`RuntimeFact::ExtendedRangeInputBlend`), or whose codes it merges there -/// (`RuntimeFact::WordInputMerge` of such an attachment), on a device that orders fetch through +/// (`RuntimeFact::WordInputMerge` of such an attachment), and the attachments held with their +/// channels rotated whose blend it computes there (`RuntimeFact::RotatedInputBlend`, which link +/// gives no Vulkan blend and the descriptor's write mask, rotated), on a device that orders fetch through /// rasterization-order input attachments, against the attachments of render inputs `r`: by color /// index, the channels each write keeps from its texel, where the pipeline's blend and write mask /// there are those the function compiled under; `NeedsInput(FramebufferFetch)` where they are @@ -203,6 +208,30 @@ pub fn input_blends( } continue; } + // An attachment held with its channels rotated whose blend the function computes over its + // input attachment (`color_writes::shader_rotated_blend`): its write keeps the channels the + // descriptor's mask leaves out through the attachment's write mask. + if let RuntimeFact::RotatedInputBlend { color, blend, kept } = *fact { + if !inputs_order(p) { + return Err(Error::Internal(InternalError::new( + InternalKind::Invariant, + "a rotated blend over an input attachment on a device that fetches otherwise", + ))); + } + let Some(a) = r.color_attachments.get(color as usize).copied().flatten() else { + return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)); + }; + let pipeline_kept = + color_write_mask(kept_channels(a.pixel_format, a.write_mask, true))?; + if !crate::pipeline::color_writes::shader_rotated_blend(&a, p) + || BlendEquation::of(&a) != Some(blend) + || pipeline_kept != kept + { + return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)); + } + out.insert(color, kept); + continue; + } let RuntimeFact::ExtendedRangeInputBlend { color, blend, kept } = *fact else { continue; }; diff --git a/crates/metal2vulkan/src/pipeline/link/graphics.rs b/crates/metal2vulkan/src/pipeline/link/graphics.rs index 2da66a4e0..c677dac4c 100644 --- a/crates/metal2vulkan/src/pipeline/link/graphics.rs +++ b/crates/metal2vulkan/src/pipeline/link/graphics.rs @@ -495,6 +495,25 @@ pub fn graphics_state( (true, _) => None, (false, false) => blend_factors(a, p)?, (false, true) if alpha_red => alpha_in_red_blend(a, p)?, + // A blend no Vulkan state on the rotated image gives, which a stage + // compiled for this pipeline computes itself, in the storage form (no + // color attachment here) or over the input attachment (above): one that + // does not was compiled for another pipeline. Unwritten, it writes nothing. + (false, true) if color_writes::shader_rotated_blend(a, p) => { + match written_here { + true => { + return Err(Error::NeedsInput(RuntimeInput::FramebufferFetch)) + } + false => None, + } + } + // Where the device orders fetch in neither form, the orderings that + // blend needs. + (false, true) if color_writes::rotated_blend_in_shader(a, p) => { + return Err( + crate::lower::fragment::fetch::unordered_extended_fetch().into() + ); + } // The second output the rotation needs is the function's only beside // a first output to the attachment; without one the draw writes nothing // there whatever the blend (its mask is empty). diff --git a/crates/metal2vulkan/src/pipeline/rotated_blend.rs b/crates/metal2vulkan/src/pipeline/rotated_blend.rs index 17e029955..a4a8df875 100644 --- a/crates/metal2vulkan/src/pipeline/rotated_blend.rs +++ b/crates/metal2vulkan/src/pipeline/rotated_blend.rs @@ -23,11 +23,17 @@ //! the very value Metal's blend reads, and computes one minus it itself, as Metal's does. This //! needs `dualSrcBlend`. A blend of Metal's own second output (`Source1` factors) reads that //! output, which the function stores rotated as the image's channels are. -//! - **What no such factor gives is `NotImplemented(Format)`:** Metal's destination alpha in a -//! color factor, the saturated source alpha, the blend color's red, green or blue, a second -//! output of Metal's own beside one the rotation needs, and different color and alpha -//! operations. A one minus a value the function would compute is not offered: it would round -//! apart from the blend's own. +//! - **What no such factor gives, the fragment function computes:** Metal's destination alpha in +//! a color factor, the saturated source alpha, the blend color's red, green or blue, and +//! different color and alpha operations (`rotated_blend` refuses them `NotImplemented(Format)`). +//! Where the device orders framebuffer fetch, the function reads the texel, rotates it into +//! Metal's order, and computes Metal's 8-bit unorm blend over it +//! (`color_writes::shader_rotated_blend`: the interlocked storage form, or over the input +//! attachment); a device that orders fetch in neither form refuses the pipeline naming both +//! orderings. A factor of the second source (Metal's own second output beside one the rotation +//! needs, or any `Source1` factor where no Vulkan state gives the blend) stays +//! `NotImplemented(Format)`. A one minus a value the function would compute is not offered +//! among Vulkan's factors: it would round apart from the blend's own. //! //! **Measured forms.** Apple's blend does not compute every factor pair alike in its color and //! alpha arithmetic, and the rotation moves Metal's blue into the image's alpha and Metal's alpha diff --git a/crates/metal2vulkan/src/tests/engine_rotated_colors.rs b/crates/metal2vulkan/src/tests/engine_rotated_colors.rs index cc06eb161..03006d73c 100644 --- a/crates/metal2vulkan/src/tests/engine_rotated_colors.rs +++ b/crates/metal2vulkan/src/tests/engine_rotated_colors.rs @@ -11,7 +11,10 @@ //! output of copies of it (`StageIo::rotated_factors`, an output of index 1 the function's //! last shuffle fills) through Vulkan's `SRC1` factors where the device blends dual-source and //! the function writes no more attachments than its dual-source limit, else names the feature -//! or the limit; and one no Vulkan factor gives, or alpha to coverage over it, is refused +//! or the limit; one no Vulkan factor gives the function computes over the texel where the +//! device orders framebuffer fetch (the interlocked storage form, or over the input attachment, +//! `RotatedInputBlend`), noting the device's conversion, and a device that orders it in neither +//! form refuses naming both orderings; alpha to coverage over the image is refused //! `NotImplemented(Format)` at the attachment; //! - where the device's blend is Apple's, straight alpha takes the measured premultiplied form: a //! second output of `(0, 0, 0, a)` and Metal's blue times Metal's alpha in the image's alpha; a @@ -168,16 +171,18 @@ fn premultiplies(pipeline: &RenderPipeline) -> bool { .any(|o| o.len() == 7 && o[3] == FMA && of_clamped(o[4], o[5])) } -/// Whether the pipeline's fragment stage records `PrecisionNote::RotatedBlendRounding`. -fn announces_rounding(pipeline: &RenderPipeline) -> bool { +/// Whether the pipeline's fragment stage records `note`. +fn notes(pipeline: &RenderPipeline, note: PrecisionNote) -> bool { pipeline .stages .iter() .filter(|s| s.stage == vk::ShaderStage::FRAGMENT) - .any(|s| { - s.precision_notes - .contains(&PrecisionNote::RotatedBlendRounding) - }) + .any(|s| s.precision_notes.contains(¬e)) +} + +/// Whether the pipeline's fragment stage records `PrecisionNote::RotatedBlendRounding`. +fn announces_rounding(pipeline: &RenderPipeline) -> bool { + notes(pipeline, PrecisionNote::RotatedBlendRounding) } fn blended( @@ -313,29 +318,84 @@ fn argb8_attachments_take_the_output_mask_and_blend_rotated() { Err(e) => panic!("{stem}: {c:?} beside color 2: {e}"), } } - // Blends no Vulkan factor gives on the image, and alpha to coverage over it. - let coverage = ColorAttachmentDescriptor::new(PixelFormat::ARGB8Unorm); - for (c, alpha_to_coverage) in [ - (blended(F::DestinationAlpha, F::Zero, O::Add, O::Add), false), - (blended(F::BlendColor, F::Zero, O::Add, O::Add), false), - (blended(F::One, F::One, O::Add, O::Subtract), false), - (blended(F::One, F::One, O::Min, O::Max), false), - (coverage, true), + // Blends no Vulkan factor gives on the image: the function computes Metal's 8-bit unorm + // blend over the texel where the device orders framebuffer fetch, in the interlocked + // storage form (color 0 is no attachment of the subpass) or over the attachment's input + // attachment (`RotatedInputBlend`, no Vulkan blend there), and a device that orders it in + // neither form names both orderings. + let interlock = crate::lower::fragment::interlock_orders(dev.profile()); + let inputs = crate::lower::fragment::inputs_order(dev.profile()); + for c in [ + blended(F::DestinationAlpha, F::Zero, O::Add, O::Add), + blended(F::BlendColor, F::Zero, O::Add, O::Add), + blended(F::One, F::One, O::Add, O::Subtract), + blended(F::One, F::One, O::Min, O::Max), ] { - let mut d = descriptor(&bc, c, true); - d.alpha_to_coverage = alpha_to_coverage; + let d = descriptor(&bc, c, true); match dev.compile_render_pipeline(&d, &Budget::standard()) { - Err(Error::Unsupported(u)) => { + Ok(p) if interlock => { + assert!(p.graphics.color_attachments[0].is_none(), "{stem}: {c:?}"); + let stored = &p.graphics.storage_attachments; + assert!( + stored.iter().any(|s| s.color_index == 0 + && s.writes + && s.format == vk::Format::R8G8B8A8_UNORM), + "{stem}: {c:?}: {stored:?}" + ); + assert!(notes(&p, PrecisionNote::DeviceColorConversion), "{stem}"); + } + Ok(p) if inputs => { + let state = p.graphics.color_attachments[0].expect("color 0"); + assert_eq!(state.blend, None, "{stem}: {c:?}"); + assert_eq!(state.format, vk::Format::R8G8B8A8_UNORM, "{stem}"); + let fact = p.dependencies.iter().any(|d| { + matches!( + d.fact, + crate::pipeline::RuntimeFact::RotatedInputBlend { color: 0, .. } + ) + }); + assert!(fact, "{stem}: {c:?}"); + assert!(notes(&p, PrecisionNote::DeviceColorConversion), "{stem}"); + } + Ok(_) => panic!("{stem}: {c:?}: made on a device that orders no fetch"), + Err(Error::Unsupported(u)) if !interlock && !inputs => { + assert_eq!(u.feature, Feature::FramebufferFetch, "{stem}: {c:?}"); assert_eq!( - (u.feature, u.needs), - (Feature::Format, Needs::NotImplemented) + u.needs, + Needs::AnyOf(vec![ + vec![Capability::Feature(VkFeature::FragmentShaderPixelInterlock)], + vec![Capability::Feature( + VkFeature::RasterizationOrderColorAttachmentAccess + )], + ]), + "{stem}: {c:?}" ); let at = u.location.as_ref().and_then(|l| l.attachment()); assert_eq!(at, Some(Attachment::Color(0)), "{stem}: {c:?}"); } + // A device that orders fetch but lacks what the form needs names it. + Err(Error::Unsupported(u)) if u.needs != Needs::NotImplemented => {} other => panic!("{stem}: {c:?}: {:?}", other.map(|_| ())), } } + // Alpha to coverage over the image. + let mut d = descriptor( + &bc, + ColorAttachmentDescriptor::new(PixelFormat::ARGB8Unorm), + true, + ); + d.alpha_to_coverage = true; + match dev.compile_render_pipeline(&d, &Budget::standard()) { + Err(Error::Unsupported(u)) => { + assert_eq!( + (u.feature, u.needs), + (Feature::Format, Needs::NotImplemented) + ); + let at = u.location.as_ref().and_then(|l| l.attachment()); + assert_eq!(at, Some(Attachment::Color(0)), "{stem}"); + } + other => panic!("{stem}: alpha to coverage: {:?}", other.map(|_| ())), + } } assert!(checked > 0); } diff --git a/docs/API.md b/docs/API.md index e78d66892..ba3641ce1 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3403,7 +3403,10 @@ bound. unit in the last place, a finite value past 65504 stored as 65504); and a fragment function's `float` blend into a 16-bit float attachment through the pixel interlock on a device not measured to round a `half` store as Metal does, and a blend into an 8-bit unorm attachment through - the pixel interlock, whose result the storage image's store converts to its code. The recorded bound past one code, measured on + the pixel interlock, whose result the storage image's store converts to its code, or into an + `ARGB8Unorm` attachment over its input attachment where no Vulkan blend state on its rotated + image gives Metal's (a destination alpha in a color factor, say), whose result the attachment's + write converts. The recorded bound past one code, measured on lavapipe against plain Metal on an Apple M3 Max: a blend into an 8-bit unorm attachment (`RGBA8Unorm`, `ARGB8Unorm`) within 2 codes of Metal's; a fragment function that fetches an 8-bit sRGB attachment and writes it again, within 2 codes once a later draw reads an earlier one's code