diff --git a/crates/metal2vulkan-runtime/src/color_resolve.rs b/crates/metal2vulkan-runtime/src/color_resolve.rs index f48ce2504..736a264c5 100644 --- a/crates/metal2vulkan-runtime/src/color_resolve.rs +++ b/crates/metal2vulkan-runtime/src/color_resolve.rs @@ -30,7 +30,10 @@ //! attachment resolves from its planes there as well ([`resolve_planes`]): its pass has one //! subpass, whose resolve references render pass compatibility ignores (`render_target.rs`). //! - **From the attachment** otherwise: its level and layer as the resolve pass's input -//! attachment 0, loaded and stored. Its image needs input attachment usage, which a +//! attachment 0, loaded and stored. An 8-bit sRGB attachment whose image takes its UNORM twin's +//! view (an sRGB texture's image lists its twin's formats) is read through that view +//! ([`raw_view`], `bind::ResolveSource::RawInputAttachment`), so the resolve reads each sample's +//! code as a unorm code with no table lookup. Its image needs input attachment usage, which a //! multisampled color render target the runtime makes takes where the device may resolve it so //! and the usage costs the image nothing, and a memoryless one wherever the device makes the //! image (`framebuffer_fetch.rs`), as does a stand-in (`attachment_stand_in.rs`). @@ -47,6 +50,11 @@ //! image of has neither usage: it resolves by the device's average, announced as //! `device-rounded-resolve`. //! +//! From any source, an 8-bit sRGB resolve writes its result through the resolve attachment's view +//! in its UNORM twin where that image takes one ([`raw_view`], +//! `bind::ColorResolveFormat::written_raw`): each code goes out as a unorm code's float, which the +//! twin's store keeps as the code, with no table lookup and no sRGB encode. +//! //! A layered pass (`renderTargetArrayLength` 2 or more) resolves each of its layers in a render //! pass instance of its own, through views of that layer. Its resolve from the sample planes, which //! hold one layer, is `NotImplemented(LayeredPass)`. @@ -60,7 +68,7 @@ //! runtime announces `shader-resolve` (performance) for the extra pass (naming the copy where the //! resolve reads one), and `unmeasured-resolve` (precision) at more than 4 samples. -use super::binding_view::VkView; +use super::binding_view::{views_as, VkView}; use super::blit::TRANSFER; use super::command_buffer::CommandBuffer; use super::device::{device_error, lock}; @@ -190,11 +198,27 @@ pub(super) fn input_candidate(plan: &ImagePlan, device: &Device) -> Option Result { + let raw = rules.raw_format(); + if raw == rules.format() || target.format != rules.format() { + return Ok(false); + } + let profile = device.compile_device().profile(); + Ok(views_as(target.texture.image_plan()?, raw, false) + && profile.supports_format(raw, FormatUsage::ColorAttachment)) +} + /// Where a resolve reads its samples (the module docs). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] enum Source { - /// The attachment, as the resolve pass's input attachment 0. - Attachment, + /// The attachment, as the resolve pass's input attachment 0: through its raw twin's view where + /// `raw` ([`raw_view`]), else in its own format. + Attachment { raw: bool }, /// The attachment's sample planes, viewed in their copy format. Planes(PlanesCopy), } @@ -202,7 +226,8 @@ enum Source { impl Source { fn bind(self) -> ResolveSource { match self { - Source::Attachment => ResolveSource::InputAttachment, + Source::Attachment { raw: false } => ResolveSource::InputAttachment, + Source::Attachment { raw: true } => ResolveSource::RawInputAttachment, Source::Planes(copy) => ResolveSource::Planes(copy), } } @@ -210,10 +235,24 @@ impl Source { /// The descriptor type of the source's binding. fn descriptor(self) -> vk::DescriptorType { match self { - Source::Attachment => vk::DescriptorType::INPUT_ATTACHMENT, + Source::Attachment { .. } => vk::DescriptorType::INPUT_ATTACHMENT, Source::Planes(_) => vk::DescriptorType::SAMPLED_IMAGE, } } + + /// Whether the source is the attachment, as input attachment 0. + fn attachment(self) -> bool { + matches!(self, Source::Attachment { .. }) + } + + /// The format of the view of the attachment the source reads, whose format is `rules`'s: its + /// raw twin through the raw view, else its own. + fn read_format(self, rules: ColorResolveFormat) -> Format { + match self { + Source::Attachment { raw: true } => rules.raw_format(), + Source::Attachment { raw: false } | Source::Planes(_) => rules.format(), + } + } } /// One resolve's objects, the device's: for one format, sample count and source. @@ -306,7 +345,7 @@ impl Device { made.set_layout = set_layout(raw, &[source.descriptor()], vk::ShaderStageFlags::FRAGMENT)?; made.layout = pipeline_layout(raw, made.set_layout)?; - made.render_pass = resolve_pass(raw, format.format(), samples, source)?; + made.render_pass = resolve_pass(raw, format, samples, source)?; let making = Making::new("color resolve") .words(&modules.vertex) .words(&modules.fragment) @@ -328,19 +367,20 @@ impl Device { } } -/// The resolve's render pass for `format` at `samples` from `source`: the multisampled -/// attachment as input attachment 0 (loaded and stored, `GENERAL`) where it reads it, then the -/// single-sampled resolve attachment, written whole over the render area (`DONT_CARE`, then -/// `STORE`). +/// The resolve's render pass for `rules`'s format at `samples` from `source`: the multisampled +/// attachment as input attachment 0 (loaded and stored, `GENERAL`, in the format of the view the +/// source reads) where it reads it, then the single-sampled resolve attachment in the format of +/// the view the result is written through (`ColorResolveFormat::written_format`), written whole +/// over the render area (`DONT_CARE`, then `STORE`). fn resolve_pass( raw: &ash::Device, - format: Format, + rules: ColorResolveFormat, samples: u32, source: Source, ) -> Result { let general = vk::ImageLayout::GENERAL; let samples_attachment = vk::AttachmentDescription::default() - .format(format.into()) + .format(source.read_format(rules).into()) .samples(vk::SampleCountFlags::from_raw(samples)) .load_op(vk::AttachmentLoadOp::LOAD) .store_op(vk::AttachmentStoreOp::STORE) @@ -349,7 +389,7 @@ fn resolve_pass( .initial_layout(general) .final_layout(general); let resolved = vk::AttachmentDescription::default() - .format(format.into()) + .format(rules.written_format().into()) .samples(vk::SampleCountFlags::TYPE_1) .load_op(vk::AttachmentLoadOp::DONT_CARE) .store_op(vk::AttachmentStoreOp::STORE) @@ -358,7 +398,7 @@ fn resolve_pass( .initial_layout(general) .final_layout(general); let (attachments, color) = match source { - Source::Attachment => (vec![samples_attachment, resolved], 1), + Source::Attachment { .. } => (vec![samples_attachment, resolved], 1), Source::Planes(_) => (vec![resolved], 0), }; let inputs = [vk::AttachmentReference::default() @@ -370,7 +410,7 @@ fn resolve_pass( let mut subpass = vk::SubpassDescription::default() .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS) .color_attachments(&colors); - if source == Source::Attachment { + if source.attachment() { subpass = subpass.input_attachments(&inputs); } let subpasses = [subpass]; @@ -624,7 +664,7 @@ fn pass_key<'a>( ) -> Result, Error> { let mut resolves = Vec::new(); for (attachment, into, format, source) in wanted { - let own_views = source == Source::Attachment + let own_views = source.attachment() && attachment.layers == layers && into.layers == layers && takes_input(attachment)?; @@ -636,8 +676,14 @@ fn pass_key<'a>( for layer in 0..layers { resolves.push(ResolveKey { pipeline: (format, attachment.samples, source), - read: (read, view_of(attachment, layer, attachment.format, INPUT)?), - written: (written, view_of(into, layer, into.format, WRITTEN)?), + read: ( + read, + view_of(attachment, layer, source.read_format(format), INPUT)?, + ), + written: ( + written, + view_of(into, layer, format.written_format(), WRITTEN)?, + ), }); } } @@ -811,9 +857,18 @@ impl ShaderResolves { .planes .as_ref() .filter(|_| last_storage.contains(&(index as u32))); + // An attachment read from a copy of its samples ([`copied`]) is read in its own + // format: the scratch image takes no other view. let source = match planes { Some(planes) => Source::Planes(planes.copy), - None => Source::Attachment, + None => Source::Attachment { + raw: takes_input(&color.target)? && raw_view(device, &color.target, format)?, + }, + }; + // The result goes out through the resolve attachment's raw view where it has one. + let format = match raw_view(device, &resolve.attachment, format)? { + true => format.written_raw(), + false => format, }; wanted.push((color, resolve, format, source, planes)); } @@ -824,7 +879,7 @@ impl ShaderResolves { // sample planes hold one layer (`sample_planes.rs`), so such a pass's resolve from them // is not built. let layers = layout.layers; - if layers > 1 && wanted.iter().any(|w| w.3 != Source::Attachment) { + if layers > 1 && wanted.iter().any(|w| !w.3.attachment()) { return Err(Error::NotImplemented(RuntimeGap::LayeredPass)); } // A pass whose resolves read their attachments through their own views takes the objects @@ -863,7 +918,7 @@ impl ShaderResolves { pool: vk::DescriptorPool::null(), resolves: Vec::with_capacity(count as usize), }; - let inputs = wanted.iter().filter(|w| w.3 == Source::Attachment).count() as u32 * layers; + let inputs = wanted.iter().filter(|w| w.3.attachment()).count() as u32 * layers; let mut sizes = Vec::new(); for (ty, n) in [ (vk::DescriptorType::INPUT_ATTACHMENT, inputs), @@ -890,7 +945,7 @@ impl ShaderResolves { } // An attachment whose image takes no input attachment usage is read from a copy of // its samples ([`copied`]). - let read_copy = source == Source::Attachment && !takes_input(attachment)?; + let read_copy = source.attachment() && !takes_input(attachment)?; let scratch = match read_copy { true if copied(device, attachment)? => { let (scratch, copy, used) = copy_out(maker, attachment, layers, layout.extent)?; @@ -915,7 +970,7 @@ impl ShaderResolves { ), false, )?), - (Source::Attachment, _) => uses.push(read_use(samples, layers)?), + (Source::Attachment { .. }, _) => uses.push(read_use(samples, layers)?), (Source::Planes(_), None) => { return Err(internal("a planes resolve without planes")) } @@ -934,14 +989,14 @@ impl ShaderResolves { .first() .copied() .ok_or_else(|| internal("the driver allocated no set"))?; - let written = view(into, layer, into.format, WRITTEN)?; + let written = view(into, layer, format.written_format(), WRITTEN)?; let (read, attachments) = match (source, planes) { (Source::Planes(copy), Some(planes)) => { let read = planes.view(copy.format(), ImageUsageFlags::SAMPLED)?; (read, vec![written]) } - (Source::Attachment, _) => { - let read = view(samples, layer, samples.format, INPUT)?; + (Source::Attachment { .. }, _) => { + let read = view(samples, layer, source.read_format(format), INPUT)?; (read, vec![read, written]) } (Source::Planes(_), None) => { @@ -1094,7 +1149,7 @@ mod tests { PassKey { extent: [4, 4], resolves: vec![ResolveKey { - pipeline: (format, 4, Source::Attachment), + pipeline: (format, 4, Source::Attachment { raw: false }), read: (read, view), written: ( written, diff --git a/crates/metal2vulkan-runtime/src/families/formats.rs b/crates/metal2vulkan-runtime/src/families/formats.rs index 7b917cebf..d98551c24 100644 --- a/crates/metal2vulkan-runtime/src/families/formats.rs +++ b/crates/metal2vulkan-runtime/src/families/formats.rs @@ -13,8 +13,9 @@ //! read (`SampledImageFilterLinear` of the view's format), of a format whose texels are not //! integers: Metal filters none, a stencil view's included, nor a bfloat format's (a linear //! sample reads the nearest texel). A texture held as its sRGB format's UNORM twin -//! (`image_plan::holds_srgb_twin`), whose raw codes the shader reads, has no view a runtime -//! sampler filters through: it answers as a format not sampled. An extended-range texture +//! (`image_plan::holds_srgb_twin`) is filtered by the device through the twin's view and the +//! filtered codes decoded through Metal's table (`PrecisionNote::SrgbTexelDecode`): its Filter +//! is the twin's linear filter. An extended-range texture //! (`ExtendedRange`) is filtered by the shader from fetches of its raw texels on every device: //! its Filter is its `ShaderRead` texture's. //! - **Write**: a 2D `ShaderWrite` texture with a storage view. @@ -67,9 +68,7 @@ use super::{Column, Facts, Refusal, RowState}; use crate::device::lock; use crate::error::{Error, RuntimeGap}; -use crate::image_plan::{ - check_image_limits, holds_srgb_twin, plan_image, ImageFacts, ImagePlan, ImageRefusal, -}; +use crate::image_plan::{check_image_limits, plan_image, ImageFacts, ImagePlan, ImageRefusal}; use crate::resolve::unmodelled_resolve; use crate::sparse::texture::sparse_refusal; use crate::sparse::SparsePageSize; @@ -316,21 +315,10 @@ pub(crate) fn answers( } else { single.clone() }; - // A texture held as its sRGB format's UNORM twin is read through its raw codes alone: a runtime - // sampler's filter and border decode through the device's view of the format, which the device - // lacks, so both answer as for a format the runtime does not sample. - let sampled = probe(TextureType::Type2D, 1, TextureUsage::SHADER_READ).and_then(|plan| { - if holds_srgb_twin(&plan) { - Err(Missing::Refused(lacking( - pf, - TextureUsage::SHADER_READ, - plan.format, - profile, - ))) - } else { - Ok(plan) - } - }); + // A texture held as its sRGB format's UNORM twin is sampled through the twin's view, whose + // filtered codes the function decodes (`lower::texture::srgb_filtered_texel`): its filter and + // border are that view's. + let sampled = probe(TextureType::Type2D, 1, TextureUsage::SHADER_READ); let own = TextureSwizzleChannels::DEFAULT; let border = match &sampled { // The binder makes a runtime sampler's opaque-black border transparent black where Metal diff --git a/crates/metal2vulkan-runtime/src/image_plan.rs b/crates/metal2vulkan-runtime/src/image_plan.rs index d0fe2a9b2..9e67a8dff 100644 --- a/crates/metal2vulkan-runtime/src/image_plan.rs +++ b/crates/metal2vulkan-runtime/src/image_plan.rs @@ -713,20 +713,34 @@ fn plan_held( .then(|| storage_image_choice(pf, profile).ok()) .flatten(); // A format no slot both reads and writes on the device, whose written-only binding's view - // the device stores (`BGRA8Unorm_sRGB` on ANV: its UNORM twin is stored without a format for - // writes alone, and SPIR-V names no BGRA format), still takes that view: a slot that only + // the device stores (on ANV, which reads no storage image without a format, a format SPIR-V + // names no image format for and no alias serves), still takes that view: a slot that only // writes the texture binds, and one that reads it too is refused at its binding. let written_only = match (stored, &storage) { (true, None) => storage_view_formats(pf, profile), _ => Vec::new(), }; let wants_attachment = wants(TextureUsage::RENDER_TARGET) && attachment.is_some(); + // 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 + // image's own, and only the storage view is the alias. + let direct_held = !facts.optimal(direct).is_empty(); + let unorm_twin = srgb_raw_twin(pf).and_then(direct_format); + let twin_stored = |m: &FormatMapping| { + Some(m.format) == unorm_twin + && !direct_held + && storage + .as_ref() + .is_some_and(|c| c.alias.is_some() && c.vk_format == m.format) + }; // The image format: the sampled representation, unless a storage view or an attachment needs // the direct format, or nothing samples the texture. let mapping = match (sampled, attachment) { (Some(m), _) if m.format == direct + || twin_stored(&m) || !(storage.is_some() || !written_only.is_empty() || wants_attachment) => { m @@ -770,7 +784,11 @@ fn plan_held( // hold (roadmap-2022 states no `A2R10G10B10` at all, whose `BGR10A2Unorm` storage its // `A2B10G10R10` view would otherwise serve). let held = !facts.optimal(format).is_empty(); - match storage.filter(|c| format == direct && (c.alias.is_none() || held)) { + let twin = Some(format) == unorm_twin + && storage + .as_ref() + .is_some_and(|c| c.alias.is_some() && c.vk_format == format); + match storage.filter(|c| twin || (format == direct && (c.alias.is_none() || held))) { Some(choice) => { usage_flags |= ImageUsageFlags::STORAGE; views.insert(match choice.alias { diff --git a/crates/metal2vulkan-runtime/src/tests/families.rs b/crates/metal2vulkan-runtime/src/tests/families.rs index 0ae7afc61..3988f29db 100644 --- a/crates/metal2vulkan-runtime/src/tests/families.rs +++ b/crates/metal2vulkan-runtime/src/tests/families.rs @@ -936,6 +936,63 @@ fn extended_range_formats_answer_the_shaders_filter_and_blend() { } } +/// An 8-bit sRGB format a device holds as its UNORM twin, unable to sample the sRGB format +/// (`R8Unorm_sRGB` on lavapipe, `RG8Unorm_sRGB` on lavapipe, ANV and NVIDIA), answers Filter where +/// the twin filters linearly: the device filters the twin's codes, which the function decodes +/// through Metal's table (`PrecisionNote::SrgbTexelDecode`), as every 8-bit sRGB format it samples +/// itself answers its own filter. +#[test] +fn srgb_formats_held_as_their_unorm_twin_answer_the_twins_filter() { + use metal2vulkan::device::FormatUsage; + use metal2vulkan::metal::format::{srgb_raw_twin, vk_format}; + let mut twins = Vec::new(); + for (stem, desc) in committed_descriptions() { + let (enabled, _) = created(&stem, &desc); + let compile = Device::new(enabled.clone(), DevicePolicy::UNTRUSTED).unwrap(); + let profile = compile.profile(); + let image = ImageFacts { + profile, + formats: &enabled.formats, + storage_multisample: enabled.has(VkFeature::ShaderStorageImageMultisample), + depth_images: crate::image_plan::DepthImageFacts::of(&enabled.driver_facts()), + linear_attachments: false, + }; + for pf in [ + PixelFormat::R8UnormSRGB, + PixelFormat::RG8UnormSRGB, + PixelFormat::RGBA8UnormSRGB, + PixelFormat::BGRA8UnormSRGB, + ] { + let sampled = [FormatUsage::SampledImage].into(); + if vk_format(pf, &sampled, profile).is_ok() { + continue; + } + let Some(twin) = srgb_raw_twin(pf).and_then(|t| vk_format(t, &sampled, profile).ok()) + else { + continue; + }; + let sparse = Err(Missing::Gap(RuntimeGap::SparseHeaps)); + let caps = answers(pf, &image, &any_limits, sparse).capabilities(); + let filters = + profile.supports_format(twin.format, FormatUsage::SampledImageFilterLinear); + assert_eq!( + caps.contains(FormatCapability::Filter), + filters, + "{stem}: {pf:?}" + ); + twins.push(format!("{stem} {pf:?}")); + } + } + for want in [ + "lavapipe R8UnormSRGB", + "lavapipe RG8UnormSRGB", + "nvidia-rtx5080-laptop RG8UnormSRGB", + "intel-arl-anv RG8UnormSRGB", + ] { + assert!(twins.iter().any(|t| t == want), "{want}: {twins:?}"); + } +} + /// No answer past the Apple GPU's the runtime presents (Apple9): a format Apple's tables list /// answers at most its Apple9 cell on every committed profile, sparse textures taken as made /// (which a profile cannot say), so the M3 Max's measured over-answers, Sparse for `GBGR422`, diff --git a/crates/metal2vulkan-runtime/src/tests/image_plan.rs b/crates/metal2vulkan-runtime/src/tests/image_plan.rs index e8dac4b8d..65853ef3d 100644 --- a/crates/metal2vulkan-runtime/src/tests/image_plan.rs +++ b/crates/metal2vulkan-runtime/src/tests/image_plan.rs @@ -25,7 +25,8 @@ use metal2vulkan::device::{ }; use metal2vulkan::error::{Capability, Feature, Needs, RuntimeDriverDefect, Unsupported}; use metal2vulkan::metal::format::{ - direct_format, srgb_raw_twin, storage_image_choice, storage_view_formats, vk_format, + alpha_in_red, alpha_in_red_format, direct_format, is_depth_stencil, srgb_raw_twin, + storage_image_choice, storage_view_formats, vk_format, FormatEmulation, WordAttachment, }; use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; use metal2vulkan::vk::{ @@ -187,7 +188,11 @@ fn check_plan( } } assert!(supports(FormatUsage::StorageImage) || extended, "{what}"); - assert_eq!(Some(plan.format), direct_format(pf), "{what}"); + // The format's own, or the UNORM twin of an 8-bit sRGB format the device holds no image + let own = direct_format(pf); + assert!( + "{what}" + ); } if plan.usage.contains(ImageUsageFlags::COLOR_ATTACHMENT) { assert!(supports(FormatUsage::ColorAttachment), "{what}"); @@ -314,103 +319,128 @@ fn every_format_and_usage_plans_or_refuses_typed_on_every_profile() { #[test] fn a_usage_the_device_lacks_is_unavailable_not_a_refusal() { - // `RGBA8Unorm_sRGB` is a storage image itself where the device stores and declares - // `R8G8B8A8_SRGB`, through its UNORM alias where the device stores `R8G8B8A8_UNORM`, and + // An 8-bit sRGB texture is a storage image itself where the device stores and declares its + // sRGB format, through its UNORM alias where the device stores the UNORM format (the image's + // own format where it holds the texture in that twin, unable to sample the sRGB one), and // otherwise its write usage is unavailable. let (mut own, mut alias, mut lacking) = (0, 0, 0); - for (name, desc, device) in committed() { - let facts = facts(&desc, &device); - let l = layout(TextureType::Type2D, PixelFormat::RGBA8UnormSRGB, 1, 1); - let usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; - let plan = plan_image(&l, usage, false, &facts).expect(&name); - assert_eq!(plan.format, Format::R8G8B8A8_SRGB, "{name}"); - match storage_image_choice(PixelFormat::RGBA8UnormSRGB, device.profile()) { - Ok(choice) if choice.alias.is_some() => { - alias += 1; - assert!(plan.usage.contains(ImageUsageFlags::STORAGE), "{name}"); - assert_eq!(choice.vk_format, Format::R8G8B8A8_UNORM, "{name}"); - assert!( - plan.view_formats.contains(&Format::R8G8B8A8_UNORM), - "{name}" - ); - let extended = !device - .profile() - .supports_format(Format::R8G8B8A8_SRGB, FormatUsage::StorageImage); - assert_eq!( - plan.flags.contains(ImageCreateFlags::EXTENDED_USAGE), - extended, - "{name}" - ); - assert!(plan.unavailable.is_empty(), "{name}"); - } - Ok(_) => { - own += 1; - assert!(plan.usage.contains(ImageUsageFlags::STORAGE), "{name}"); - assert!( - !plan.flags.contains(ImageCreateFlags::EXTENDED_USAGE), - "{name}" - ); - assert!(plan.unavailable.is_empty(), "{name}"); - } - Err(_) - if storage_view_formats(PixelFormat::RGBA8UnormSRGB, device.profile()) - .is_empty() => - { - lacking += 1; - assert!(!plan.usage.contains(ImageUsageFlags::STORAGE), "{name}"); - assert_eq!(plan.unavailable, TextureUsage::SHADER_WRITE, "{name}"); - } - Err(_) => { - own += 1; - assert!(plan.usage.contains(ImageUsageFlags::STORAGE), "{name}"); - assert!(plan.unavailable.is_empty(), "{name}"); + for (pf, srgb, unorm) in [ + ( + PixelFormat::RGBA8UnormSRGB, + Format::R8G8B8A8_SRGB, + Format::R8G8B8A8_UNORM, + ), + ( + PixelFormat::RG8UnormSRGB, + Format::R8G8_SRGB, + Format::R8G8_UNORM, + ), + (PixelFormat::R8UnormSRGB, Format::R8_SRGB, Format::R8_UNORM), + ] { + for (name, desc, device) in committed() { + let name = format!("{name} {pf:?}"); + let facts = facts(&desc, &device); + let l = layout(TextureType::Type2D, pf, 1, 1); + let usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + let plan = plan_image(&l, usage, false, &facts).expect(&name); + assert!(plan.format == srgb || plan.format == unorm, "{name}"); + match storage_image_choice(pf, device.profile()) { + Ok(choice) if choice.alias.is_some() => { + alias += 1; + assert!(plan.usage.contains(ImageUsageFlags::STORAGE), "{name}"); + assert_eq!(choice.vk_format, unorm, "{name}"); + assert!( + plan.format == unorm || plan.view_formats.contains(&unorm), + "{name}" + ); + let extended = !device + .profile() + .supports_format(plan.format, FormatUsage::StorageImage); + assert_eq!( + plan.flags.contains(ImageCreateFlags::EXTENDED_USAGE), + extended, + "{name}" + ); + assert!(plan.unavailable.is_empty(), "{name}"); + } + Ok(_) => { + own += 1; + assert!(plan.usage.contains(ImageUsageFlags::STORAGE), "{name}"); + assert!( + !plan.flags.contains(ImageCreateFlags::EXTENDED_USAGE), + "{name}" + ); + assert!(plan.unavailable.is_empty(), "{name}"); + } + Err(_) if storage_view_formats(pf, device.profile()).is_empty() => { + lacking += 1; + assert!(!plan.usage.contains(ImageUsageFlags::STORAGE), "{name}"); + assert_eq!(plan.unavailable, TextureUsage::SHADER_WRITE, "{name}"); + } + Err(_) => { + own += 1; + assert!(plan.usage.contains(ImageUsageFlags::STORAGE), "{name}"); + assert!(plan.unavailable.is_empty(), "{name}"); + } } } } assert!( - alias > 0 && own + alias + lacking > 10, + alias > 0 && own + alias + lacking > 30, "{own} {alias} {lacking}" ); } /// A texture of a format no slot both reads and writes on the device, whose written-only -/// binding's view the device stores, takes the storage usage and that view: `BGRA8Unorm_sRGB` on -/// the ANV profiles, whose `B8G8R8A8_UNORM` twin ANV stores without a format for writes alone (no -/// `STORAGE_READ_WITHOUT_FORMAT`, and SPIR-V names no BGRA format), so a slot that only writes it -/// binds (EV RES-all1-anv refused it at dispatch). Where no written-only view serves either, the -/// write stays unavailable. +/// binding's view the device stores, takes the storage usage and that view, so a slot that only +/// writes it binds: on ANV, which reads no storage image without a format, a format SPIR-V names +/// no image format for and no alias view serves (the packed 16-bit formats among them), whose own +/// format ANV stores without one for writes alone. Where no written-only view serves either, the +/// write stays unavailable. `BGRA8Unorm_sRGB`, whose `R8G8B8A8_UNORM` view serves both accesses +/// (`StorageImageClass::SrgbEncodeBgra`), is not such a format on any committed profile. #[test] fn a_written_only_view_serves_where_no_slot_both_reads_and_writes() { - let pf = PixelFormat::BGRA8UnormSRGB; let mut written_only = Vec::new(); for (name, desc, device) in committed() { let facts = facts(&desc, &device); let profile = device.profile(); - let l = layout(TextureType::Type2D, pf, 1, 1); - let usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; - let plan = plan_image(&l, usage, false, &facts).expect(&name); - if storage_image_choice(pf, profile).is_ok() { - continue; + for &pf in PixelFormat::ALL { + let what = format!("{name} {pf:?}"); + let l = layout(TextureType::Type2D, pf, 1, 1); + let usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + let Ok(plan) = plan_image(&l, usage, false, &facts) else { + continue; + }; + if storage_image_choice(pf, profile).is_ok() || is_depth_stencil(pf) { + continue; + } + let views = storage_view_formats(pf, profile); + if views.is_empty() { + assert!(!plan.usage.contains(ImageUsageFlags::STORAGE), "{what}"); + assert!( + plan.unavailable.contains(TextureUsage::SHADER_WRITE), + "{what}" + ); + continue; + } + assert!(plan.usage.contains(ImageUsageFlags::STORAGE), "{what}"); + for view in &views { + assert!( + plan.format == *view || plan.view_formats.contains(view), + "{what}: {plan:?}" + ); + } + assert!( + !plan.unavailable.contains(TextureUsage::SHADER_WRITE), + "{what}" + ); + assert_ne!(pf, PixelFormat::BGRA8UnormSRGB, "{what}"); + written_only.push(what); } - let views = storage_view_formats(pf, profile); - if views.is_empty() { - assert!(!plan.usage.contains(ImageUsageFlags::STORAGE), "{name}"); - assert_eq!(plan.unavailable, TextureUsage::SHADER_WRITE, "{name}"); - continue; - } - assert_eq!(views, [Format::B8G8R8A8_UNORM], "{name}"); - assert_eq!(plan.format, Format::B8G8R8A8_SRGB, "{name}"); - assert!(plan.usage.contains(ImageUsageFlags::STORAGE), "{name}"); - assert!( - plan.view_formats.contains(&Format::B8G8R8A8_UNORM), - "{name}" - ); - assert!(plan.unavailable.is_empty(), "{name}"); - written_only.push(name); } assert!( - written_only.iter().any(|n| n.ends_with("-anv")), - "an ANV profile takes the written-only view: {written_only:?}" + written_only.iter().any(|n| n.contains("-anv ")), + "an ANV profile takes a written-only view: {written_only:?}" ); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index 201cc05bd..beee693f1 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -630,6 +630,8 @@ mod seq_cst_fences; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod shader_stencil; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod shared_exponent_storage; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod single_sample_passes; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod snapshot_reads; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/resolve_rounding.rs b/crates/metal2vulkan-validation/src/runtime_lane/resolve_rounding.rs index 3057b5fee..a10a561c9 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/resolve_rounding.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/resolve_rounding.rs @@ -1393,6 +1393,62 @@ fn a_maps_form_pass_resolves_bgra8_by_metals_rule() { quiet(lane, &messages); } +/// A 4x sRGB texture of `RenderTarget` usage alone, cleared in a pass of no draws that resolves +/// it, resolves to the clear's codes, the bytes Metal stores for that clear (`renders.rs`' +/// `COLOR_CLEARS`): every sample holds the clear, which Metal's rule gives back. The exact resolve +/// reads such an attachment through its UNORM twin's view (`color_resolve.rs`), whatever form the +/// device keeps the clear in. +#[test] +fn cleared_srgb_attachments_resolve_to_the_clear_s_codes() { + let (messages, _cache, lane) = lane(); + let name = lane.device.name().to_owned(); + let side = 64u32; + for (pf, [r, g, b, a], bytes) in [ + ( + PixelFormat::RGBA8UnormSRGB, + [0.5, 0.214, 0.0031308, 1.0], + [0xbc, 0x7f, 0x0a, 0xff], + ), + ( + PixelFormat::BGRA8UnormSRGB, + [0.5, 0.214, 0.0031308, 0.5], + [0x0a, 0x7f, 0xbc, 0x80], + ), + ] { + let texture = |samples: u64| { + let mut d = TextureDescriptor::texture_2d(pf, side.into(), side.into(), false); + if samples > 1 { + d.texture_type = TextureType::Type2DMultisample; + d.sample_count = samples; + } + d.usage = TextureUsage::RENDER_TARGET; + d.resource_options = ResourceOptions::private(); + lane.device.new_texture(&d).unwrap() + }; + let (msaa, resolved) = (texture(4), texture(1)); + let mut pass = RenderPassDescriptor::new(); + let target = &mut pass.color_attachments[0]; + target.texture = Some(msaa); + target.load_action = LoadAction::Clear; + target.clear_color = ClearColor::new(r, g, b, a); + target.store_action = StoreAction::MultisampleResolve; + target.resolve_texture = Some(resolved.clone()); + let command_buffer = lane.queue.command_buffer().unwrap(); + let encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer + .wait_until_completed_for(super::WAIT) + .unwrap(); + assert_eq!(command_buffer.error(), None); + let read = super::renders::blit_read(&lane.device, &resolved, 4); + let wrong = read.chunks(4).filter(|texel| *texel != bytes).count(); + eprintln!("cleared resolve {pf:?} x4 on {name}: {wrong} texels other than the clear's"); + assert_eq!(wrong, 0, "{pf:?} on {name}: {:02x?}", &read[..4]); + } + quiet(lane, &messages); +} + /// The width and height of the cost test's target: a 1080p frame. const FRAME: [u32; 2] = [1920, 1080]; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/shared_exponent_storage.rs b/crates/metal2vulkan-validation/src/runtime_lane/shared_exponent_storage.rs new file mode 100644 index 000000000..c8797dc84 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/shared_exponent_storage.rs @@ -0,0 +1,328 @@ +//! A kernel's storage reads and writes of `RGB9E5Float` on the device the cfg selects, under the +//! validation layer, against Metal's answers (an Apple M3 Max under macOS 27.0.1, our own probe +//! `srgb8`: every texel of 65,536 `float` writes, both accesses, and 65,536 `half` writes, and +//! 16,384 words read). Every device writes and reads it through its `R32_UINT` alias +//! (`StorageImageClass::SharedExponentBits`), where the shader encodes Metal's word: a device's own +//! conversion rounds each mantissa half up, where Metal truncates it. +//! +//! Metal's word for red, green and blue: each channel clamped to `[0, 65408]` (a NaN, a negative +//! value and `-0` 0), the exponent `e = max(⌊log2 m⌋, -16) + 16` of the largest clamped channel +//! `m`, each mantissa the channel times `2^(24 - e)` truncated. A read gives each channel `mantissa +//! · 2^(e - 24)`, exact in `float` and in `half`, and alpha 1. The kernels are the owned fixture +//! `fpv_srgb_storage`'s, which take any `float` storage texture. + +use super::degrade_notices::on_device; +use super::{buffer_with, read_buffer, WAIT}; +use crate::air_library::AirLibrary; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; +use metal2vulkan_devtools::{engine_dir, llvm_assemble}; +use metal2vulkan_runtime::{ + CommandBufferStatus, ComputePipelineState, Device, PipelineOptions, Region, ResourceOptions, + Size, Texture, TextureDescriptor, +}; + +/// The texture's width; its height holds every value. +const WIDTH: u64 = 256; + +/// Metal's word for red, green and blue `rgb` (the module docs). +fn word(rgb: [f32; 3]) -> u32 { + let c = rgb.map(|v| match v.is_nan() || v.is_sign_negative() { + true => 0.0, + false => v.min(65408.0), + }); + let m = c[0].max(c[1]).max(c[2]); + let e = (((m.to_bits() >> 23) as i32).max(111) - 111) as u32; + let scale = 2f64.powi(24 - e as i32); + let mantissa = c.map(|v| ((f64::from(v) * scale).floor() as u32).min(511)); + mantissa[0] | mantissa[1] << 9 | mantissa[2] << 18 | e << 27 +} + +/// The value of `half` bits `h`, exactly (a NaN for a NaN). +fn half_value(h: u16) -> f32 { + let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; + let e = i32::from((h >> 10) & 0x1f); + let m = f32::from(h & 0x3ff); + sign * match e { + 0 => m * 2f32.powi(-24), + 31 if m == 0.0 => f32::INFINITY, + 31 => f32::NAN, + _ => (1024.0 + m) * 2f32.powi(e - 25), + } +} + +/// The texels a write takes, four lanes each: specials, mantissa-step edges of every exponent, +/// and spread random values from `2^-30` to past the clamp. +fn floats() -> Vec<[f32; 4]> { + let specials: [f32; 14] = [ + 0.0, + -0.0, + -1.0, + f32::NAN, + f32::INFINITY, + 65408.0, + 65472.0, + 65536.0, + 2e-5, + 1.0, + 0.5, + f32::from_bits(1), + 2f32.powi(-16), + 2f32.powi(-24), + ]; + let mut out: Vec<[f32; 4]> = specials + .iter() + .flat_map(|&a| { + specials + .iter() + .map(move |&b| [a, b, 0.5 * a + 0.25 * b, 1.0]) + }) + .collect(); + let mut s: u64 = 0x9E37_79B9_7F4A_7C15; + let mut next = || { + s = s + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + s >> 33 + }; + for _ in 0..16384 { + let e = (next() % 48) as i32 - 30; + let big = 2f32.powi(e) * (1.0 + (next() % 4096) as f32 / 4096.0); + let frac = |r: u64| (r % 65536) as f32 / 65536.0; + out.push([ + big, + big * frac(next()), + big * frac(next()) * frac(next()), + 0.5, + ]); + let unit = 2f32.powi(e.clamp(-24, 7)); + let edge = ((next() % 511) as f32 + 0.5) * unit; + out.push([ + edge, + f32::from_bits(edge.to_bits() + 1), + f32::from_bits(edge.to_bits() - 1), + 0.0, + ]); + } + while !out.len().is_multiple_of(WIDTH as usize) { + out.push([0.0; 4]); + } + out +} + +fn state(device: &Device, kernel: &str) -> ComputePipelineState { + let bitcode = llvm_assemble(&engine_dir().join("fpv_srgb_storage.ll")).unwrap(); + let library = device.new_library_with_air(&bitcode).unwrap(); + let function = library.new_function_with_name(kernel).unwrap(); + device + .new_compute_pipeline_state( + &ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())), + &PipelineOptions::default(), + ) + .unwrap() +} + +/// A shared `RGB9E5Float` texture, [`WIDTH`] texels wide and `height` high, that kernels read and +/// write, holding the words `words`. +fn texture(device: &Device, height: u64, words: &[u32]) -> Texture { + let mut d = TextureDescriptor::texture_2d(PixelFormat::RGB9E5Float, WIDTH, height, false); + d.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + d.resource_options = ResourceOptions::shared(); + let texture = device.new_texture(&d).unwrap(); + let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + texture + .replace_region( + Region::new_2d(0, 0, WIDTH, height), + 0, + 0, + &bytes, + WIDTH * 4, + 0, + ) + .unwrap(); + texture +} + +/// `texture`'s words, `height` rows. +fn words_of(texture: &Texture, height: u64) -> Vec { + let mut out = vec![0u8; (WIDTH * height * 4) as usize]; + texture + .get_bytes( + &mut out, + WIDTH * 4, + 0, + Region::new_2d(0, 0, WIDTH, height), + 0, + 0, + ) + .unwrap(); + out.as_chunks::<4>() + .0 + .iter() + .map(|&b| u32::from_le_bytes(b)) + .collect() +} + +/// Run `state` over every texel of `texture` (`height` rows) with `data` at buffer 0, and return +/// buffer 0's bytes. +fn run( + device: &Device, + state: &ComputePipelineState, + texture: &Texture, + height: u64, + data: &[u8], +) -> Vec { + let data_buffer = buffer_with(device, data).unwrap(); + let width = buffer_with(device, &(WIDTH as u32).to_le_bytes()).unwrap(); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(state).unwrap(); + encoder.set_buffer(Some(&data_buffer), 0, 0).unwrap(); + encoder.set_buffer(Some(&width), 0, 1).unwrap(); + encoder.set_texture(Some(texture), 0).unwrap(); + encoder + .dispatch_threadgroups(Size::new(WIDTH / 16, height, 1), Size::new(16, 1, 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); + assert_eq!(command_buffer.error(), None); + read_buffer(&data_buffer, 0, data.len() as u64).unwrap() +} + +/// Every kernel write of the floats, and of every half (each lane its own bit pattern), stores +/// Metal's word, over words of `0xA5A5A5A5`. +#[test] +fn shared_exponent_storage_writes_store_metals_word() { + on_device(|device, _| { + let name = device.name().to_owned(); + let floats = floats(); + let halves: Vec<[u16; 4]> = (0..=u16::MAX) + .map(|h| { + [ + h, + h.wrapping_mul(7).wrapping_add(3), + h.wrapping_mul(13).wrapping_add(5), + 0x3c00, + ] + }) + .collect(); + let mut differ = Vec::new(); + for (kernel, half) in [ + ("fpv_srgb_write", false), + ("fpv_srgb_update", false), + ("fpv_srgb_write_half", true), + ("fpv_srgb_update_half", true), + ] { + let (texels, data): (Vec<[f32; 3]>, Vec) = match half { + false => ( + floats.iter().map(|t| [t[0], t[1], t[2]]).collect(), + floats + .iter() + .flatten() + .flat_map(|v| v.to_bits().to_le_bytes()) + .collect(), + ), + true => ( + halves + .iter() + .map(|t| [0, 1, 2].map(|c| half_value(t[c]))) + .collect(), + halves + .iter() + .flatten() + .flat_map(|h| h.to_le_bytes()) + .collect(), + ), + }; + let height = texels.len() as u64 / WIDTH; + let state = state(device, kernel); + let target = texture(device, height, &vec![0xA5A5_A5A5; texels.len()]); + run(device, &state, &target, height, &data); + let got = words_of(&target, height); + let wrong: Vec<_> = texels + .iter() + .zip(&got) + .filter(|(rgb, w)| word(**rgb) != **w) + .collect(); + eprintln!( + "RGB9E5 write by {kernel} on {name}: {} of {} texels differ from Metal's{}", + wrong.len(), + texels.len(), + wrong.first().map_or(String::new(), |(rgb, w)| format!( + ", e.g. {rgb:?}: {w:#010x}, Metal {:#010x}", + word(**rgb) + )) + ); + if !wrong.is_empty() { + differ.push(format!("{kernel}: {} of {}", wrong.len(), texels.len())); + } + } + assert!( + differ.is_empty(), + "RGB9E5 storage writes not Metal's: {differ:#?}" + ); + }); +} + +/// Every `read_write` read of words of every exponent: each channel exact, alpha 1, `float` and +/// `half`. +#[test] +fn shared_exponent_storage_reads_decode_exactly() { + on_device(|device, _| { + let name = device.name().to_owned(); + let words: Vec = (0..WIDTH as u32 * 4) + .map(|n| (n % 32) << 27 | (n * 37 % 512) | (n * 101 % 512) << 9 | (n * 7 % 512) << 18) + .collect(); + let height = words.len() as u64 / WIDTH; + let source = texture(device, height, &words); + let mut differ = Vec::new(); + for (kernel, half) in [ + ("fpv_srgb_read_write", false), + ("fpv_srgb_read_write_half", true), + ] { + let size = if half { 8 } else { 16 }; + let state = state(device, kernel); + let got = run( + device, + &state, + &source, + height, + &vec![0u8; words.len() * size], + ); + let mut wrong = 0; + for (n, &w) in words.iter().enumerate() { + for c in 0..4usize { + let v = match c { + 3 => 1.0, + _ => ((w >> (9 * c)) & 0x1ff) as f32 * 2f32.powi((w >> 27) as i32 - 24), + }; + let lane = &got[(n * 4 + c) * size / 4..]; + let ok = match half { + true => { + half_value(u16::from_le_bytes([lane[0], lane[1]])).to_bits() + == v.to_bits() + } + false => { + u32::from_le_bytes([lane[0], lane[1], lane[2], lane[3]]) == v.to_bits() + } + }; + wrong += usize::from(!ok); + } + } + eprintln!( + "RGB9E5 read by {kernel} on {name}: {wrong} of {} lanes differ from Metal's", + words.len() * 4 + ); + if wrong > 0 { + differ.push(format!("{kernel}: {wrong}")); + } + } + assert!( + differ.is_empty(), + "RGB9E5 storage reads not Metal's: {differ:#?}" + ); + }); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/srgb_storage.rs b/crates/metal2vulkan-validation/src/runtime_lane/srgb_storage.rs index a7c61cb68..841cb6151 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/srgb_storage.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/srgb_storage.rs @@ -1,7 +1,8 @@ -//! A kernel's storage reads and writes of the 8-bit sRGB formats `RGBA8Unorm_sRGB`, -//! `RGBX8Unorm_sRGB` and `BGRA8Unorm_sRGB` on the device the cfg selects, under the validation -//! layer, against Metal's answers (EV FPV-sr1-m4, an M4 under macOS 27.0.1, our own probe -//! `srgb-storage`). +//! A kernel's storage reads and writes of the 8-bit sRGB formats `R8Unorm_sRGB`, `RG8Unorm_sRGB`, +//! `RGBA8Unorm_sRGB`, `RGBX8Unorm_sRGB` and `BGRA8Unorm_sRGB` on the device the cfg selects, under +//! the validation layer, against Metal's answers (an M4 under macOS 27.0.1, our own +//! probe `srgb-storage`; `R8Unorm_sRGB`, `RG8Unorm_sRGB` and `RGBA8Unorm_sRGB` again on an M3 Max +//! under macOS 27.0.1, our own probe `srgb8`: every texel of the same rule). //! //! Metal's answers, recorded there for the values below: a kernel's write (`access::write` and //! `read_write`, `float4` and `half4`) stores each color channel as its twelve-bit encode (a NaN @@ -10,7 +11,7 @@ //! 255 rounded to nearest even, the X field of `RGBX8Unorm_sRGB` green's byte: every texel equal //! to `pack_float_to_srgb_unorm4x8` of the same values. A read (`read_write`, `float4` and //! `half4`) of code `c` answers its twelve-bit step `k / 4095` correctly rounded (alpha `c / 255`, -//! 1 for `RGBX8Unorm_sRGB`). The tables are Metal's own: the first encode indices are the color +//! 1 for `RGBX8Unorm_sRGB`; a channel the format lacks 0, alpha 1). The tables are Metal's own: the first encode indices are the color //! table's (`bind::color_write_table`), the steps `round(decode(c / 255) * 4095)` of the sRGB //! transfer (every one at least `1.6e-4` of a step from a half step). //! @@ -20,10 +21,12 @@ //! `c` of texel `t` takes value `4t + (c + p) % 4` in pass `p` of 4, so each value reaches each //! channel. The kernels are the owned fixture `fpv_srgb_storage`'s. -use super::degrade_notices::on_device; +use super::degrade_notices::{on_device, on_device_with}; use super::{buffer_with, read_buffer, WAIT}; use crate::air_library::AirLibrary; +use metal2vulkan::metal::format::storage_image_choice; use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use metal2vulkan::pipeline::StorageImageClass; use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ @@ -34,12 +37,39 @@ use metal2vulkan_runtime::{ /// The texture's width; its height holds every value. const WIDTH: u64 = 256; -/// Each format, whether the probe measured its `read_write` access, and the byte of each -/// channel (red, green, blue, alpha) in its texel. -const FORMATS: [(PixelFormat, bool, [usize; 4]); 3] = [ - (PixelFormat::RGBA8UnormSRGB, true, [0, 1, 2, 3]), - (PixelFormat::RGBX8UnormSRGB, true, [0, 1, 2, 3]), - (PixelFormat::BGRA8UnormSRGB, false, [2, 1, 0, 3]), +/// Each format, whether the probe measured its `read_write` access, its texel's bytes, and the +/// byte of each channel (red, green, blue, alpha) in its texel, `None` for a channel it lacks. +const FORMATS: [(PixelFormat, bool, usize, [Option; 4]); 5] = [ + ( + PixelFormat::R8UnormSRGB, + true, + 1, + [Some(0), None, None, None], + ), + ( + PixelFormat::RG8UnormSRGB, + true, + 2, + [Some(0), Some(1), None, None], + ), + ( + PixelFormat::RGBA8UnormSRGB, + true, + 4, + [Some(0), Some(1), Some(2), Some(3)], + ), + ( + PixelFormat::RGBX8UnormSRGB, + true, + 4, + [Some(0), Some(1), Some(2), Some(3)], + ), + ( + PixelFormat::BGRA8UnormSRGB, + false, + 4, + [Some(2), Some(1), Some(0), Some(3)], + ), ]; /// The byte of each twelve-bit index: the largest whose first encode index (the color table's @@ -183,9 +213,14 @@ fn state(device: &Device, kernel: &str) -> ComputePipelineState { .unwrap() } -/// A shared texture of `pf`, [`WIDTH`] texels wide and `height` high, that kernels read and -/// write, holding `bytes` where given. -fn texture(device: &Device, pf: PixelFormat, height: u64, bytes: Option<&[u8]>) -> Texture { +/// A shared texture of `pf` (`size` bytes a texel), [`WIDTH`] texels wide and `height` high, that +/// kernels read and write, holding `bytes` where given. +fn texture( + device: &Device, + (pf, size): (PixelFormat, u64), + height: u64, + bytes: Option<&[u8]>, +) -> Texture { let mut d = TextureDescriptor::texture_2d(pf, WIDTH, height, false); d.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; d.resource_options = ResourceOptions::shared(); @@ -197,7 +232,7 @@ fn texture(device: &Device, pf: PixelFormat, height: u64, bytes: Option<&[u8]>) 0, 0, bytes, - WIDTH * 4, + WIDTH * size, 0, ) .unwrap(); @@ -205,13 +240,13 @@ fn texture(device: &Device, pf: PixelFormat, height: u64, bytes: Option<&[u8]>) texture } -/// `texture`'s bytes, `height` rows. -fn bytes_of(texture: &Texture, height: u64) -> Vec { - let mut out = vec![0u8; (WIDTH * height * 4) as usize]; +/// `texture`'s bytes (`size` a texel), `height` rows. +fn bytes_of(texture: &Texture, size: u64, height: u64) -> Vec { + let mut out = vec![0u8; (WIDTH * height * size) as usize]; texture .get_bytes( &mut out, - WIDTH * 4, + WIDTH * size, 0, Region::new_2d(0, 0, WIDTH, height), 0, @@ -268,75 +303,100 @@ fn write_values(half: bool) -> Vec<(f32, Vec)> { /// each texel's (the X field of `RGBX8Unorm_sRGB` green's byte), over bytes of `0xA5`. #[test] fn srgb_storage_writes_store_metals_codes() { + on_device(|device, _| writes_store_metals_codes(device)); +} + +/// [`srgb_storage_writes_store_metals_codes`] on the device made without its storage accesses +#[test] +fn srgb_storage_writes_through_rgba8_store_metals_codes() { + on_device_with( + |options| { + options.withheld_features.extend([ + VkFeature::ShaderStorageImageReadWithoutFormat, + VkFeature::ShaderStorageImageWriteWithoutFormat, + ]); + }, + |device, _| { + let profile = device.compile_device().profile(); + let choice = storage_image_choice(PixelFormat::BGRA8UnormSRGB, profile).unwrap(); + assert_eq!(choice.class, StorageImageClass::SrgbEncodeBgra); + writes_store_metals_codes(device); + }, + ); +} + +fn writes_store_metals_codes(device: &Device) { let bytes = encode_bytes(); - on_device(|device, _| { - let name = device.name().to_owned(); - let mut differ = Vec::new(); - for (pf, read_write, at) in FORMATS { - let rgbx = pf == PixelFormat::RGBX8UnormSRGB; - let kernels: &[(&str, bool)] = match read_write { - true => &[ - ("fpv_srgb_write", false), - ("fpv_srgb_update", false), - ("fpv_srgb_write_half", true), - ("fpv_srgb_update_half", true), - ], - false => &[("fpv_srgb_write", false), ("fpv_srgb_write_half", true)], - }; - for &(kernel, half) in kernels { - let state = state(device, kernel); - let list = write_values(half); - let texels = list.len() / 4; - let height = (texels as u64).div_ceil(WIDTH); - let cells = (WIDTH * height) as usize; - let size = list[0].1.len(); - let (mut wrong, mut example) = (0, None); - for pass in 0..4 { - let entry = |t: usize, c: usize| &list[4 * t + (c + pass) % 4]; - let mut data = vec![0u8; cells * 4 * size]; - for t in 0..texels { - for c in 0..4 { - let at = (4 * t + c) * size; - data[at..at + size].copy_from_slice(&entry(t, c).1); - } + let name = device.name().to_owned(); + let mut differ = Vec::new(); + for (pf, read_write, texel, at) in FORMATS { + let rgbx = pf == PixelFormat::RGBX8UnormSRGB; + let kernels: &[(&str, bool)] = match read_write { + true => &[ + ("fpv_srgb_write", false), + ("fpv_srgb_update", false), + ("fpv_srgb_write_half", true), + ("fpv_srgb_update_half", true), + ], + false => &[("fpv_srgb_write", false), ("fpv_srgb_write_half", true)], + }; + for &(kernel, half) in kernels { + let state = state(device, kernel); + let list = write_values(half); + let texels = list.len() / 4; + let height = (texels as u64).div_ceil(WIDTH); + let cells = (WIDTH * height) as usize; + let size = list[0].1.len(); + let (mut wrong, mut example) = (0, None); + for pass in 0..4 { + let entry = |t: usize, c: usize| &list[4 * t + (c + pass) % 4]; + let mut data = vec![0u8; cells * 4 * size]; + for t in 0..texels { + for c in 0..4 { + let at = (4 * t + c) * size; + data[at..at + size].copy_from_slice(&entry(t, c).1); } - let target = texture(device, pf, height, Some(&vec![0xA5u8; cells * 4])); - run(device, &state, &target, height, &data); - let got = bytes_of(&target, height); - for t in 0..texels { - let mut want = [0u8; 4]; - for (c, byte) in at.into_iter().enumerate() { + } + let fill = vec![0xA5u8; cells * texel]; + let target = texture(device, (pf, texel as u64), height, Some(&fill)); + run(device, &state, &target, height, &data); + let got = bytes_of(&target, texel as u64, height); + for t in 0..texels { + let mut want = [0u8; 4]; + for (c, byte) in at.into_iter().enumerate() { + if let Some(byte) = byte { want[byte] = code(&bytes, entry(t, c).0, c < 3); } - if rgbx { - want[3] = want[1]; - } - if got[4 * t..4 * t + 4] != want { - wrong += 1; - example.get_or_insert(( - (0..4).map(|c| entry(t, c).0).collect::>(), - got[4 * t..4 * t + 4].to_vec(), - want, - )); - } + } + if rgbx { + want[3] = want[1]; + } + let got = &got[texel * t..texel * (t + 1)]; + if got != &want[..texel] { + wrong += 1; + example.get_or_insert(( + (0..4).map(|c| entry(t, c).0).collect::>(), + got.to_vec(), + want, + )); } } - let example = example.map_or(String::new(), |e| format!(", e.g. {e:?}")); - eprintln!( - "SRGB write {pf:?} by {kernel} on {name}: {wrong} of {} texels differ from \ - Metal's{example}", - 4 * texels - ); - if wrong > 0 { - differ.push(format!("{pf:?} by {kernel}: {wrong} of {}", 4 * texels)); - } + } + let example = example.map_or(String::new(), |e| format!(", e.g. {e:?}")); + eprintln!( + "SRGB write {pf:?} by {kernel} on {name}: {wrong} of {} texels differ from \ + Metal's{example}", + 4 * texels + ); + if wrong > 0 { + differ.push(format!("{pf:?} by {kernel}: {wrong} of {}", 4 * texels)); } } - assert!( - differ.is_empty(), - "sRGB storage writes not Metal's: {differ:#?}" - ); - }); + } + assert!( + differ.is_empty(), + "sRGB storage writes not Metal's: {differ:#?}" + ); } /// Every `read_write` read of every code in every channel of each format the probe read so: @@ -346,19 +406,21 @@ fn srgb_storage_reads_are_metals_table() { on_device(|device, _| { let name = device.name().to_owned(); let mut differ = Vec::new(); - for (pf, read_write, at) in FORMATS { + for (pf, read_write, texel, at) in FORMATS { if !read_write { continue; } let rgbx = pf == PixelFormat::RGBX8UnormSRGB; let codes = |b: u32| [b, 255 - b, (37 * b) & 255, (b + 128) & 255]; - let mut bytes = vec![0u8; 256 * 4]; + let mut bytes = vec![0u8; 256 * texel]; for b in 0..256u32 { for (c, code) in codes(b).into_iter().enumerate() { - bytes[4 * b as usize + at[c]] = code as u8; + if let Some(byte) = at[c] { + bytes[texel * b as usize + byte] = code as u8; + } } } - let source = texture(device, pf, 1, Some(&bytes)); + let source = texture(device, (pf, texel as u64), 1, Some(&bytes)); for (kernel, half) in [ ("fpv_srgb_read_write", false), ("fpv_srgb_read_write_half", true), @@ -369,9 +431,11 @@ fn srgb_storage_reads_are_metals_table() { let mut wrong = 0; for b in 0..256u32 { for (c, code) in codes(b).into_iter().enumerate() { - let (k, d) = match (c, rgbx) { - (3, true) => (1, 1), - (3, false) => (u64::from(code), 255), + // A channel the format lacks reads 0, alpha 1. + let (k, d) = match (c, rgbx, at[c]) { + (3, true, _) | (3, _, None) => (1, 1), + (_, _, None) => (0, 1), + (3, false, Some(_)) => (u64::from(code), 255), _ => (u64::from(super::srgb_step(code)), 4095), }; let lane = &got[(b as usize * 4 + c) * size / 4..]; diff --git a/crates/metal2vulkan/src/bind/color_resolve.rs b/crates/metal2vulkan/src/bind/color_resolve.rs index 2244316dd..4b65e91a7 100644 --- a/crates/metal2vulkan/src/bind/color_resolve.rs +++ b/crates/metal2vulkan/src/bind/color_resolve.rs @@ -50,31 +50,40 @@ //! over the whole viewport from `VertexIndex` 0 to 2 (the sample planes merge's), and a `Fragment` //! entry `main` that reads each of a pixel's samples from its [`ResolveSource`] at //! [`ColorResolveModules::SOURCE_BINDING`] of set [`ColorResolveModules::SET`], resolves each -//! channel by its rule, and writes the result to the color output at `Location` 0 as the float -//! that the resolve texture's format stores as the resolved code: `code / (2^b - 1)` for unorm, +//! channel by its rule, and writes the result to the color output at `Location` 0 as the float that +//! the resolve texture's format stores as the resolved code: `code / (2^b - 1)` for unorm, //! `code / (2^(b-1) - 1)` for snorm, the code's linear value for sRGB (the attachment encodes it), -//! and the float's own bits. A pixel whose samples all hold the same bits, as every pixel inside -//! a primitive does where one invocation writes each covered sample, skips the average: there -//! every rule but the 32-bit float's gives back the sample's code (a 16-bit float's NaN and -0 as -//! +0), so the module writes that code's float, after a small float's grid step and a shared -//! exponent's encode as after an average. The 32-bit float's rule always averages, as its sum -//! rounds; so does a format of unorm and snorm channels alone, whose average costs about what -//! comparing the samples does: on a Radeon 780M, comparing first took 8% off an `RGBA8Unorm` -//! 1080p 4x resolve's cost over a plain store where every pixel's samples matched, and added 14% -//! where one pixel in 16 straddled an edge (`runtime_lane::resolve_rounding`'s cost test). +//! or `code / 255` where the result is written through the raw twin's view +//! ([`ColorResolveFormat::written_raw`]), and the float's own bits. A pixel whose samples all hold +//! the same bits, as every pixel inside a primitive does where one invocation writes each covered +//! sample, skips the average: there every rule but the 32-bit float's gives back the sample's code +//! (a 16-bit float's NaN and -0 as +0), so the module writes that code's float, after a small +//! float's grid step and a shared exponent's encode as after an average. The 32-bit float's rule +//! always averages, as its sum rounds; so does a format of unorm and snorm channels alone, whose +//! average costs about what comparing the samples does: on a Radeon 780M, comparing first took 8% +//! off an `RGBA8Unorm` 1080p 4x resolve's cost over a plain store where every pixel's samples +//! matched, and added 14% where one pixel in 16 straddled an edge +//! (`runtime_lane::resolve_rounding`'s cost test). //! //! - [`ResolveSource::InputAttachment`]: the multisampled attachment as the input attachment of //! index 0 (`InputAttachmentIndex 0`), in its own format, read at each sample. A unorm or snorm //! channel's code is its float times the code's scale, rounded; an sRGB channel's the code whose //! linear value is nearest the float; a float's its bits (a half's as the `float` it reads as). +//! - [`ResolveSource::RawInputAttachment`]: the same attachment viewed in the format's raw twin +//! ([`ColorResolveFormat::raw_format`]: an 8-bit sRGB format's UNORM one), so an sRGB channel's +//! float is its code over 255, whose code is read as a unorm channel's, with no table lookup. +//! Another format's raw twin is itself, and the source reads it as +//! [`ResolveSource::InputAttachment`] does. //! - [`ResolveSource::Planes`]: the attachment's sample planes (`bind::PlanesCopy`), a sampled //! 2D-array view of every layer in the copy format, layer `s` holding sample `s`: each channel's //! code is its bits in the texel `(FragCoord.xy, s)` (a half's, unpacked to its `float`). //! //! Draw it into a render pass whose one color attachment is the resolve texture's single-sampled -//! level and layer in its own format, over the render area, one sample, without blending; for +//! level and layer in [`ColorResolveFormat::written_format`] (its own format, or its raw twin +//! where the result is written raw), over the render area, one sample, without blending; for //! [`ResolveSource::InputAttachment`] the pass's subpass also reads the multisampled attachment as -//! its input attachment 0. +//! its input attachment 0, and for [`ResolveSource::RawInputAttachment`] a view of it in its raw +//! twin. //! //! **Synchronization** (consumer): the samples' writes before the draw's reads, and the resolve //! texture's earlier accesses before its color writes. @@ -206,6 +215,9 @@ pub struct ResolveChannel { pub struct ColorResolveFormat { format: Format, channels: [Option; 4], + /// Whether the result is written through the raw twin's view + /// ([`ColorResolveFormat::written_raw`]). + written_raw: bool, } /// A channel of `rule` at bit `offset`. @@ -272,7 +284,11 @@ impl ColorResolveFormat { Format::E5B9G9R9_UFLOAT_PACK32 => [at(E9, 0), at(E9, 9), at(E9, 18), None], _ => return None, }; - Some(ColorResolveFormat { format, channels }) + Some(ColorResolveFormat { + format, + channels, + written_raw: false, + }) } /// The Vulkan format. @@ -295,6 +311,38 @@ impl ColorResolveFormat { .all(|c| c.rule.resolves(samples)) } + /// The format of the view [`ResolveSource::RawInputAttachment`] reads: an 8-bit sRGB format's + /// UNORM twin, whose floats are the codes over 255; any other format itself. + pub fn raw_format(self) -> Format { + match self.format { + Format::R8_SRGB => Format::R8_UNORM, + Format::R8G8_SRGB => Format::R8G8_UNORM, + Format::R8G8B8A8_SRGB => Format::R8G8B8A8_UNORM, + Format::B8G8R8A8_SRGB => Format::B8G8R8A8_UNORM, + format => format, + } + } + + /// The resolve writing its result through a view of the format's raw twin + /// ([`raw_format`](Self::raw_format)): an sRGB channel's code as an 8-bit unorm code's float, + /// `code / 255`, which the twin's store keeps as the code, in place of the code's linear value, + /// which the format's own store encodes. Another format's is itself. + pub fn written_raw(self) -> ColorResolveFormat { + ColorResolveFormat { + written_raw: self.raw_format() != self.format, + ..self + } + } + + /// The format of the view the result is written through: the raw twin's where + /// [`written_raw`](Self::written_raw), else the format. + pub fn written_format(self) -> Format { + match self.written_raw { + true => self.raw_format(), + false => self.format, + } + } + /// Whether the channels share an exponent (`RGB9E5Float`'s, at bits 27 to 31). fn shared_exponent(self) -> bool { self.channels @@ -319,6 +367,9 @@ impl ColorResolveFormat { pub enum ResolveSource { /// The multisampled attachment, as input attachment 0. InputAttachment, + /// The multisampled attachment, as input attachment 0, viewed in its format's raw twin + /// ([`ColorResolveFormat::raw_format`]). + RawInputAttachment, /// The attachment's sample planes, viewed in their copy format. Planes(PlanesCopy), } @@ -506,15 +557,26 @@ struct SrgbTables { linear: GlobalId, /// [`SRGB_RESOLVE_THRESHOLDS`]. thresholds: GlobalId, - /// Each code's linear value as an `f32`: what the attachment encodes as the code. - decoded: GlobalId, + /// Each code's linear value as an `f32`: what the attachment encodes as the code. Declared + /// only where the module writes an sRGB channel's linear value (not + /// [`ColorResolveFormat::written_raw`]). + decoded: Option, /// The `f32` midway between each code's linear value and the next code's: an input - /// attachment's float is the code of the midpoints at or below it. - midpoints: GlobalId, + /// attachment's float is the code of the midpoints at or below it. Declared only where the + /// module reads an sRGB attachment's floats ([`ResolveSource::InputAttachment`]). + midpoints: Option, } impl SrgbTables { - fn declare(b: &mut ModuleBuilder, t: Types) -> BResult { + /// The tables of `format`'s module reading `source`: [`SrgbTables::midpoints`] among them + /// where it reads an sRGB attachment's floats, and [`SrgbTables::decoded`] where it writes + /// linear values. + fn declare( + b: &mut ModuleBuilder, + t: Types, + format: ColorResolveFormat, + source: ResolveSource, + ) -> BResult { let linear = table( b, t.u32_, @@ -527,21 +589,27 @@ impl SrgbTables { t.u32_, SRGB_RESOLVE_THRESHOLDS.iter().map(|&v| u64::from(v)), )?; - let decoded = table( - b, - t.f32_, - t.u32_, - (0..256).map(|k| u64::from((srgb_decode(k) as f32).to_bits())), - )?; - let midpoints = table( - b, - t.f32_, - t.u32_, - (0..255).map(|k| { - let mid = (srgb_decode(k) + srgb_decode(k + 1)) / 2.0; - u64::from((mid as f32).to_bits()) - }), - )?; + let decoded = match format.written_raw { + true => None, + false => Some(table( + b, + t.f32_, + t.u32_, + (0..256).map(|k| u64::from((srgb_decode(k) as f32).to_bits())), + )?), + }; + let midpoints = match source == ResolveSource::InputAttachment { + true => Some(table( + b, + t.f32_, + t.u32_, + (0..255).map(|k| { + let mid = (srgb_decode(k) + srgb_decode(k + 1)) / 2.0; + u64::from((mid as f32).to_bits()) + }), + )?), + false => None, + }; Ok(SrgbTables { linear, thresholds, @@ -551,6 +619,26 @@ impl SrgbTables { } } +/// The float an sRGB channel's resolved `code` (a `uint`) is written as: its linear value, which +/// the format's store encodes as the code, or, written through the raw twin (`tables` without +/// [`SrgbTables::decoded`]), `code / 255`, which the twin's store keeps as the code, as an 8-bit +/// unorm channel's. +fn srgb_written( + f: &mut FunctionBuilder<'_>, + t: Types, + tables: SrgbTables, + code: Value, +) -> BResult { + match tables.decoded { + Some(decoded) => element(f, decoded, code), + None => { + let x = f.convert(ConvOp::ConvertUToF, code, t.f32_)?; + let scale = float(f, t, (1.0 / 255.0f64) as f32)?; + f.binary(BinOp::FMul, x, scale) + } + } +} + /// The element of the `Private` array `table` at `index`. fn element(f: &mut FunctionBuilder<'_>, table: GlobalId, index: Value) -> BResult { let base = f.module().global_value(table)?; @@ -690,7 +778,16 @@ fn code( | ResolveRule::Float16 | ResolveRule::SmallFloat { .. } | ResolveRule::SharedExponent => f.convert(ConvOp::Bitcast, lane, t.u32_), - ResolveRule::Unorm { .. } | ResolveRule::HalfUnorm { .. } => { + ResolveRule::Srgb if source != ResolveSource::RawInputAttachment => { + let midpoints = srgb + .and_then(|tables| tables.midpoints) + .ok_or(crate::spirv::error::BuildError::IdSpaceExhausted)?; + let estimate = srgb_estimate(f, t, lane)?; + corrected_rank(f, t, midpoints, lane, estimate, BinOp::FOrdGreaterThanEqual) + } + // Read through the raw twin, an sRGB channel's float is its code over 255: an 8-bit unorm + // code's. + ResolveRule::Unorm { .. } | ResolveRule::HalfUnorm { .. } | ResolveRule::Srgb => { let scale = float(f, t, ((1u64 << bits) - 1) as f32)?; let half = float(f, t, 0.5)?; let x = f.binary(BinOp::FMul, lane, scale)?; @@ -703,18 +800,6 @@ fn code( let x = f.glsl(GlslOp::Round, &[x])?; f.convert(ConvOp::ConvertFToS, x, t.i32_) } - ResolveRule::Srgb => { - let tables = srgb.ok_or(crate::spirv::error::BuildError::IdSpaceExhausted)?; - let estimate = srgb_estimate(f, t, lane)?; - corrected_rank( - f, - t, - tables.midpoints, - lane, - estimate, - BinOp::FOrdGreaterThanEqual, - ) - } } } @@ -870,7 +955,7 @@ fn resolve( estimate, BinOp::UGreaterThanEqual, )?; - element(f, tables.decoded, code) + srgb_written(f, t, tables, code) } ResolveRule::HalfUnorm { .. } => resolve_half_unorm(f, t, bits, codes), ResolveRule::Float32 => { @@ -1218,7 +1303,7 @@ fn resolve_alike( } ResolveRule::Srgb => { let tables = srgb.ok_or(crate::spirv::error::BuildError::IdSpaceExhausted)?; - element(f, tables.decoded, code)? + srgb_written(f, t, tables, code)? } ResolveRule::Float16 | ResolveRule::SharedExponent => half(f)?, ResolveRule::SmallFloat { mantissa } => { @@ -1347,12 +1432,12 @@ pub fn fragment_typed_module( let mut b = ModuleBuilder::new(); let t = Types::new(&mut b)?; let srgb = if format.srgb() { - Some(SrgbTables::declare(&mut b, t)?) + Some(SrgbTables::declare(&mut b, t, format, source)?) } else { None }; let (image, coord) = match source { - ResolveSource::InputAttachment => { + ResolveSource::InputAttachment | ResolveSource::RawInputAttachment => { let ty = b.ty(Type::Image(ImageType { sampled_type: t.f32_, dim: Dim::SubpassData, diff --git a/crates/metal2vulkan/src/bind/color_resolve/tests.rs b/crates/metal2vulkan/src/bind/color_resolve/tests.rs index 8c2b5e4f5..774b5f6fc 100644 --- a/crates/metal2vulkan/src/bind/color_resolve/tests.rs +++ b/crates/metal2vulkan/src/bind/color_resolve/tests.rs @@ -113,6 +113,31 @@ fn the_srgb_tables_are_metals_measured_ones() { assert_eq!(higher, [804, 1371, 2121, 2569]); } +/// The sources a test reads `format` from: the input attachment, in its own format and, where that +/// is another, its raw twin's, and the sample planes in `copy`. +fn sources(format: ColorResolveFormat, copy: PlanesCopy) -> Vec { + let mut sources = vec![ResolveSource::InputAttachment]; + if format.raw_format() != format.format() { + sources.push(ResolveSource::RawInputAttachment); + } + sources.push(ResolveSource::Planes(copy)); + sources +} + +/// The resolves a test runs of `format`: its result written in its own format and, where its raw +/// twin is another, through the twin ([`ColorResolveFormat::written_raw`]), each from every source +/// ([`sources`]). +fn cases(format: ColorResolveFormat, copy: PlanesCopy) -> Vec<(ColorResolveFormat, ResolveSource)> { + let mut written = vec![format]; + if format.written_raw() != format { + written.push(format.written_raw()); + } + written + .into_iter() + .flat_map(|format| sources(format, copy).into_iter().map(move |s| (format, s))) + .collect() +} + /// The requirements of `m` as serialized. fn needs(m: TypedModule) -> Requirements { crate::spirv::serialize::serialize(m) @@ -145,12 +170,12 @@ fn representatives() -> Vec<(ColorResolveFormat, PlanesCopy)> { } /// The fragment stage needs nothing of a device beyond Vulkan 1.2's shaders, at every sample count -/// its rules hold at and from either source. +/// its rules hold at and from every source. #[test] fn the_fragment_stage_needs_nothing_of_a_device() { for (format, copy) in representatives() { for samples in [2, 4, 8].into_iter().filter(|&n| format.resolves(n)) { - for source in [ResolveSource::InputAttachment, ResolveSource::Planes(copy)] { + for (format, source) in cases(format, copy) { let r = needs(fragment_typed_module(format, samples, source).expect("module")); assert!( r.features.is_empty(), @@ -166,7 +191,7 @@ fn the_fragment_stage_needs_nothing_of_a_device() { fn the_modules_are_valid_on_every_committed_profile() { for (name, profile) in committed_profiles().expect("profiles") { for (format, copy) in representatives() { - for source in [ResolveSource::InputAttachment, ResolveSource::Planes(copy)] { + for (format, source) in cases(format, copy) { for samples in [2, 4] { let m = fragment_typed_module(format, samples, source).expect("module"); let _ = assert_valid(m, &profile); @@ -187,7 +212,7 @@ fn the_modules_come_numbered_and_refuse_another_count() { let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); let device = Device::new(desc, DevicePolicy::default()).expect("device"); let (format, copy) = representatives()[0]; - for source in [ResolveSource::InputAttachment, ResolveSource::Planes(copy)] { + for (format, source) in cases(format, copy) { let modules = color_resolve_modules(&device, format, 4, source, Feature::Format).expect("modules"); assert!(!modules.vertex.is_empty() && !modules.fragment.is_empty()); @@ -232,7 +257,7 @@ fn arithmetic_module( let t = Types::new(&mut b).expect("types"); let srgb = format .srgb() - .then(|| SrgbTables::declare(&mut b, t)) + .then(|| SrgbTables::declare(&mut b, t, format, source)) .transpose() .expect("tables"); let words = super::super::visibility_resolve::words_buffer; @@ -727,6 +752,10 @@ fn sample_words( let offset = u32::from(channel.offset); words[(offset / 32) as usize] |= code << (offset % 32); } + // The raw twin reads an sRGB code as an 8-bit unorm one. + ResolveSource::RawInputAttachment if channel.rule == ResolveRule::Srgb => { + words[component] = read_as(ResolveRule::Unorm { bits: 8 }, code).to_bits() + } _ => words[component] = read_as(channel.rule, code).to_bits(), } } @@ -789,12 +818,20 @@ fn check( let word = u32::from_le_bytes(out[at..at + 4].try_into().expect("word")); let codes: Vec = texel.iter().map(|s| s[component]).collect(); let want = metal(channel.rule, &codes); - let got = stored_as(channel.rule, f32::from_bits(word)); + // Written through the raw twin, an sRGB channel's float is stored as an 8-bit unorm + // one. + let stored = match channel.rule { + ResolveRule::Srgb if format.written_raw => ResolveRule::Unorm { bits: 8 }, + rule => rule, + }; + let got = stored_as(stored, f32::from_bits(word)); assert_eq!( got, want, - "{:?} x{samples} {source:?} component {component}: {codes:x?} wrote {word:#x}", - format.format() + "{:?} written as {:?} x{samples} {source:?} component {component}: {codes:x?} \ + wrote {word:#x}", + format.format(), + format.written_format() ); } } @@ -846,7 +883,7 @@ fn every_pair_of_8_bit_codes(format: Format) { let texels: Vec> = (0..65536u32) .map(|p| vec![[p & 0xff, 0, 0, 0], [p >> 8, 0, 0, 0]]) .collect(); - for source in [ResolveSource::InputAttachment, ResolveSource::Planes(copy)] { + for (resolve, source) in cases(resolve, copy) { check(resolve, 2, source, &texels); } } @@ -867,7 +904,7 @@ fn every_pair_of_snorm_codes_resolves_as_metal() { } /// Random and edge texels of every closed format at 2, 4 and 8 samples (those its rules hold at), -/// through both sources. +/// through every source ([`sources`]). #[test] fn random_texels_of_every_format_resolve_as_metal() { let mut r = SplitMix(0x0052_504c); @@ -906,7 +943,7 @@ fn random_texels_of_every_format_resolve_as_metal() { .collect() }) .collect(); - for source in [ResolveSource::InputAttachment, ResolveSource::Planes(copy)] { + for (resolve, source) in cases(resolve, copy) { check(resolve, samples, source, &texels); } } @@ -1623,7 +1660,8 @@ fn alike_texels( /// A pixel whose samples all hold the same codes resolves as the model of Metal's rules /// ([`metal`]) says, which is the code (`resolve_alike`): every closed format but the shared -/// exponent's (below), at each of 2, 4 and 8 samples its rules hold at, through both sources. +/// exponent's (below), at each of 2, 4 and 8 samples its rules hold at, through every source +/// ([`sources`]). #[test] fn alike_samples_resolve_as_metal() { let mut r = SplitMix(0x0041_4c4b); @@ -1638,7 +1676,7 @@ fn alike_samples_resolve_as_metal() { .filter(|&n| resolve.resolves(n as u32)) { let texels = alike_texels(resolve, samples, &mut r); - for source in [ResolveSource::InputAttachment, ResolveSource::Planes(copy)] { + for (resolve, source) in cases(resolve, copy) { for chunk in texels.chunks(4096) { check(resolve, samples, source, chunk); } @@ -1684,14 +1722,14 @@ fn alike_shared_exponents_resolve_as_metal() { } /// A pixel whose samples all hold the same bits skips the average: on the interpreter, 64 such -/// texels of each representative format at 4 samples take fewer lane-steps, through either +/// texels of each representative format at 4 samples take fewer lane-steps, through every /// source, than the same texels with the last sample's first channel changed; a format that /// always averages (32-bit floats, or unorm and snorm channels alone) takes as many. #[test] fn alike_samples_skip_the_average() { let mut r = SplitMix(0x0041_4c53); for (format, copy) in representatives() { - for source in [ResolveSource::InputAttachment, ResolveSource::Planes(copy)] { + for source in sources(format, copy) { let inputs = if format.shared_exponent() { let words: Vec = (0..64).map(|_| shared_word(&mut r)).collect(); [false, true].map(|change| { @@ -1749,6 +1787,60 @@ fn alike_samples_skip_the_average() { } } +/// The raw twin reads an sRGB format's codes with no table lookup: on the interpreter, 64 random +/// `BGRA8Unorm_sRGB` texels at 4 samples take fewer lane-steps from +/// [`ResolveSource::RawInputAttachment`] than from [`ResolveSource::InputAttachment`], each sample +/// alike and with the last sample's red changed. +#[test] +fn the_raw_twin_reads_srgb_codes_in_fewer_steps() { + let format = ColorResolveFormat::of(Format::B8G8R8A8_SRGB).expect("closed"); + let mut r = SplitMix(0x0052_4157); + let codes: Vec<[u32; 4]> = (0..64) + .map(|_| [0; 4].map(|_: u32| (r.next() as u32) & 0xff)) + .collect(); + for change in [false, true] { + let texels: Vec> = codes + .iter() + .map(|&c| { + let mut last = c; + if change { + last[0] ^= 2; + } + vec![c, c, c, last] + }) + .collect(); + let [read, raw] = [ + ResolveSource::InputAttachment, + ResolveSource::RawInputAttachment, + ] + .map(|source| { + let input = sample_words(format, source, &texels); + dispatch(format, 4, source, input, texels.len()).steps + }); + assert!(raw < read, "changed {change}: {raw} against {read}"); + } +} + +/// Written through the raw twin, an sRGB format's codes go out with no table: the fragment module +/// of `BGRA8Unorm_sRGB` at 4 samples, read through the raw twin, holds no 256-entry table of +/// linear values written raw ([`ColorResolveFormat::written_raw`]), and so is at least that many +/// words smaller than the one written in the format. Lane-steps do not show the saving: the +/// lookup takes as many instructions as the conversion and scale in its place, where the GPU pays +/// for a dynamically indexed `Private` array (`runtime_lane::resolve_rounding`'s cost test). +#[test] +fn the_raw_twin_writes_srgb_codes_with_no_table() { + let format = ColorResolveFormat::of(Format::B8G8R8A8_SRGB).expect("closed"); + let source = ResolveSource::RawInputAttachment; + let [own, raw] = [format, format.written_raw()].map(|format| { + let m = fragment_typed_module(format, 4, source).expect("module"); + crate::spirv::serialize::serialize(m) + .expect("serialize") + .words + .len() + }); + assert!(raw + 256 <= own, "{raw} words against {own}"); +} + // ---- The sRGB codes by estimate and correction ---- /// A kernel whose invocation `i` reads `words` words from `SAMPLES_IN` at `i * words` and writes @@ -1759,7 +1851,10 @@ fn word_kernel( ) -> TypedModule { let mut b = ModuleBuilder::new(); let t = Types::new(&mut b).expect("types"); - let tables = SrgbTables::declare(&mut b, t).expect("tables"); + // Every table: an sRGB format's, read as floats and written in its own format. + let srgb = ColorResolveFormat::of(Format::R8G8B8A8_SRGB).expect("closed"); + let tables = + SrgbTables::declare(&mut b, t, srgb, ResolveSource::InputAttachment).expect("tables"); let buffer = super::super::visibility_resolve::words_buffer; let input = buffer(&mut b, SAMPLES_IN, t.u32_).expect("in"); let output = buffer(&mut b, RESOLVED_OUT, t.u32_).expect("out"); @@ -1916,7 +2011,8 @@ fn the_srgb_codes_are_exact_from_any_estimate_near_the_encode() { let offset = f.convert(ConvOp::Bitcast, w[1], t.f32_)?; let e = srgb_estimate(f, t, x)?; let e = f.binary(BinOp::FAdd, e, offset)?; - corrected_rank(f, t, tables.midpoints, x, e, BinOp::FOrdGreaterThanEqual) + let midpoints = tables.midpoints.expect("midpoints"); + corrected_rank(f, t, midpoints, x, e, BinOp::FOrdGreaterThanEqual) }); let cases: Vec<(f32, u32, f32)> = srgb_floats() .into_iter() diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index 0b9435349..9e7a51f88 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -301,8 +301,8 @@ use crate::bind::plan::resources::{separate_samplers, ResourcePlanner}; use crate::bind::plan::slots::{ address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots, check_sparse_textures, cross_variant, cubic_variant, large_view_candidates, mark_disjoint, - plan_buffer, psb_variant, range_variant, record_specialized, snapshot_forms, srgb_variant, - storage_view_variant, used_uses, ycbcr_variant, + plan_buffer, psb_variant, range_variant, record_specialized, snapshot_forms, srgb_twin_variant, + srgb_variant, storage_view_variant, used_uses, ycbcr_variant, }; use crate::bind::plan::{ AccessClass, BindingPlan, BoundKind, ByteRange, DescriptorWrite, FactorSite, FactorTemplate, @@ -2365,6 +2365,7 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result Result { other => other, }; // A half-float texture the function only writes through its unsigned integer alias - // (`StorageImageClass::HalfBits`): the slot is declared of the alias's numeric type, as - // its neutral is. + // (`StorageImageClass::HalfBits`), and an `RGB9E5Float` texture through `R32_UINT` + // (`StorageImageClass::SharedExponentBits`): the slot is declared of the alias's numeric + // type, as its neutral is. let base = match choice { - Some((c, _)) if c.class == StorageImageClass::HalfBits => ImageHandleClass { - sampled_type: SampledType::Uint, - ..base - }, + Some((c, _)) + if matches!( + c.class, + StorageImageClass::HalfBits | StorageImageClass::SharedExponentBits + ) => + { + ImageHandleClass { + sampled_type: SampledType::Uint, + ..base + } + } _ => base, }; let mut variant = choice @@ -1179,8 +1189,11 @@ impl ResourcePlanner<'_> { && extended.is_none() && (t.access.read || t.access.sample) && swizzled_packed(self.profile, pixel_format, swizzle); - let shader_swizzle = - (accessed || reads_extended || reads_packed) && !swizzle.is_default(); + let reads_srgb_raw = !storage + && (t.access.read || t.access.sample) + && self.swizzles_decoded_srgb(slot, pixel_format, swizzle); + let shader_swizzle = (accessed || reads_extended || reads_packed || reads_srgb_raw) + && !swizzle.is_default(); if shader_swizzle { self.variant.swizzled_storage.insert(slot); } @@ -1204,7 +1217,7 @@ impl ResourcePlanner<'_> { shader_swizzle, } } else { - match self.texel_view(slot, pixel_format, &class, depth_twin, raw)? { + match self.texel_view(pixel_format, &class, depth_twin, raw)? { Some((view, _)) => ImageViewDesc { shader_swizzle, ..view @@ -1228,18 +1241,17 @@ impl ResourcePlanner<'_> { sampled_view(self.profile, pf, class, twin) } - /// The view a binding of texture slot `slot` reads a texture of `pf` through (declared - /// `class`, `twin` for a depth twin's): its sampled view, or for a binding of the raw view - /// (`raw`) that view, `None` for a format without one. Where the device cannot sample an 8-bit - /// sRGB format, whose sampled texture it holds as the format's UNORM twin - /// (`metal::format::srgb_raw_twin`), the twin's sampled view serves the raw binding, and the - /// slot's own binding where the function decodes none of its texels through the device (no - /// `RuntimeFact::SrgbDeviceDecode`), which then reads the view for queries alone; elsewhere the - /// sRGB format's refusal stands. With the view, the format whose sampled view it is (the - /// twin's, where the twin serves). + /// The view a binding of a texture slot reads a texture of `pf` through (declared `class`, + /// `twin` for a depth twin's): its sampled view, or for a binding of the raw view (`raw`) that + /// view, `None` for a format without one. Where the device cannot sample an 8-bit sRGB format, + /// whose sampled texture it holds as the format's UNORM twin (`metal::format::srgb_raw_twin`), + /// the twin's sampled view serves both bindings: the raw codes are the twin's texels, and the + /// slot's own binding is read for queries alone, or, where the function decodes texels through + /// the device's view (`RuntimeFact::SrgbDeviceDecode`), under the slot's + /// `VariantKey::srgb_twins`, whose function decodes what the device samples there. With the + /// view, the format whose sampled view it is (the twin's, where the twin serves). fn texel_view( &self, - slot: SlotRef, pf: PixelFormat, class: &ImageHandleClass, twin: bool, @@ -1251,16 +1263,34 @@ impl ResourcePlanner<'_> { Err(missing) => missing, }; match srgb_raw_twin(pf) { - Some(linear) if raw || !self.has_fact(RuntimeFact::SrgbDeviceDecode { slot }) => self + Some(linear) => self .sampled_view(linear, class, false) .map(|view| Some((view, linear))) .map_err(|_| missing), - _ => Err(missing), + None => Err(missing), } } + /// Whether slot `slot`'s function decodes the raw codes of a texture of `pf` bound there with + /// `swizzle` by Metal's table (`RuntimeFact::SrgbTexture`, an 8-bit sRGB format) where the + /// swizzle moves a code between a color lane and alpha: a view's component mapping would move + /// it before the decode (a color code onto alpha, read as alpha's `c / 255`; alpha's code onto + /// a color lane, decoded through the table), where plain Metal swizzles the decoded texel. The + /// function then decodes the unswizzled texel and swizzles it, every access of the slot alike, + /// under `VariantKey::swizzled_storage`, and the slot's views take no swizzle. A swizzle among + /// the color lanes, or to a constant (0 and 1 decode to themselves), reads the same either way /// and keeps the view's. A format whose codes the device does not hold (an ASTC sRGB format /// it decodes itself, `srgb_raw_on`) is decoded by the device's view, swizzle and all. + fn swizzles_decoded_srgb( + &self, + slot: SlotRef, + pf: PixelFormat, + swizzle: TextureSwizzleChannels, + ) -> bool { + use crate::metal::TextureSwizzle as S; + let color = |s: S| matches!(s, S::Red | S::Green | S::Blue); + let crosses = + color(swizzle.alpha) || [swizzle.red, swizzle.green, swizzle.blue].contains(&S::Alpha); crosses && self.has_fact(RuntimeFact::SrgbTexture { slot }) && srgb_raw_on(pf, self.profile) } @@ -1270,6 +1300,8 @@ impl ResourcePlanner<'_> { /// ([`TexelFormat::OTHER`]) and no bicubic treatment, as a format outside the families. fn decodes_srgb_itself(&self, pf: PixelFormat) -> bool { srgb_raw(pf) && !srgb_raw_on(pf, self.profile) + } + /// The runtime sampler `slot` for a use, with the shape's value checks /// (`metal::sampler::check_sampler`: reduction; address modes, border colors, and LOD /// clamps), or the neutral sampler when the slot is unbound. The write keeps the use's @@ -1634,7 +1666,7 @@ impl ResourcePlanner<'_> { depth_twin, swizzle, .. - }) => match self.texel_view(texture, pixel_format, &class, depth_twin, sampler.raw)? { + }) => match self.texel_view(pixel_format, &class, depth_twin, sampler.raw)? { Some((view, viewed)) => { self.texture_use(texture, &t, false); // A swizzled packed normalized texture's sampled view takes no swizzle where @@ -1642,7 +1674,8 @@ impl ResourcePlanner<'_> { // variant (`texture_write`'s `reads_packed`): its sampler reads the // unswizzled texture's border texel, which the function swizzles. let shader_swizzle = !swizzle.is_default() - && swizzled_packed(self.profile, pixel_format, swizzle); + && (swizzled_packed(self.profile, pixel_format, swizzle) + || self.swizzles_decoded_srgb(texture, pixel_format, swizzle)); if shader_swizzle { self.variant.swizzled_storage.insert(texture); } diff --git a/crates/metal2vulkan/src/bind/plan/slots.rs b/crates/metal2vulkan/src/bind/plan/slots.rs index cb8c6d90f..4a0561360 100644 --- a/crates/metal2vulkan/src/bind/plan/slots.rs +++ b/crates/metal2vulkan/src/bind/plan/slots.rs @@ -278,6 +278,30 @@ pub(crate) fn srgb_variant( .collect() } +/// The slots of `srgb` (`VariantKey::srgb_textures`) at which `shape` binds a texture whose 8-bit +/// sRGB format `profile`'s device cannot sample, which the runtime holds as the format's UNORM twin +/// (`metal::format::srgb_raw_twin`), a format it can: the plan's `VariantKey::srgb_twins`. Its +/// views read the codes, so the function decodes what the device samples there. Derived from the +/// device's format features alone, as the runtime's image plan holds the twin. +pub(crate) fn srgb_twin_variant( + profile: &DeviceProfile, + srgb: &std::collections::BTreeSet, + shape: &BindShape, +) -> std::collections::BTreeSet { + use crate::device::requirements::FormatUsage; + let samples = |pf: metal::PixelFormat| { + metal::format::vk_format(pf, &[FormatUsage::SampledImage].into(), profile).is_ok() + }; + srgb.iter() + .filter(|slot| { + matches!(bound_texture(shape, **slot), Some(TextureShape::Texture { pixel_format, .. }) + if !samples(*pixel_format) + && metal::format::srgb_raw_twin(*pixel_format).is_some_and(samples)) + }) + .copied() + .collect() +} + /// The form each of the snapshot slots `slots` keeps its texels in (`VariantKey::snapshot_textures`, /// `SnapshotForm::of`): by the view the snapshot's copy fetches through, the bound texture's /// sampled view or, at a slot whose raw codes the variant reads (`srgb`, `slots::srgb_variant`), diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 985b9f067..e7c20f2d0 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -188,6 +188,14 @@ pub struct VariantKey { /// the plan of a pipeline compiled under it states it. #[cfg_attr(feature = "serde", serde(default))] pub srgb_textures: BTreeSet, + /// Slots of [`srgb_textures`](Self::srgb_textures) bound to a texture whose 8-bit sRGB format + /// the device cannot sample, which it holds as the format's UNORM twin + /// (`metal::format::srgb_raw_twin`), whose views read the codes (`c / 255`): the accesses the + /// raw codes do not serve exactly (a runtime sampler's sample, a filter the emulation does not + /// reach) sample the twin and decode the device's filtered codes + /// (`LoweringInputs::srgb_twins`). The plan of a pipeline compiled under it states it. + #[cfg_attr(feature = "serde", serde(default))] + pub srgb_twins: BTreeSet, /// Fragment texture slots the draw reads through a snapshot an earlier draw of the same /// primitives took (`LoweringInputs::snapshot_textures`), each with the form the snapshot /// keeps its texels in (`SnapshotForm::of` the slot's bound view): the slots @@ -504,6 +512,7 @@ impl VariantKey { && !self.dropped_vertex_layer && self.storage_view_slots.is_empty() && self.srgb_textures.is_empty() + && self.srgb_twins.is_empty() && self.snapshot_textures.is_empty() && self.ycbcr_textures.is_empty() && self.address_maps.is_empty() @@ -592,6 +601,12 @@ impl VariantKey { .filter(|s| s.stage == stage) .copied() .collect(); + out.srgb_twins = self + .srgb_twins + .iter() + .filter(|s| s.stage == stage) + .copied() + .collect(); out.snapshot_textures = self .snapshot_textures .iter() diff --git a/crates/metal2vulkan/src/lower/sampler/emit.rs b/crates/metal2vulkan/src/lower/sampler/emit.rs index 10c4c5b10..04c5eb579 100644 --- a/crates/metal2vulkan/src/lower/sampler/emit.rs +++ b/crates/metal2vulkan/src/lower/sampler/emit.rs @@ -2566,11 +2566,16 @@ pub(super) fn held_value( }; // An 8-bit sRGB texel's raw code, decoded as Metal decodes it: a gather's lanes are one // channel's, all alpha or all color. - if s.raw() { + if s.raw() || s.srgb_codes { let color = match s.op { SampleOp::Gather { component, .. } => [component != 3; 4], _ => crate::lower::texture::SRGB_TEXEL, }; + // The device's sample of a twin's codes, filtered: decoded through the table, exactly + // where it read one texel. + if !s.raw() { + return crate::lower::texture::srgb_filtered_texel(cx, fb, form, texel, color); + } return crate::lower::texture::srgb_raw_texel(cx, fb, form, texel, color); } // A `half` texel of a slot converts by the bound format's class: a gather's texel as a read's, diff --git a/crates/metal2vulkan/src/lower/sampler/linear.rs b/crates/metal2vulkan/src/lower/sampler/linear.rs index bfb7d1582..31a8a8d57 100644 --- a/crates/metal2vulkan/src/lower/sampler/linear.rs +++ b/crates/metal2vulkan/src/lower/sampler/linear.rs @@ -94,19 +94,12 @@ //! device specializes the module the arithmetic folds to the bound sampler's. A `MirrorClampToEdge` //! axis, which only a runtime sampler states, reflects each tap's index once, `-1 - i` for a //! negative `i`, and clamps it into the level, under pixel and normalized coordinates alike, its -//! constant texel offset placed as on a repeating axis (RRP-probe1-m4 and RRP-probe5-m4, Apple M4: -//! every lane of nearest and linear samples, gathers and depth comparisons of textures 1 to 8 -//! texels wide); the emulation reaches it on a 1D or 2D texture, and the device filters it on a 3D -//! texture or a cube, where no probe measured it ([`Linear::mirror_clamp_reached`]). -//! Argument-buffer samplers are not reached: their textures are heap elements, whose format no -//! specialization states; the device filters them, under the notes. A slot under its 8-bit sRGB -//! variant is (EVs TXN-srgbprobe-m3 and -m4, Metal's samples of `RGBA8Unorm_sRGB` and -//! `BGRA8Unorm_sRGB` through a runtime sampler are its constexpr sampler's of the same state, bit -//! for bit, in 1D, 2D, and 3D): the emulation sums the raw codes fetched through the slot's raw -//! view (`Linear::fetch`) where the word reaches it, and elsewhere the device samples the slot's -//! own binding, the decoding view, under `PrecisionNote::SrgbTexelDecode` ([`decode_when`]). A -//! cube's is inferred from the same equality on the other formats and from its constexpr -//! sampler's raw emulation. +//! view (`Linear::fetch`) where the word reaches it; where the word reads one texel the device +//! samples the raw view through the same sampler, and Metal's table decodes the code, as a +//! constexpr nearest sample's raw read does; elsewhere the device samples the slot's own binding, +//! the decoding view, under `PrecisionNote::SrgbTexelDecode` ([`decode_when`]). A cube's is +//! inferred from the same equality on the other formats and from its constexpr sampler's raw +//! emulation; its word that reads one texel samples the decoding view too. //! //! **Where it is exact**, on the probes: in 1D and 2D for every measured format (a 16-bit //! normalized format's 2D sum on every channel of probes, under `clamp_to_edge`, `repeat`, @@ -225,8 +218,9 @@ pub struct Linear { /// variant: each tap's color lanes become the table's steps (`srgb_raw_tap`), and the exact /// routine sums them on the sRGB grids (`BicubicTexels::SRGB`), whatever the device. Through a /// runtime sampler slot it does so where the word reaches the emulation, its taps fetched - /// through [`fetch`](Self::fetch), the slot's raw view; the sample's own binding is the - /// decoding view, which its device arm samples elsewhere. + /// through [`fetch`](Self::fetch), the slot's raw view, which its device arm samples where the + /// word reads one texel; the sample's own binding is the decoding view, which its device arm + /// samples elsewhere. pub raw: bool, /// A cube's sample (`cube`), with its face position's routines: its taps are fetched from the /// faces of the slot's 2D-array view (its raw view where `raw`), its state's addressing is its @@ -801,11 +795,17 @@ pub(super) fn device_when(l: &Linear) -> Vec { } /// Where a raw emulation `l` through a runtime sampler slot hands its sample to the device's -/// decoding view (`PrecisionNote::SrgbTexelDecode`): wherever the word does not reach the -/// emulation, a word that reads one texel included. Never for another emulation. +/// decoding view (`PrecisionNote::SrgbTexelDecode`): where the word does not reach the emulation +/// and filters, since a word that reads one texel samples the slot's raw view ([`Linear::fetch`]); +/// a cube's (no such view) wherever the word does not reach it. Never for another emulation. pub(super) fn decode_when(l: &Linear) -> Vec { - match (&l.state, l.raw) { - (LinearState::Slot { sampler, .. }, true) => unreached(l, *sampler), + match (&l.state, l.raw, &l.cube) { + // A word that reads one texel samples the raw view ([`emit`], [`emit_shared`]): the + // device decodes only where the word filters too. + (LinearState::Slot { sampler, .. }, true, None) => { + both(&unreached(l, *sampler), &word_filters(*sampler)) + } + (LinearState::Slot { sampler, .. }, true, Some(_)) => unreached(l, *sampler), _ => Vec::new(), } } @@ -958,8 +958,9 @@ fn reaches(s: &SamplerState) -> bool { /// binding's sampled image (a `vec4` of `f32`), converted as a sample's for a `half` result: a /// branch on the slot's `TexelFormat` specialization, so only one of them runs, and once a device /// specializes the module the other is dead. A raw emulation runs alone through a constexpr -/// sampler, and through a runtime sampler where its word reaches it, the device's sample of the -/// binding's decoding view elsewhere. Each arm loads the binding's sampled image, which is consumed +/// sampler, and through a runtime sampler where its word reaches it; elsewhere the device samples +/// the slot's raw view where the word reads one texel, decoded through Metal's table, and the +/// binding's decoding view otherwise. Each arm loads the binding's sampled image, which is consumed /// in the block that loads it, or a cube's emulation the slot's 2D-array view at `plane`, the /// direction the device's sample reads (its ties broken as Metal breaks them). A `half` result is /// the held `half` texel. @@ -1073,6 +1074,19 @@ pub(super) fn emit( device(fb, si)? } }; + // Under the slot's twin variant the device sampled the codes: decoded through the table, + // exactly where the sampler read one texel. + let x = match s.srgb_codes { + true => { + let four = crate::lower::texture::TexelForm { + lanes: 4, + conv: crate::lower::texture::TexelConv::F32, + }; + let color = crate::lower::texture::SRGB_TEXEL; + crate::lower::texture::srgb_filtered_texel(cx, fb, four, x, color)? + } + false => x, + }; let x = match (h, float) { (Some(HalfArm::Class(h)), _) => { let lanes = super::emit::sample_lanes(cx, fb, s)?; @@ -1095,13 +1109,57 @@ pub(super) fn emit( }; Ok(ArmEnd::FallThrough(vec![x])) }); - let Merged(merged) = fb.if_(cx, measured, emulated, Some(filtered))?; + // A raw emulation's device arm, where the runtime sampler's word reads one texel (nearest + // minification and magnification, no linear mip filter, isotropic): the device's sample of the + // slot's raw view, through the same sampler, reads that texel's code, which Metal's table + // decodes exactly, as a constexpr nearest sample's raw read does. Every other word samples the + // decoding view ([`decode_when`]). Under the slot's twin variant the decoding view holds the + // codes already. + let device_arm: ArmFn<'_, EmitCx<'_>> = match (l.raw, word, &l.cube, s.srgb_codes) { + (true, Some(word), None, false) => { + let (Some(raw_key), Some(form)) = (l.fetch, s.texel) else { + return Err(cx.fail("a raw sample's device arm without its raw view")); + }; + let Some(&(raw_binding, _)) = cx.decl.families.sampler.combined.get(&raw_key) else { + return Err(cx.fail(format!("raw binding {raw_key:?} is not declared"))); + }; + let raw: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { + let si = raw_binding.sampled_image(fb)?; + let x = device(fb, si)?; + let color = crate::lower::texture::SRGB_TEXEL; + let x = crate::lower::texture::srgb_raw_texel(cx, fb, form, x, color)?; + Ok(ArmEnd::FallThrough(vec![x])) + }); + one_texel_arm(word, raw, filtered) + } + _ => filtered, + }; + let Merged(merged) = fb.if_(cx, measured, emulated, Some(device_arm))?; match merged[..] { [x] => Ok(x), _ => Err(cx.fail("a linear sample's branch without its texel")), } } +/// A raw emulation's device arm through runtime sampler word `word`: `raw`'s texel (the device's +/// sample of the slot's raw view, decoded through Metal's table) where the word reads one texel +/// (`compared::one_texel`), else `filtered`'s (the device's sample of the decoding view). +fn one_texel_arm<'a, 'c: 'a>( + word: SValue, + raw: ArmFn<'a, EmitCx<'c>>, + filtered: ArmFn<'a, EmitCx<'c>>, +) -> ArmFn<'a, EmitCx<'c>> { + Box::new(move |fb, cx| { + let t = Tys::new(fb)?; + let (one, _) = super::compared::one_texel(fb, &t, word)?; + let Merged(merged) = fb.if_(cx, one, raw, Some(filtered))?; + match merged[..] { + [x] => Ok(ArmEnd::FallThrough(vec![x])), + _ => Err(cx.fail("a raw sample's device arm without its texel")), + } + }) +} + /// The gathered texel of cube gather `s` by `g` (`cube`) of channel `component`, along `plane` (the /// direction, its ties broken as Metal breaks them), a comparison's against reference `dref`. An /// integer result's and a raw gather's are the emulation's alone. A `float` or `half` result's, a @@ -1239,7 +1297,34 @@ pub(super) fn emit_shared( }; Ok(ArmEnd::FallThrough(vec![x])) }); - let Merged(merged) = fb.if_(cx, measured, emulated, Some(filtered))?; + // A raw emulation's device arm reads each arm's raw view where the word reads one texel, as + // [`emit`]'s does; a null arm's zero decodes to zero. + let device_arm: ArmFn<'_, EmitCx<'_>> = match (l.raw, word, &l.cube, s.srgb_codes) { + (true, Some(word), None, false) => { + let (Some(_), Some(form)) = (l.fetch, s.texel) else { + return Err(cx.fail("a shared raw sample's device arm without its raw view")); + }; + let raw: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| { + let read = |cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, a: &Sampling| { + let si = c.fetch_sampled_image(cx, fb, a)?; + Ok(vec![device(fb, si)?]) + }; + let null = |_: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>| { + let z = fb.module().constant(Constant::Null { ty: t.vec4 })?; + Ok(vec![value(fb, z)?]) + }; + let [x] = c.each(cx, fb, &read, &null)?[..] else { + return Err(cx.fail("a shared raw sample's device texel")); + }; + let color = crate::lower::texture::SRGB_TEXEL; + let x = crate::lower::texture::srgb_raw_texel(cx, fb, form, x, color)?; + Ok(ArmEnd::FallThrough(vec![x])) + }); + one_texel_arm(word, raw, filtered) + } + _ => filtered, + }; + let Merged(merged) = fb.if_(cx, measured, emulated, Some(device_arm))?; match merged[..] { [x] => Ok(x), _ => Err(cx.fail("a linear sample's branch without its texel")), diff --git a/crates/metal2vulkan/src/lower/sampler/mod.rs b/crates/metal2vulkan/src/lower/sampler/mod.rs index 5061d81ea..be36c2d83 100644 --- a/crates/metal2vulkan/src/lower/sampler/mod.rs +++ b/crates/metal2vulkan/src/lower/sampler/mod.rs @@ -709,6 +709,11 @@ pub struct Sampling { /// device's samples at explicit levels, answers ([`anisotropic`]): through a constexpr /// sampler always, through a runtime sampler slot where its word states anisotropy. pub anisotropic: Option, + /// The slot's own binding views the codes of an 8-bit sRGB texture held as its UNORM twin + /// (`LoweringInputs::srgb_twins`), where the access would keep the device's decode: the + /// device's sample there, filtered codes, decodes through Metal's table + /// (`texture::srgb_filtered_texel`), exactly where it read one texel. + pub srgb_codes: bool, } /// The declared result of a sampling whose slot's variant binds a texture of another numeric @@ -1150,6 +1155,7 @@ impl Sampling { 0 } _ if self.raw() => crate::lower::texture::SRGB_RAW_WORDS, + _ if self.srgb_codes => crate::lower::texture::SRGB_FILTERED_WORDS, // A heap color texture's call reads the class its handle carries first. (_, Some(f)) if f.conv == crate::lower::texture::TexelConv::F16 => { let class = match self.source { @@ -1190,11 +1196,20 @@ impl Sampling { _ => 0, }; // The emulation beside the device's sample, or gather, and a native class's snapped - // coordinate. - let linear = self - .linear - .as_ref() - .map_or(0, |l| l.words() + l.native_words()) + // coordinate; a runtime sampler's raw emulation's device arm where its word reads one + // texel: the word's test and branch, the raw view's sampled image and sample, and the + // table's decode (`linear::emit`). + let one_texel = match &self.linear { + Some(l) if l.raw && l.word_state() && l.cube.is_none() && !self.srgb_codes => { + RAW_TEXEL_ARM_WORDS + crate::lower::texture::SRGB_RAW_WORDS + } + _ => 0, + }; + let linear = one_texel + + self + .linear + .as_ref() + .map_or(0, |l| l.words() + l.native_words()) + self .cube_gather .as_ref() @@ -1281,6 +1296,12 @@ impl Sampling { /// selects of each lane's source (`extended`'s). const SWIZZLE_WORDS: u32 = extended::SWIZZLE_WORDS; +/// The estimated words of a runtime sampler's raw emulation's device arm where its word reads one +/// texel, but the table's decode: the word's filter test and mip field, the branch and its merge, +/// and the raw view's sampled image and sample (`linear::emit`, +/// `the_raw_estimate_bounds_its_emission`). +const RAW_TEXEL_ARM_WORDS: u32 = 64 + 64; + /// The estimated words of setting an access's lanes to the constants Metal reads /// (`texture::constant_lanes`): per lane its extraction and two selections (the slot's tests are /// specialization constants), the construction, and their constants, at most 8 words each. diff --git a/crates/metal2vulkan/src/lower/sampler/select.rs b/crates/metal2vulkan/src/lower/sampler/select.rs index 3ec4addab..e89f8803e 100644 --- a/crates/metal2vulkan/src/lower/sampler/select.rs +++ b/crates/metal2vulkan/src/lower/sampler/select.rs @@ -1829,21 +1829,32 @@ fn select_one( // Or natively (`VkProperty::DeviceSampling`), whose are the device's: every sample and // gather is then the device's answer, which the module records. let metal_sampler = cx.profile.device_samples(); + // Whether the device's sampler is Metal's own (`VkProperty::MetalSampler` alone), whose sRGB + // decode is Metal's table. + let metal_unit = cx + .profile + .fields() + .enabled + .properties + .contains(&crate::device::requirements::VkProperty::MetalSampler); if metal_sampler && matches!(op, SampleOp::Sample { .. } | SampleOp::Gather { .. }) { cx.families.sampler.device_sampling = true; } // An 8-bit sRGB texel Metal decodes from its raw code: a nearest sample's, a pixel fetch's, a // `half` gather's, an emulated cube gather's (a `float` one's too), a `float` gather's on a - // device whose own decode is not Metal's (Metal's own sampler gathers the table's decode, EV - // FRT4-rpk2-mvk4), a bicubic sample's, and an emulated linear sample's through a constexpr - // sampler, through the slot's raw view under its variant, decoded exactly (the filters sum the - // table's steps). A runtime sampler's emulated linear sample reads the raw codes where its word - // reaches the emulation, and the device's decoding view elsewhere (`word_raw`). An LOD query - // reads no texel. + // device whose sampler is not Metal's own, whatever the sampling policy (Metal's own sampler + // gathers the table's decode; a gather reads one texel per lane, so the + // table's decode is exact and cheap), a bicubic sample's, and an emulated linear sample's + // through a constexpr sampler, through the slot's raw view under its variant, decoded exactly + // (the filters sum the table's steps). A runtime sampler's emulated linear sample reads the raw + // codes where its word reaches the emulation or reads one texel (not a cube's there), and the + // device's decoding view elsewhere (`word_raw`). Under the slot's twin variant (a bound format the device cannot sample) the + // device's view reads the codes, so an access the raw codes do not serve decodes what the + // device samples there (`srgb_codes`). An LOD query reads no texel. let constant = linear .as_ref() .is_some_and(|l| matches!(l.state, super::linear::LinearState::Constant { .. })); - let (raw, word_raw) = match form { + let (raw, word_raw, srgb_codes) = match form { Some(f) if matches!(f.conv, TexelConv::F16 | TexelConv::F32) => { use crate::lower::texture::SrgbReach; let reach = match &op { @@ -1854,19 +1865,21 @@ fn select_one( _ => SrgbReach::Device, }, SampleOp::Gather { .. } - if f.conv == TexelConv::F16 || cube_gather.is_some() || !metal_sampler => + if f.conv == TexelConv::F16 || cube_gather.is_some() || !metal_unit => { SrgbReach::Raw } _ => SrgbReach::Device, }; let read = crate::lower::texture::srgb_texels(cx, image, shape, reach)?; + let codes = reach != SrgbReach::Raw && crate::lower::texture::srgb_twin(cx, image)?; ( read && reach == SrgbReach::Raw, read && reach == SrgbReach::Word, + codes, ) } - _ => (false, false), + _ => (false, false, false), }; let cube_gather = cube_gather.map(|g| super::linear::CubeGather { raw, ..g }); // A cube gather's corner rule, where the bound format's class states none, is the device's @@ -2510,6 +2523,7 @@ fn select_one( swizzle, offset_base, anisotropic, + srgb_codes, }; // The sampling routines it calls, for the census. super::routine::note(&mut cx.families.sampler, &sampling); diff --git a/crates/metal2vulkan/src/lower/sampler/shared.rs b/crates/metal2vulkan/src/lower/sampler/shared.rs index 71508da3d..ac43cf51e 100644 --- a/crates/metal2vulkan/src/lower/sampler/shared.rs +++ b/crates/metal2vulkan/src/lower/sampler/shared.rs @@ -74,6 +74,18 @@ impl Candidates<'_> { binding(cx, a)?.0.sampled_image(fb) } + /// The sampled image of arm sampling `a`'s binding its linear taps are fetched through + /// (`Linear::fetch`; its own binding where it names none), made in the open block: a raw + /// emulation's raw view, through the arm's runtime sampler. + pub(super) fn fetch_sampled_image( + &self, + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + a: &Sampling, + ) -> BResult { + fetch_binding(cx, a)?.sampled_image(fb) + } + /// The image of arm sampling `a`'s binding, loaded in the open block: for an emulated linear /// comparison the binding its taps are fetched through (`Linear::fetch`). pub(super) fn image( @@ -82,15 +94,7 @@ impl Candidates<'_> { fb: &mut FunctionBuilder<'_>, a: &Sampling, ) -> BResult { - let key = match (&a.linear, a.source) { - (Some(super::linear::Linear { fetch: Some(k), .. }), _) => *k, - (_, Source::Combined(key)) => key, - _ => return Err(cx.fail("a shared sampling of a heap element")), - }; - match cx.decl.families.sampler.combined.get(&key) { - Some(&(b, _)) => b.image(fb), - None => Err(cx.fail(format!("combined binding {key:?} is not declared"))), - } + fetch_binding(cx, a)?.image(fb) } } @@ -105,6 +109,19 @@ fn binding(cx: &mut EmitCx<'_>, a: &Sampling) -> BResult<(Binding, CombinedImage } } +/// The binding arm sampling `a`'s linear taps are fetched through (`Linear::fetch`), else its own. +fn fetch_binding(cx: &mut EmitCx<'_>, a: &Sampling) -> BResult { + let key = match (&a.linear, a.source) { + (Some(super::linear::Linear { fetch: Some(k), .. }), _) => *k, + (_, Source::Combined(key)) => key, + _ => return Err(cx.fail("a shared sampling of a heap element")), + }; + match cx.decl.families.sampler.combined.get(&key) { + Some(&(b, _)) => Ok(b), + None => Err(cx.fail(format!("combined binding {key:?} is not declared"))), + } +} + /// The emulation every arm of a shared switch takes. #[derive(Clone, Copy)] enum Emulation<'a> { diff --git a/crates/metal2vulkan/src/lower/texture/emit.rs b/crates/metal2vulkan/src/lower/texture/emit.rs index 761e17228..bbd3549b2 100644 --- a/crates/metal2vulkan/src/lower/texture/emit.rs +++ b/crates/metal2vulkan/src/lower/texture/emit.rs @@ -848,6 +848,11 @@ fn from_image( }; return srgb_raw_texel(cx, fb, form, x, SRGB_TEXEL); } + // `BGRA8Unorm_sRGB`'s codes through an rgba8 view: red and blue exchanged, then decoded. + StorageImageClass::SrgbEncodeBgra => { + let x = swizzle_bgra(fb, x)?; + return srgb_raw_texel(cx, fb, form, x, SRGB_TEXEL); + } StorageImageClass::RotateArgb => rotate_argb(fb, x, true)?, // A `YCbCrWrite` slot is only written (`StorageImageClass::YCbCrWrite`). StorageImageClass::HalfTowardZero @@ -857,6 +862,8 @@ fn from_image( | StorageImageClass::OneBitAlpha => x, // A half-float texel's bits, through its unsigned integer alias: Metal's read, whole. StorageImageClass::HalfBits => return half_bits_texel(fb, decl, form, x), + // An `RGB9E5Float` word, through its `R32_UINT` alias, decoded exactly. + StorageImageClass::SharedExponentBits => return shared_exponent_texel(fb, form, x), }; let x = match decl.x_channel { true => x_channel_read(fb, decl, x)?, @@ -906,6 +913,87 @@ pub(crate) fn srgb_raw_texel( srgb_ratio(fb, form, steps) } +/// The held texel (`form`, a `half` or `float` result) of a device's sample `x` (a `vec4` of +/// `f32`) of an 8-bit sRGB texture held as its UNORM twin, whose view reads each code `c` as +/// `c / 255`, so the device filters the codes, where Metal decodes each texel and filters the +/// decoded values (`PrecisionNote::SrgbTexelDecode`). A lane within `2^-10` of a code once +/// scaled by 255 (one texel's: a nearest sample's, a gather's) decodes as [`srgb_raw_texel`] +/// decodes it, Metal's value exactly. Another color lane, `c + t` between codes `c` and `c + 1`, +/// takes the steps' interpolation `(k_c + t (k_{c+1} - k_c)) / 4095`, Metal's sum where the +/// filter blends two adjacent codes and near it where the codes are close; another alpha lane +/// keeps the device's filtered value, which Metal's alpha sums alike. `color` says which lanes +/// are color, as [`srgb_raw_texel`]'s. +pub(crate) fn srgb_filtered_texel( + cx: &mut EmitCx<'_>, + fb: &mut FunctionBuilder<'_>, + form: TexelForm, + x: SValue, + color: [bool; 4], +) -> BResult { + use crate::lower::arith::legal::{Form, Held}; + let Some(table) = cx.decl.families.arith.srgb else { + return Err(cx.fail("an sRGB twin's sample without Metal's table")); + }; + let four = TexelForm { lanes: 4, ..form }; + let exact = srgb_raw_texel(cx, fb, four, x, color)?; + let (u, f) = (u32_ty(fb)?, f32_ty(fb)?); + let (vu, vf) = (vec(fb, u, 4)?, vec(fb, f, 4)?); + let scale = f32s(fb, 4, 255.0)?; + let zero = f32s(fb, 4, 0.0)?; + let c = fb.binary(BinOp::FMul, x, scale)?; + let c = fb.glsl(GlslOp::FClamp, &[c, zero, scale])?; + // One texel's lanes: within `2^-10` of a code. + let nearest = fb.glsl(GlslOp::RoundEven, &[c])?; + let off = fb.binary(BinOp::FSub, c, nearest)?; + let off = fb.glsl(GlslOp::FAbs, &[off])?; + let within = f32s(fb, 4, 1.0 / 1024.0)?; + let one = fb.binary(BinOp::FOrdLessThanEqual, off, within)?; + // The steps' interpolation between the codes below and above, `c` 255 taking 254 and 255. + let below = fb.glsl(GlslOp::Floor, &[c])?; + let below = fb.convert(ConvOp::ConvertFToU, below, vu)?; + let top = u32s(fb, 4, 254)?; + let below = fb.glsl(GlslOp::UMin, &[below, top])?; + let base = fb.convert(ConvOp::ConvertUToF, below, vf)?; + let t = fb.binary(BinOp::FSub, c, base)?; + let ones = u32s(fb, 4, 1)?; + let above = fb.binary(BinOp::IAdd, below, ones)?; + let steps = f32s(fb, 1, 1.0 / 4095.0)?; + let mut lanes = Vec::with_capacity(4); + for (i, color) in (0u32..).zip(color) { + if !color { + lanes.push(fb.composite_extract(x, &[i])?); + continue; + } + let lo = fb.composite_extract(below, &[i])?; + let hi = fb.composite_extract(above, &[i])?; + let lo = crate::lower::arith::srgb::step(fb, table, lo)?; + let hi = crate::lower::arith::srgb::step(fb, table, hi)?; + let lo = fb.convert(ConvOp::ConvertUToF, lo, f)?; + let hi = fb.convert(ConvOp::ConvertUToF, hi, f)?; + let rise = fb.binary(BinOp::FSub, hi, lo)?; + let ti = fb.composite_extract(t, &[i])?; + let k = fb.glsl(GlslOp::Fma, &[ti, rise, lo])?; + lanes.push(fb.binary(BinOp::FMul, k, steps)?); + } + let blended = fb.composite_construct(vf, &lanes)?; + let blended = match form.conv { + TexelConv::F16 => { + let half = Form { + held: Held::Float(crate::lower::arith::legal::FloatFmt::Half), + lanes: 4, + }; + narrow::round_texel(fb, half, blended)? + } + _ => blended, + }; + let r = fb.select(one, exact, blended)?; + if form.lanes == 1 { + fb.composite_extract(r, &[0]) + } else { + Ok(r) + } +} + /// A raw cube gather's held texel (`form`, a `half` or `float` result): the four taps' raw codes /// `codes` (a `vec4` of `f32`, gather order, channel `component`) decoded as [`srgb_raw_texel`] /// decodes a gather's, but for each lane `corner` names, the tap past both edges of its face, which @@ -1054,6 +1142,11 @@ pub(crate) const SRGB_TEXEL: [bool; 4] = [true, true, true, false]; /// the exact quotients (`the_srgb_raw_words_bound_its_emission`). pub(crate) const SRGB_RAW_WORDS: u32 = 520; +/// The words [`srgb_filtered_texel`] emits, at most: [`srgb_raw_texel`]'s, the codes' scale, test +/// and interpolation (two table steps per color lane), a `half` result's rounding, and the +/// selection (`the_raw_estimate_bounds_its_emission`). +pub(crate) const SRGB_FILTERED_WORDS: u32 = SRGB_RAW_WORDS + 400; + /// The conversion of a slot's `half` texels by the bound format's class: the module's routine and /// the slot's `TexelFormat` specialization constant; or of a heap color texture's by the class its /// handle carries, read from the handle. @@ -1600,6 +1693,17 @@ pub fn to_image( )) } }, + StorageImageClass::SrgbEncodeBgra => match srgb { + Some(table) => { + let codes = srgb_codes(fb, table, form, x, test)?; + swizzle_bgra(fb, codes)? + } + None => { + return Err(crate::spirv::error::BuildError::Type( + crate::spirv::error::TypeRule::FunctionSignature, + )) + } + }, StorageImageClass::RotateArgb => { let x = argb_codes(fb, form, x)?; rotate_argb(fb, x, false)? @@ -1617,6 +1721,7 @@ pub fn to_image( _ => x, }, StorageImageClass::HalfBits => half_bits(fb, form, x)?, + StorageImageClass::SharedExponentBits => shared_exponent_word(fb, form, x)?, }; match decl.x_channel && form.lanes == 4 { true => x_channel_write(fb, x), @@ -1743,6 +1848,112 @@ fn half_bits(fb: &mut FunctionBuilder<'_>, form: TexelForm, x: SValue) -> BResul crate::lower::arith::narrow::to_bits(fb, form.half(), x) } +/// The held texel (`form`, a `half` or `float` result) of a `SharedExponentBits` slot's image texel +/// `x` (a `uvec4`, the `RGB9E5Float` word in its first lane): each of red, green and blue its +/// mantissa `m` times `2^(e - 24)` for the word's exponent `e`, exact in `f32` and in `half` (nine +/// significant bits, from `2^-24` to 65408), and alpha 1, as Metal reads the texel. +fn shared_exponent_texel( + fb: &mut FunctionBuilder<'_>, + form: TexelForm, + x: SValue, +) -> BResult { + let f = f32_ty(fb)?; + let word = fb.composite_extract(x, &[0])?; + let twenty_seven = fb.u32_const(27)?; + let twenty_seven = fb.module().const_value(twenty_seven)?; + let e = fb.binary(BinOp::ShiftRightLogical, word, twenty_seven)?; + // `2^(e - 24)`: the `f32` of biased exponent `e + 103`, a normal for every `e` in `[0, 31]`. + let bias = fb.u32_const(103)?; + let bias = fb.module().const_value(bias)?; + let biased = fb.binary(BinOp::IAdd, e, bias)?; + let twenty_three = fb.u32_const(23)?; + let twenty_three = fb.module().const_value(twenty_three)?; + let scale = fb.binary(BinOp::ShiftLeftLogical, biased, twenty_three)?; + let scale = fb.convert(ConvOp::Bitcast, scale, f)?; + let nine_bits = fb.u32_const(0x1ff)?; + let nine_bits = fb.module().const_value(nine_bits)?; + let mut lanes = Vec::with_capacity(4); + for c in 0..3u32 { + let shift = fb.u32_const(9 * c)?; + let shift = fb.module().const_value(shift)?; + let m = fb.binary(BinOp::ShiftRightLogical, word, shift)?; + let m = fb.binary(BinOp::BitwiseAnd, m, nine_bits)?; + let m = fb.convert(ConvOp::ConvertUToF, m, f)?; + lanes.push(fb.binary(BinOp::FMul, m, scale)?); + } + lanes.push(f32s(fb, 1, 1.0)?); + let v4 = vec(fb, f, 4)?; + let v = fb.composite_construct(v4, &lanes)?; + match form.lanes { + 1 => fb.composite_extract(v, &[0]), + _ => Ok(v), + } +} + +/// 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 +fn shared_exponent_word( + fb: &mut FunctionBuilder<'_>, + form: TexelForm, + x: SValue, +) -> BResult { + if form.lanes != 4 || !matches!(form.conv, TexelConv::F32 | TexelConv::F16) { + return Err(crate::spirv::error::BuildError::Type( + crate::spirv::error::TypeRule::FunctionSignature, + )); + } + let u = u32_ty(fb)?; + let f = f32_ty(fb)?; + let constant = |fb: &mut FunctionBuilder<'_>, v: u32| -> BResult { + let c = fb.u32_const(v)?; + fb.module().const_value(c) + }; + let zero = constant(fb, 0)?; + let top = constant(fb, 65408.0f32.to_bits())?; + let magnitude = constant(fb, 0x7fff_ffff)?; + let infinity = constant(fb, 0x7f80_0000)?; + let mut clamped = [zero; 3]; + for (c, out) in (0u32..).zip(clamped.iter_mut()) { + let v = fb.composite_extract(x, &[c])?; + let bits = fb.convert(ConvOp::Bitcast, v, u)?; + // A NaN, or any value with its sign bit set, is 0; a positive value's bits order as its + // value does, so the clamp is an unsigned minimum. + let mag = fb.binary(BinOp::BitwiseAnd, bits, magnitude)?; + let nan = fb.binary(BinOp::UGreaterThan, mag, infinity)?; + let negative = fb.binary(BinOp::UGreaterThan, bits, magnitude)?; + let dropped = fb.binary(BinOp::LogicalOr, nan, negative)?; + let below = fb.glsl(GlslOp::UMin, &[bits, top])?; + *out = fb.select(dropped, zero, below)?; + } + let [red, green, blue] = clamped; + let largest = fb.glsl(GlslOp::UMax, &[red, green])?; + let largest = fb.glsl(GlslOp::UMax, &[largest, blue])?; + // `max(⌊log2 m⌋, -16) + 16` is `max(field, 111) - 111` of the exponent field (a zero or a + // denormal `m` taking 0). + let twenty_three = constant(fb, 23)?; + let field = fb.binary(BinOp::ShiftRightLogical, largest, twenty_three)?; + let floor = constant(fb, 111)?; + let field = fb.glsl(GlslOp::UMax, &[field, floor])?; + let e = fb.binary(BinOp::ISub, field, floor)?; + // `2^(24 - e)`: the `f32` of biased exponent `151 - e`. + let top_bias = constant(fb, 151)?; + let biased = fb.binary(BinOp::ISub, top_bias, e)?; + let scale = fb.binary(BinOp::ShiftLeftLogical, biased, twenty_three)?; + let scale = fb.convert(ConvOp::Bitcast, scale, f)?; + let most = constant(fb, 0x1ff)?; + let exponent_at = constant(fb, 27)?; + let mut word = fb.binary(BinOp::ShiftLeftLogical, e, exponent_at)?; + for (c, bits) in clamped.into_iter().enumerate() { + let v = fb.convert(ConvOp::Bitcast, bits, f)?; + let scaled = fb.binary(BinOp::FMul, v, scale)?; + let m = fb.convert(ConvOp::ConvertFToU, scaled, u)?; + let m = fb.glsl(GlslOp::UMin, &[m, most])?; + let shift = constant(fb, 9 * c as u32)?; + let m = fb.binary(BinOp::ShiftLeftLogical, m, shift)?; + word = fb.binary(BinOp::BitwiseOr, word, m)?; + } +} + /// The `f32` NaN a written `float`'s NaN becomes under `HalfTowardZero` and `HalfQuietNan` /// (`color_write::round`'s), which a device of `DriverDeviation::MetalFloatStorageNans` stores as /// Metal's `0x7e00`. @@ -2036,8 +2247,9 @@ pub(crate) fn class_write_words(class: StorageImageClass) -> u32 { color_write::words(&[Some(ChannelWrite::Unorm { bits: 8 }); 4]) as u32 } StorageImageClass::YCbCrWrite => YCBCR_WRITE_WORDS, - StorageImageClass::SrgbEncode => SRGB_WRITE_WORDS, + StorageImageClass::SrgbEncode | StorageImageClass::SrgbEncodeBgra => SRGB_WRITE_WORDS, StorageImageClass::OneBitAlpha => ONE_BIT_ALPHA_WORDS, + StorageImageClass::SharedExponentBits => SHARED_EXPONENT_WORDS, // A `float` texel's rounding, then four lanes' bits. StorageImageClass::HalfBits => { let half = crate::lower::arith::legal::Form { @@ -2053,6 +2265,10 @@ pub(crate) fn class_write_words(class: StorageImageClass) -> u32 { } } +/// The words of [`shared_exponent_word`], at most: three channels' extract, clamp and mantissa +/// (about twelve instructions each), the exponent's six, the word's placement, and the constants. +pub(crate) const SHARED_EXPONENT_WORDS: u32 = 3 * 12 * 6 + 8 * 6 + 3 * 6 + 12 * 4; + /// The words of [`one_bit_alpha`]: the extract, comparison, select and insert, and the /// constants. pub(crate) const ONE_BIT_ALPHA_WORDS: u32 = 40; diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index 7330a118e..0083eb9d3 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -2082,20 +2082,37 @@ pub(crate) fn srgb_texels( return Ok(false); } // A form the raw codes do not serve everywhere decodes through the device's view, which a - // device that cannot sample the bound format does not have. + // device that cannot sample the bound format does not have: under the slot's twin variant it + // decodes the device's filtered codes instead, through Metal's table. if reach != SrgbReach::Raw { cx.facts .insert(crate::pipeline::facts::RuntimeFact::SrgbDeviceDecode { slot }); } - if reach == SrgbReach::Device { + let twin = reach != SrgbReach::Raw && cx.inputs.srgb_twins.contains(&slot); + if reach == SrgbReach::Device && !twin { device_decode(cx); return Ok(false); } + if reach == SrgbReach::Device { + cx.precision.insert(PrecisionNote::SrgbTexelDecode); + } cx.families .arith .srgb .get_or_insert(crate::air::intrinsics::PackDir::Unpack); - Ok(true) + Ok(reach != SrgbReach::Device) +} + +/// Whether an access of `image` that keeps the device's decode of an 8-bit sRGB texture +/// ([`srgb_texels`] with a reach other than [`SrgbReach::Raw`]) samples the bound format's UNORM +/// twin instead (`LoweringInputs::srgb_twins`: a format the device cannot sample), whose view reads +/// the codes, so the access decodes the device's filtered codes through Metal's table +/// (`texture::srgb_filtered_texel`), Metal's value exactly where the filter reads one texel. +pub(crate) fn srgb_twin(cx: &SelectCx<'_>, image: ImageRef) -> Result { + match image { + ImageRef::Slot(index) => Ok(cx.inputs.srgb_twins.contains(&slot_of(cx, index)?.slot)), + ImageRef::Heap { .. } => Ok(false), + } } /// An access that keeps the device's decode of a texture that may be bound in an 8-bit sRGB @@ -3349,12 +3366,19 @@ fn select_read_as( // (the slot's planning declares it), as a raw view's are. let srgb_codes = storage && matches!(texel.conv, TexelConv::F16 | TexelConv::F32) - && storage_class(cx, image)? == StorageImageClass::SrgbEncode; + && matches!( + storage_class(cx, image)?, + StorageImageClass::SrgbEncode | StorageImageClass::SrgbEncodeBgra + ); // A storage slot's half-float texels, through its unsigned integer alias, widened exactly - // (the slot's planning declares it): Metal's read, a NaN's included. + // (the slot's planning declares it): Metal's read, a NaN's included. So is an `RGB9E5Float` + // slot's word through its `R32_UINT` alias, decoded exactly. let half_bits = storage && matches!(texel.conv, TexelConv::F16 | TexelConv::F32) - && storage_class(cx, image)? == StorageImageClass::HalfBits; + && matches!( + storage_class(cx, image)?, + StorageImageClass::HalfBits | StorageImageClass::SharedExponentBits + ); let exact = raw || srgb_codes || half_bits; // An extended-range texel is decoded exactly to `f32`, which a `half` result rounds to // nearest even, as Metal answers. A read is one texel. diff --git a/crates/metal2vulkan/src/lower/texture/slot.rs b/crates/metal2vulkan/src/lower/texture/slot.rs index f07534234..4ca31d3e4 100644 --- a/crates/metal2vulkan/src/lower/texture/slot.rs +++ b/crates/metal2vulkan/src/lower/texture/slot.rs @@ -772,7 +772,10 @@ fn storage_format( // written stores its half bits in its unsigned integer alias. let converting = !matches!( choice.class, - StorageImageClass::Identity | StorageImageClass::YCbCrWrite | StorageImageClass::HalfBits + StorageImageClass::Identity + | StorageImageClass::YCbCrWrite + | StorageImageClass::HalfBits + | StorageImageClass::SharedExponentBits ); if converting && texel != TexelClass::Float { return Err(Unsupported::not_representable(Feature::Format).into()); @@ -1018,11 +1021,12 @@ fn declare_slot( // holds each texel's half bits there (`StorageImageClass::HalfBits`): a `float` slot's reads // and writes, as the binder chooses it (`metal::format::storage_choice`); no atomic. let half_bits = storage - && cx - .inputs - .storage_images - .get(&s.slot) - .is_some_and(|c| c.class == StorageImageClass::HalfBits); + && cx.inputs.storage_images.get(&s.slot).is_some_and(|c| { + matches!( + c.class, + StorageImageClass::HalfBits | StorageImageClass::SharedExponentBits + ) + }); if half_bits && (s.uses.atomic || !float) { return Err(Unsupported::not_representable(Feature::Format).into()); } @@ -1386,7 +1390,10 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { for (index, d, volatile) in decls { // An 8-bit sRGB format's codes convert through Metal's twelve-bit tables (`emit:: // srgb_codes`, `emit::srgb_raw_texel`), which the module declares once. - if d.class == StorageImageClass::SrgbEncode { + if matches!( + d.class, + StorageImageClass::SrgbEncode | StorageImageClass::SrgbEncodeBgra + ) { let written = cx .families .texture diff --git a/crates/metal2vulkan/src/metal/format/mod.rs b/crates/metal2vulkan/src/metal/format/mod.rs index 15be43fdc..77f053a02 100644 --- a/crates/metal2vulkan/src/metal/format/mod.rs +++ b/crates/metal2vulkan/src/metal/format/mod.rs @@ -2580,7 +2580,8 @@ pub(crate) fn without_format_gaps( /// `STORAGE_{READ,WRITE}_WITHOUT_FORMAT` optimal-tiling bits, or what the specification implies /// for them), else with its SPIR-V image format. Otherwise an alias view (bgra8 through rgba8 and /// bgr10a2 through rgb10a2 with `SwizzleBgra`, the 8-bit sRGB formats through their UNORM twin with -/// `SrgbEncode`), else +/// `SrgbEncode` or bgra8 sRGB through rgba8 with `SrgbEncodeBgra`, `RGB9E5Float` through `R32_UINT` +/// with `SharedExponentBits`, `A8Unorm` through `R8_UNORM` with `AlphaInRed`), else /// `Unsupported{Format}`. A read-and-write choice serves any access to a storage image, so a /// caller that does not know the function's accesses uses it. It does not serve a texture /// buffer: Vulkan implies no buffer bit, so a format formatless as an image can need a declared @@ -2604,9 +2605,10 @@ pub fn storage_image_choice( /// Otherwise an alias view of a `MUTABLE_FORMAT` image (or the same bytes viewed as the alias /// format, for a texture buffer): bgra8 through an rgba8 view and bgr10a2 through an rgb10a2 view /// (`A2R10G10B10` through `A2B10G10R10`, which NVIDIA and lavapipe store where they do not store -/// the former) with `SwizzleBgra`, and the 8-bit sRGB formats through their UNORM twin with -/// `SrgbEncode`. Anything else is `Unsupported{Format}` naming what each route lacks, a format's -/// without-format usage included. +/// the former) with `SwizzleBgra`, the 8-bit sRGB formats through their UNORM twin with +/// `SrgbEncode` (`BGRA8Unorm_sRGB`, where its twin is not accessed without a format, through +/// `R8G8B8A8_UNORM` with `SrgbEncodeBgra`), `RGB9E5Float` through `R32_UINT` with +/// `SharedExponentBits`, and `A8Unorm` through `R8_UNORM` with `AlphaInRed` (no alias: such a /// /// An RGBX format's choice ([`x_channel`]) is its RGBA twin's, which converts its texels in the /// shader (`StorageImageChoice::x_channel`); its texture buffer, whose reads a texel buffer's view @@ -2675,13 +2677,20 @@ fn held_storage_choice( Some((F::A2B10G10R10_UNORM_PACK32, StorageImageClass::SwizzleBgra)) } PixelFormat::ARGB8Unorm => Some((F::R8G8B8A8_UNORM, StorageImageClass::RotateArgb)), + PixelFormat::RGB9E5Float => Some((F::R32_UINT, StorageImageClass::SharedExponentBits)), + PixelFormat::R8UnormSRGB => Some((F::R8_UNORM, StorageImageClass::SrgbEncode)), + PixelFormat::RG8UnormSRGB => Some((F::R8G8_UNORM, StorageImageClass::SrgbEncode)), PixelFormat::RGBA8UnormSRGB => Some((F::R8G8B8A8_UNORM, StorageImageClass::SrgbEncode)), PixelFormat::RGBX8UnormSRGB => Some((F::R8G8B8A8_UNORM, StorageImageClass::SrgbEncode)), - // bgra8 sRGB needs both conversions unless its own UNORM twin is declarable. PixelFormat::BGRA8UnormSRGB => Some((F::B8G8R8A8_UNORM, StorageImageClass::SrgbEncode)), _ => None, }; - // An RGBX format's write stores the green field's bits as X (EV FPV-pf1-m4): green's sRGB code + // bgra8 sRGB takes both conversions through an rgba8 view where its own UNORM twin, which + // has no SPIR-V image format, is not accessed without one. + let second = match pf { + PixelFormat::BGRA8UnormSRGB => Some((F::R8G8B8A8_UNORM, StorageImageClass::SrgbEncodeBgra)), + _ => None, + }; // for `RGBX8Unorm_sRGB`. A device storing into the sRGB image itself encodes red, green and // blue and stores the fourth lane linearly, as alpha, so that format's writes take the UNORM // alias, whose encode the shader applies before it moves green into the fourth lane. @@ -2695,7 +2704,11 @@ fn held_storage_choice( choice.alias = Some(AliasView::new(image)); return Ok(choice); } - if storage(image) && declarable(image) && !rotated && !srgb_x { + // Vulkan's conversion to a shared-exponent texel rounds each mantissa half up, where Metal + // truncates it: an `RGB9E5Float` write takes its word alias, whose encode is Metal's, even on a + // device that stores the format. + let word = matches!(alias, Some((_, StorageImageClass::SharedExponentBits))); + if storage(image) && declarable(image) && !rotated && !srgb_x && !word { let class = half_storage_class(pf, use_, profile); if !formatless(image) { return Ok(StorageImageChoice::new(image, class)); @@ -2706,7 +2719,7 @@ fn held_storage_choice( choice.numeric = crate::bind::neutral::numeric_type(image); return Ok(choice); } - if let Some((view, class)) = alias { + for (view, class) in alias.into_iter().chain(second) { if storage(view) && declarable(view) { let mut choice = StorageImageChoice::new(view, class); // `ARGB8Unorm`'s image is the view's format: its choice rotates without an alias. @@ -2726,9 +2739,7 @@ fn held_storage_choice( missing }; let mut alternatives = vec![lacks(image)]; - if let Some((view, _)) = alias { - alternatives.push(lacks(view)); - } + alternatives.extend(alias.into_iter().chain(second).map(|(view, _)| lacks(view))); Err(Unsupported::needs_any_of(Feature::Format, alternatives).into()) } diff --git a/crates/metal2vulkan/src/metal/format/tests.rs b/crates/metal2vulkan/src/metal/format/tests.rs index bc9914a01..0e535e2c2 100644 --- a/crates/metal2vulkan/src/metal/format/tests.rs +++ b/crates/metal2vulkan/src/metal/format/tests.rs @@ -638,6 +638,50 @@ fn a8_is_direct_where_exposed_and_samples_as_red_elsewhere() { assert_eq!(m.format, vk::Format::A8_UNORM); } +/// A `BGRA8Unorm_sRGB` storage texture is its `B8G8R8A8_UNORM` twin's encode view where the device +/// accesses the twin without a format (SPIR-V names no BGRA image format), and else an +/// `R8G8B8A8_UNORM` view that encodes and exchanges red and blue (`SrgbEncodeBgra`), which every +/// committed profile stores: ARL's and Pascal's profiles state no `VkFormatProperties3`, so their +/// twin takes neither access without a format, and the Iris Xe's ANV reads no storage image +/// without one. Its texture lists the view among its formats. +#[test] +fn bgra8_srgb_storage_takes_an_rgba8_view_where_its_twin_is_not_declarable() { + let mut swizzled = Vec::new(); + for (name, dev) in committed_devices() { + let p = dev.profile(); + let pf = PixelFormat::BGRA8UnormSRGB; + let c = storage_image_choice(pf, p).unwrap_or_else(|e| panic!("{name}: {e}")); + vk::Format::B8G8R8A8_UNORM, + StorageUse::READ_WRITE_TEXTURE, + p, + match c.class { + StorageImageClass::Identity => {} + StorageImageClass::SrgbEncode => { + assert!(twin, "{name}"); + assert_eq!(c.vk_format, vk::Format::B8G8R8A8_UNORM, "{name}"); + } + StorageImageClass::SrgbEncodeBgra => { + assert!(!twin, "{name}"); + assert_eq!(c.vk_format, vk::Format::R8G8B8A8_UNORM, "{name}"); + assert_eq!( + c.alias, + Some(AliasView::new(vk::Format::B8G8R8A8_SRGB)), + "{name}" + ); + assert!( + storage_view_formats(pf, p).contains(&vk::Format::R8G8B8A8_UNORM), + "{name}" + ); + swizzled.push(name); + } + other => panic!("{name}: {other:?}"), + } + } + for want in ["intel-arl-anv", "nvidia-pascal-linux", "intel-irisxe-anv"] { + assert!(swizzled.iter().any(|n| n == want), "{want}: {swizzled:?}"); + } +} + /// An `A8Unorm` view reads an `R8Unorm` image through `(Zero, Zero, Zero, Red)` composed under the /// view's own swizzle, where the device has `A8_UNORM` and where it does not (the probe a8view on /// an Apple M3 Max under macOS 27.0.1: Metal's `A8Unorm` view of an `R8Unorm` texture made without @@ -1261,6 +1305,91 @@ fn depth_and_stencil_fall_back_to_combined_formats() { ); } +/// A one- or two-channel 8-bit sRGB storage texture on a device that stores neither sRGB format +/// takes its UNORM twin's view, converting through Metal's tables (`SrgbEncode`), as the +/// four-channel ones do; without the UNORM format's storage the refusal names both routes. +#[test] +fn one_and_two_channel_srgb_storage_takes_the_unorm_alias() { + use vk::Format as F; + let storage = SAMPLED | vk::FormatFeatureFlags::STORAGE_IMAGE; + let stored = device(floor_with(&[ + (F::R8_UNORM, storage), + (F::R8G8_UNORM, storage), + (F::R8_SRGB, SAMPLED), + (F::R8G8_SRGB, SAMPLED), + ])); + for (pf, image, view) in [ + (PixelFormat::R8UnormSRGB, F::R8_SRGB, F::R8_UNORM), + (PixelFormat::RG8UnormSRGB, F::R8G8_SRGB, F::R8G8_UNORM), + ] { + let mut want = StorageImageChoice::new(view, StorageImageClass::SrgbEncode); + want.alias = Some(AliasView::new(image)); + assert_eq!( + storage_image_choice(pf, stored.profile()), + Ok(want), + "{pf:?}" + ); + } + let unstored = device(floor_with(&[(F::R8_UNORM, SAMPLED), (F::R8_SRGB, SAMPLED)])); + let Err(Error::Unsupported(u)) = + storage_image_choice(PixelFormat::R8UnormSRGB, unstored.profile()) + else { + panic!("R8Unorm_sRGB stored without R8_UNORM storage"); + }; + let named: Vec> = match u.needs { + Needs::AnyOf(routes) => routes + .iter() + .map(|route| { + route + .iter() + .filter_map(|c| match c { + Capability::Format { format, .. } => Some(*format), + _ => None, + }) + .collect() + }) + .collect(), + other => panic!("{other:?}"), + }; + assert!( + named[0].contains(&F::R8_SRGB) && named[1].contains(&F::R8_UNORM), + "{named:?}" + ); +} + +/// An `RGB9E5Float` storage texture takes its `R32_UINT` alias, holding Metal's word +/// (`SharedExponentBits`), on a device that does not store the format and on one that stores it +/// (whose own conversion rounds the mantissas half up, where Metal truncates them). +#[test] +fn shared_exponent_storage_takes_the_word_alias() { + use vk::Format as F; + let storage = SAMPLED | vk::FormatFeatureFlags::STORAGE_IMAGE; + let unstored = device(floor_with(&[ + (F::R32_UINT, storage), + (F::E5B9G9R9_UFLOAT_PACK32, SAMPLED), + ])); + let mut want = StorageImageChoice::new(F::R32_UINT, StorageImageClass::SharedExponentBits); + want.alias = Some(AliasView::new(F::E5B9G9R9_UFLOAT_PACK32)); + assert_eq!( + storage_image_choice(PixelFormat::RGB9E5Float, unstored.profile()), + Ok(want) + ); + let mut desc = floor_with(&[(F::R32_UINT, storage), (F::E5B9G9R9_UFLOAT_PACK32, storage)]); + if let Some(e5) = desc.formats.formats.get_mut(&F::E5B9G9R9_UFLOAT_PACK32) { + e5.optimal_tiling |= vk::FormatFeatureFlags2::STORAGE_READ_WITHOUT_FORMAT + | vk::FormatFeatureFlags2::STORAGE_WRITE_WITHOUT_FORMAT; + } + desc.features + .insert(VkFeature::ShaderStorageImageReadWithoutFormat); + desc.features + .insert(VkFeature::ShaderStorageImageWriteWithoutFormat); + let stored = device(desc); + assert_eq!( + storage_image_choice(PixelFormat::RGB9E5Float, stored.profile()), + Ok(want) + ); +} + /// The required fixture shape: on a profile where bgra8 lacks `STORAGE_IMAGE`, a bgra8 and an rgba8 /// storage texture get distinct choices (and so distinct keys). #[test] @@ -1286,8 +1415,14 @@ fn storage_choices_follow_d25() { let srgb = choice(PixelFormat::RGBA8UnormSRGB, &typed).unwrap(); assert_eq!(srgb.class, StorageImageClass::SrgbEncode); assert_eq!(srgb.alias, Some(AliasView::new(vk::Format::R8G8B8A8_SRGB))); - // bgra8 sRGB needs its own UNORM twin to be declarable: formatless only. - assert!(choice(PixelFormat::BGRA8UnormSRGB, &typed).is_err()); + // bgra8 sRGB, whose own UNORM twin is declarable only without a format, takes both + // conversions through rgba8. + let mut srgb_bgra = StorageImageChoice::new( + vk::Format::R8G8B8A8_UNORM, + StorageImageClass::SrgbEncodeBgra, + ); + srgb_bgra.alias = Some(AliasView::new(vk::Format::B8G8R8A8_SRGB)); + assert_eq!(choice(PixelFormat::BGRA8UnormSRGB, &typed), Ok(srgb_bgra)); assert_eq!( choice(PixelFormat::Depth32Float, &typed), Err(Unsupported::not_representable(Feature::Format).into()) @@ -1382,30 +1517,11 @@ fn storage_choices_follow_d25() { choice(PixelFormat::RGBA16Sint, &formatless), Ok(unknown(SampledType::Sint)) ); - assert_eq!(choice(PixelFormat::A8Unorm, &formatless), a8_lacks(true)); - // bgra8 sRGB has only its UNORM twin's encode view, which the shader cannot declare either: - // a typed refusal naming each route's without-format usages (both conversions through rgba8 are - // not modelled). - let without = |format| { - [ - FormatUsage::StorageImageReadWithoutFormat, - FormatUsage::StorageImageWriteWithoutFormat, - ] - .map(|usage| Capability::Format { format, usage }) - }; - let srgb = vk::Format::B8G8R8A8_SRGB; - let mut direct = vec![Capability::Format { - format: srgb, - usage: FormatUsage::StorageImage, - }]; - direct.extend(without(srgb)); + // bgra8 sRGB's UNORM twin is not accessed without a format here (no `VkFormatProperties3`): + // both conversions through rgba8. assert_eq!( choice(PixelFormat::BGRA8UnormSRGB, &formatless), - Err(Unsupported::needs_any_of( - Feature::Format, - vec![direct, without(vk::Format::B8G8R8A8_UNORM).to_vec()] - ) - .into()) + Ok(srgb_bgra) ); } diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index a6d8fa575..45e9644c2 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -196,6 +196,7 @@ mod serde_round_trips { dropped_vertex_layer: true, storage_view_slots: BTreeSet::from([buffer(3)]), srgb_textures: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 4)]), + srgb_twins: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 4)]), ycbcr_textures: BTreeSet::from([slot(Stage::Kernel, SlotClass::Texture, 6)]), flat_grid: true, replay_bindings: true, @@ -321,6 +322,7 @@ mod serde_round_trips { half_blends: BTreeSet::from([0]), }), srgb_textures: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 7)]), + srgb_twins: BTreeSet::from([slot(Stage::Fragment, SlotClass::Texture, 7)]), snapshot_textures: BTreeMap::from([( slot(Stage::Fragment, SlotClass::Texture, 3), crate::pipeline::SnapshotForm::Half, diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index c28c123a2..3c756c01b 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -854,7 +854,8 @@ pub enum PrecisionNote { /// it: the class is unbounded. HalfSampleFilter, /// The module reads, samples, or gathers a texture with a `half` or `float` result through - /// the device's sRGB decode where the texture may be bound in an 8-bit sRGB format. Metal + /// the device's sRGB decode, or decodes the device's filter of its codes, where the texture may + /// be bound in an 8-bit sRGB format. Metal /// decodes such a texel's color channels through its twelve-bit table (`k / 4095` for the /// code's step `k`) and its alpha as `c / 255`, which the device's decode (Vulkan's transfer /// function, within its precision rules) does not reproduce. A texture slot the shape binds in @@ -872,7 +873,12 @@ pub enum PrecisionNote { /// known when the function compiles); and any such access of an argument-buffer (heap) element, /// whose format is never known. On a device that does (`VkProperty::MetalSampler`: MoltenVK on /// Apple's GPU) the device's decode is Metal's, and the module requires the property instead. - /// Validation derives no tolerance from it: the class is unbounded. + /// Where the device cannot sample the bound format, whose texture it holds as the format's + /// UNORM twin (`LoweringInputs::srgb_twins`), such an access samples the twin's codes and + /// decodes the device's filtered value through the table: Metal's value where the filter reads + /// one texel (a nearest sampler's), Metal's sum where it blends two adjacent codes, otherwise + /// the decode of the codes' blend, where Metal blends the decoded texels; recorded on every + /// device under that variant. Validation derives no tolerance from it: the class is unbounded. SrgbTexelDecode, /// The module samples a texture with a `float` result through a filter on a device that does /// not sample through Metal's own sampler (one that does, `VkProperty::MetalSampler`, filters diff --git a/crates/metal2vulkan/src/pipeline/compile/key.rs b/crates/metal2vulkan/src/pipeline/compile/key.rs index fee2e8081..0b3264211 100644 --- a/crates/metal2vulkan/src/pipeline/compile/key.rs +++ b/crates/metal2vulkan/src/pipeline/compile/key.rs @@ -200,6 +200,11 @@ pub fn function_key( .bytes(format!("{:?}", inputs.srgb_textures).as_bytes()); } // Appended only when set, as `storage_view_slots`. + if !inputs.srgb_twins.is_empty() { + h.bytes(b"srgb-twins") + .bytes(format!("{:?}", inputs.srgb_twins).as_bytes()); + } + // Appended only when set, as `storage_view_slots`. if !inputs.snapshot_textures.is_empty() { h.bytes(b"snapshot-textures") .bytes(format!("{:?}", inputs.snapshot_textures).as_bytes()); diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index eac91a0a5..6ca0d6254 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -645,6 +645,7 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() { .replace(", replay_bindings: false", "") .replace(", framebuffer_fetch: None", "") .replace(", srgb_textures: {}", "") + .replace(", srgb_twins: {}", "") .replace(", snapshot_textures: {}", "") .replace(", ycbcr_textures: {}", "") .replace(", viewport_index_varying: false", "") diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 862897a29..3442b579a 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -424,11 +424,12 @@ pub enum RuntimeFact { AbsentArgumentRead { stage: Stage }, /// Under its `SrgbTexture` variant (`LoweringInputs::srgb_textures`), the function still /// decodes texels of the 8-bit sRGB texture bound to the slot through the device's sampled - /// view, in a form the raw codes do not serve (a `float` gather, a linear mip filter, a - /// runtime sampler's sample; `PrecisionNote::SrgbTexelDecode`). Where the device cannot sample - /// the bound sRGB format, whose texture it holds as the format's UNORM twin, the planner - /// refuses the texture there, needing the format's `SampledImage`; without the fact the - /// slot's own binding serves queries alone and takes the twin's view. + /// view, in a form the raw codes do not serve (a `float` gather on Metal's own sampler, a + /// linear mip filter, a runtime sampler's sample; `PrecisionNote::SrgbTexelDecode`). Where the + /// device cannot sample the bound sRGB format, whose texture it holds as the format's UNORM + /// twin, the slot's own binding takes the twin's view, and the plan's variant names the slot + /// in `VariantKey::srgb_twins`, under which the function decodes what the device samples + /// there; without the fact that binding serves queries alone. SrgbDeviceDecode { slot: SlotRef }, /// The fragment function was compiled under `VariantKey::zeroed_colors` /// (`LoweringInputs::zeroed_colors`): it writes zero to color attachment `color`, of pixel diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index a528df8bc..ebc2339f4 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -135,6 +135,14 @@ pub struct LoweringInputs { /// Metal's twelve-bit table. A slot of no such access is ignored. #[cfg_attr(feature = "serde", serde(default))] pub srgb_textures: BTreeSet, + /// Slots of `srgb_textures` bound to a texture held as its 8-bit sRGB format's UNORM twin, a + /// format the device cannot sample (`VariantKey::srgb_twins`): each access the raw codes do + /// not serve exactly, which elsewhere keeps the device's decode, samples the twin through the + /// slot's own binding and decodes the device's filtered codes + /// (`PrecisionNote::SrgbTexelDecode`): exactly where the filter reads one texel. A slot of no + /// such access is ignored. + #[cfg_attr(feature = "serde", serde(default))] + pub srgb_twins: BTreeSet, /// Fragment texture slots of `StageInterface::snapshot_textures` the draw reads through a /// snapshot (`VariantKey::snapshot_textures`), each with its snapshot's form, drawn twice /// (`PushField::SnapshotPhase`). The entry opens with the ordered pixel interlock's critical @@ -1315,6 +1323,14 @@ pub enum StorageImageClass { /// An sRGB image viewed as its UNORM alias: the shader encodes and decodes sRGB, through /// Metal's twelve-bit tables. SrgbEncode, + /// A `BGRA8Unorm_sRGB` image viewed as `R8G8B8A8_UNORM`, on a device that cannot declare its + /// `B8G8R8A8_UNORM` twin (a format without a SPIR-V image format, so it needs the device's + /// without-format access): the shader encodes and decodes sRGB as [`SrgbEncode`] does and + /// exchanges red and blue as [`SwizzleBgra`] does. + /// + /// [`SrgbEncode`]: StorageImageClass::SrgbEncode + /// [`SwizzleBgra`]: StorageImageClass::SwizzleBgra + SrgbEncodeBgra, /// An `ARGB8Unorm` image (alpha in byte 0, then red, green, and blue) viewed as /// `R8G8B8A8_UNORM`: the shader rotates the channels. RotateArgb, @@ -1358,6 +1374,16 @@ pub enum StorageImageClass { /// Metal reads them. The slot is declared of the alias's unsigned integer format; it takes no /// atomic. HalfBits, + /// An `RGB9E5Float` image a slot writes, and may read, viewed through its `R32_UINT` alias, on + /// every device (one that stores the format rounds each mantissa half up, as Vulkan's + /// conversion states, where Metal truncates it): the shader writes each texel as the word Metal + /// stores, and a read decodes the word exactly (each channel `m · 2^(e - 24)`, alpha 1). Metal's + /// word (an Apple M3 Max under macOS 27.0.1: kernel writes of `float` and `half` texels, both + /// accesses): each red, green and blue channel clamped to `[0, 65408]` (a NaN or a negative + /// value 0), the exponent `e = max(⌊log2 m⌋, -16) + 16` of the largest clamped channel `m` (0 + /// where all are 0), and each mantissa the clamped channel times `2^(24 - e)` truncated. The + /// slot is declared `R32ui`; it takes no atomic. + SharedExponentBits, } /// The alias view of a storage image created with `MUTABLE_FORMAT`. diff --git a/crates/metal2vulkan/src/tests/engine_rgbx_storage.rs b/crates/metal2vulkan/src/tests/engine_rgbx_storage.rs index baa9625a3..84d0826cf 100644 --- a/crates/metal2vulkan/src/tests/engine_rgbx_storage.rs +++ b/crates/metal2vulkan/src/tests/engine_rgbx_storage.rs @@ -10,7 +10,8 @@ //! too); a write, `access::write` or `read_write`, stores the plain write's texel with its fourth //! lane the green lane's bits, after the class's conversion. An sRGB twin's `SrgbEncode`, and an //! `_sRGB` format's at any storage slot, reads and writes Metal's codes through its twelve-bit -//! tables, with and without the RGBX conversion. +//! tables, with and without the RGBX conversion. An `RGB9E5Float` texture's `SharedExponentBits` +//! writes Metal's truncated shared-exponent word through its `R32_UINT` alias and reads it exactly. //! //! `llvm-as` assembles the kernels; without it the tests skip visibly. @@ -588,3 +589,163 @@ fn an_srgb_storage_write_stores_metals_codes() { } assert!(ran > 0); } + +/// The choice of an `RGB9E5Float` texture at a storage slot of a device that does not store the +/// format: its `R32_UINT` alias, holding Metal's word (`SharedExponentBits`). +const SHARED_EXPONENT: (vk::Format, StorageImageClass) = + (vk::Format::R32_UINT, StorageImageClass::SharedExponentBits); + +/// The `RGB9E5Float` word Metal stores for red, green and blue `rgb` (an Apple M3 Max under macOS +/// 27.0.1, our own probe: every texel of 65,536 `float` and 65,536 `half` kernel writes): each +/// channel clamped to `[0, 65408]` (a NaN, a negative value and `-0` 0), the exponent +/// `max(⌊log2 m⌋, -16) + 16` of the largest clamped channel `m`, and each mantissa the channel +/// times `2^(24 - e)` truncated. +fn shared_exponent_word(rgb: [f32; 3]) -> u32 { + let c = rgb.map(|v| match v.is_nan() || v.is_sign_negative() { + true => 0.0, + false => v.min(65408.0), + }); + let m = c[0].max(c[1]).max(c[2]); + let field = (m.to_bits() >> 23) as i32; + let e = (field.max(111) - 111) as u32; + let scale = 2f64.powi(24 - e as i32); + let mantissa = c.map(|v| ((f64::from(v) * scale).floor() as u32).min(511)); + mantissa[0] | mantissa[1] << 9 | mantissa[2] << 18 | e << 27 +} + +/// The values the shared-exponent tests write, three a texel: the specials, the values at and +/// around each exponent's mantissa steps and the clamp, and spread random values from `2^-30` +/// to past the clamp. +fn shared_exponent_values(half: bool) -> Vec<[f32; 3]> { + use crate::float16::{f16_bits_to_f32, f32_to_f16_bits}; + let specials = [ + 0.0, + -0.0, + -1.0, + f32::NAN, + f32::INFINITY, + f32::NEG_INFINITY, + 65408.0, + 65472.0, + 65504.0, + 65536.0, + 2f32.powi(-16), + 2f32.powi(-17), + 2f32.powi(-24), + 2f32.powi(-25), + f32::from_bits(1), + 1.0, + 0.5, + ]; + let mut out: Vec<[f32; 3]> = specials + .iter() + .flat_map(|&a| specials.iter().map(move |&b| [a, b, 0.25 * b])) + .collect(); + let mut s: u64 = 0x2545_F491_4F6C_DD1D; + let mut next = || { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + s + }; + for _ in 0..384 { + let e = (next() % 48) as i32 - 30; + let big = 2f32.powi(e) * (1.0 + (next() % 1024) as f32 / 1024.0); + let frac = |r: u64| (r % 65536) as f32 / 65536.0; + out.push([big, big * frac(next()), big * frac(next()) * frac(next())]); + // A mantissa step's edge: `k + 1/2` units of the exponent's step, and one ulp either side. + let unit = 2f32.powi(e.clamp(-24, 7)); + let k = (next() % 511) as f32; + let edge = (k + 0.5) * unit; + out.push([ + edge, + f32::from_bits(edge.to_bits() + 1), + f32::from_bits(edge.to_bits() - 1), + ]); + } + if half { + for t in &mut out { + *t = t.map(|v| f16_bits_to_f32(f32_to_f16_bits(v))); + } + } + out +} + +/// A write of an `RGB9E5Float` texture through its `R32_UINT` alias (`SharedExponentBits`), +/// `access::write` and `read_write`, of `float` and `half` texels, stores Metal's word. +#[test] +fn a_shared_exponent_storage_write_stores_metals_word() { + let mut ran = 0; + for texel in [Texel::Float, Texel::Half] { + let values = shared_exponent_values(texel == Texel::Half); + let width = u32::try_from(values.len()).expect("texels"); + let bytes: Vec = values + .iter() + .flat_map(|rgb| { + let lanes = [rgb[0], rgb[1], rgb[2], 1.0]; + lanes.into_iter().flat_map(move |v| match texel { + Texel::Half => crate::float16::f32_to_f16_bits(v).to_le_bytes().to_vec(), + _ => v.to_bits().to_le_bytes().to_vec(), + }) + }) + .collect(); + for access in ["write", "read_write"] { + let what = format!("{texel:?} {access}"); + let Some(bc) = assemble(&what, &write_kernel(texel, access)) else { + return; + }; + for (stem, p) in committed_profiles().expect("profiles") { + let what = format!("{what} on {stem}"); + let (plan, m) = compiled(&bc, &p, &inputs(SHARED_EXPONENT, false), &what); + let img = image_of(width, |_| [0x5a5a_5a5a; 4], robust(&p)); + let (_, got) = run_over(width, &m, &resources(&plan, bytes.clone()), &img); + for (n, rgb) in values.iter().enumerate() { + let at = img.index(0, 0, 0, [n as u32, 0, 0]).expect("texel"); + let want = shared_exponent_word(*rgb); + assert_eq!(got[at][0], want, "{what}: values {rgb:?}"); + } + ran += 1; + } + } + } + assert!(ran > 0); +} + +/// A `read_write` read of an `RGB9E5Float` texture through its `R32_UINT` alias +/// (`SharedExponentBits`) is Metal's: each channel its mantissa times `2^(e - 24)`, exact in +/// `float` and in `half`, and alpha 1, for words of every exponent. +#[test] +fn a_shared_exponent_storage_read_decodes_exactly() { + let mut ran = 0; + let words: Vec = (0..256u32) + .map(|n| (n % 32) << 27 | (n * 37 % 512) | (n * 101 % 512) << 9 | (511 - n % 512) << 18) + .collect(); + let value = |w: u32, c: u32| ((w >> (9 * c)) & 0x1ff) as f32 * 2f32.powi((w >> 27) as i32 - 24); + for texel in [Texel::Float, Texel::Half] { + let what = format!("{texel:?}"); + let Some(bc) = assemble(&what, &read_kernel(texel, 0)) else { + return; + }; + for (stem, p) in committed_profiles().expect("profiles") { + let what = format!("{what} on {stem}"); + let (plan, m) = compiled(&bc, &p, &inputs(SHARED_EXPONENT, false), &what); + let img = image_of(256, |n| [words[n as usize], 0, 0, 1], robust(&p)); + let size = if texel == Texel::Half { 8 } else { 16 }; + let fill = vec![0xab; size * 256]; + let (got, _) = run_over(256, &m, &resources(&plan, fill), &img); + for (n, &w) in words.iter().enumerate() { + for c in 0..4u32 { + let v = if c == 3 { 1.0 } else { value(w, c) }; + let want = match texel { + Texel::Half => u32::from(crate::float16::f32_to_f16_bits(v)), + _ => v.to_bits(), + }; + let read = lane(&got, texel, n as u32, c as usize); + assert_eq!(read, want, "{what}: word {w:#x} lane {c}"); + } + } + ran += 1; + } + } + assert!(ran > 0); +} diff --git a/crates/metal2vulkan/src/tests/engine_srgb_raw.rs b/crates/metal2vulkan/src/tests/engine_srgb_raw.rs index 160879bea..56b26a59a 100644 --- a/crates/metal2vulkan/src/tests/engine_srgb_raw.rs +++ b/crates/metal2vulkan/src/tests/engine_srgb_raw.rs @@ -13,7 +13,8 @@ //! sample both, its note conditional on the bound sampler's word), and that without the //! variant every access records the fact and nothing else. //! - On the CPU interpreter, a linear sample through a runtime sampler under the variant is the -//! raw emulation's sum where the word reaches it, as a constexpr sampler's is. +//! raw emulation's sum where the word reaches it, as a constexpr sampler's is; where the word +//! reads one texel the device samples the raw view, and the decode note does not hold there. //! - The binder joins a slot bound in an 8-bit sRGB format to the plan's variant, the variant's //! plan states the same key, and its raw bindings view the image in the UNORM format of the //! same channels, on every committed profile. @@ -234,6 +235,14 @@ fn inputs(variant: bool) -> LowerInputs { i } +/// Lowering inputs with slot 0 in the `SrgbTexture` variant and bound to a format held as its +/// UNORM twin (`LoweringInputs::srgb_twins`). +fn twin_inputs() -> LowerInputs { + let mut i = inputs(true); + i.srgb_twins.insert(TEXTURE); + i +} + fn lavapipe() -> crate::device::profile::DeviceProfile { profile("lavapipe", EXACT_SAMPLING).expect("profile") } @@ -445,6 +454,119 @@ fn raw_reads_and_fetches_decode_every_code_as_metal_does() { } } +/// A read of an 8-bit sRGB texture whose swizzle moves a code between a color lane and alpha +/// (`abgr`) decodes each code by its own channel and then swizzles, as plain Metal does, under +/// the slot's `swizzled_storage` variant (the view takes no swizzle): each lane is its source +/// channel's quotient, a color channel's step over 4095 on alpha's lane and alpha's code over 255 +/// on red's, bit for bit, on the interpreter. +#[test] +fn a_swizzled_srgb_read_decodes_before_its_swizzle() { + use crate::metal::{TextureSwizzle as S, TextureSwizzleChannels}; + let Some(bc) = assemble("read float", &kernel(Access::Read, false)) else { + return; + }; + let swizzle = TextureSwizzleChannels { + red: S::Alpha, + green: S::Blue, + blue: S::Green, + alpha: S::Red, + }; + let source = [3usize, 2, 1, 0]; + for (stem, p) in [("lavapipe", lavapipe()), ("moltenvk-m3", m3())] { + let mut under = inputs(true); + under.swizzled_storage.insert(TEXTURE); + let (plan, m) = + typed_module_with(&bc, "k", &p, &under).unwrap_or_else(|e| panic!("{stem}: {e}")); + let raw = resource(&m, |k| *k == ResourceKind::RawTexture) + .unwrap_or_else(|| panic!("{stem}: no raw binding")); + let mut own = Image::new( + ResourceSlot { + stage: Stage::Kernel, + kind: ResourceKind::Texture, + index: 0, + }, + [SIDE, SIDE, 1], + 1, + 1, + 1, + ); + own.texels.fill([0x7fc0_0001; 4]); + let mut res = resources(&plan, 16); + res.spec + .insert(SpecKey::TextureSwizzle(TEXTURE), u64::from(swizzle.word())); + let out = run(&m, &res, &[raw_image(raw), own]); + for n in 0..SIDE * SIDE { + let codes = codes(n); + for (lane, &from) in source.iter().enumerate() { + let (k, d) = quotient(from, codes[from]); + let i = n as usize * 16 + 4 * lane; + let got = u32::from_le_bytes([out[i], out[i + 1], out[i + 2], out[i + 3]]); + assert_eq!( + got, + f32_bits(k, d), + "{stem}: texel {n} lane {lane} (channel {from}, code {})", + codes[from] + ); + } + } + } +} + +/// The plan of a slot bound in an 8-bit sRGB format with a swizzle names the slot in +/// `VariantKey::swizzled_storage`, and its views take no swizzle, exactly where the swizzle moves +/// a code between a color lane and alpha; a swizzle among the color lanes or to constants keeps +/// the views' component mapping, which reads the same. +#[test] +fn an_srgb_swizzle_across_alpha_swizzles_in_the_function() { + use crate::metal::{TextureSwizzle as S, TextureSwizzleChannels}; + let Some(bc) = assemble("read float", &kernel(Access::Read, false)) else { + return; + }; + let channels = |red, green, blue, alpha| TextureSwizzleChannels { + red, + green, + blue, + alpha, + }; + let cases = [ + (channels(S::Alpha, S::Blue, S::Green, S::Red), true), + (channels(S::Red, S::Green, S::Blue, S::Red), true), + (channels(S::Alpha, S::Green, S::Blue, S::Alpha), true), + (channels(S::Blue, S::Green, S::Red, S::Alpha), false), + (channels(S::Red, S::Red, S::Red, S::One), false), + (channels(S::Zero, S::Green, S::One, S::Alpha), false), + ]; + let mut planned = 0; + for (stem, dev) in devices() { + let variant = pipeline(&dev, &bc, &inputs(true)); + for (swizzle, crosses) in cases { + let what = format!("{stem} {swizzle:?}"); + let mut state = state(Some(PixelFormat::RGBA8UnormSRGB)); + if let Some(BoundTexture::Texture { facts, .. }) = state + .stages + .get_mut(&Stage::Kernel) + .and_then(|t| t.textures.get_mut(&0)) + { + facts.swizzle = swizzle; + } + let Ok(plan) = variant.plan(&dev, &state.shape()) else { + continue; + }; + assert_eq!( + plan.variant.swizzled_storage.contains(&TEXTURE), + crosses, + "{what}" + ); + let (raw, own) = views(&variant, &plan); + for v in raw.iter().chain(own.iter()).filter_map(view_of) { + assert_eq!(v.shader_swizzle, crosses, "{what}"); + } + planned += 1; + } + } + assert!(planned > 0, "no committed profile planned the texture"); +} + /// Where an access reads the raw view under the variant. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Raw { @@ -1161,8 +1283,219 @@ fn runtime_raw_filters_sum_the_steps_where_the_word_reaches() { } } +/// How many device samples (`OpImageSample*`) of `m` read the combined binding at `slot`: their +/// sampled image loaded from the slot's variable. +fn samples_of(m: &TypedModule, slot: ResourceSlot) -> usize { + use crate::spirv::ir::Inst; + let Some(var) = m.globals().iter().find_map(|g| match g.kind { + GlobalKind::Resource(s) if s == slot => Some(g.value), + _ => None, + }) else { + return 0; + }; + let insts = || m.blocks().iter().flat_map(|b| &b.insts); + let loads: BTreeSet = insts() + .filter_map(|n| match (&n.inst, n.result) { + (Inst::Load { ptr, .. }, Some(r)) if *ptr == var => Some(r.0), + _ => None, + }) + .collect(); + insts() + .filter(|n| { + matches!(&n.inst, Inst::ImageSample { sampled_image, .. } + if loads.contains(&sampled_image.0)) + }) + .count() +} + +/// Under the variant a runtime sampler's sample (2D `half` and `float`, 3D, and 1D) whose bound +/// word reads one texel (nearest minification and magnification, no linear mip filter, isotropic) +/// samples the slot's raw view through the same sampler and decodes the code through Metal's table, +/// as a constexpr nearest sample's raw read does: the module samples the raw binding as well as the +/// decoding one, and `PrecisionNote::SrgbTexelDecode` holds only where the word filters but does +/// not reach the emulation, not under a nearest word with or without a nearest mip filter. On +/// lavapipe; every form validates. +#[test] +fn a_runtime_raw_sample_reads_one_texel_through_the_raw_view() { + use crate::metal::sampler::SamplerWord; + use crate::metal::SamplerAddressMode; + let mut clamp = 0; + for shift in SamplerWord::ADDRESS_SHIFT { + clamp |= SamplerAddressMode::ClampToEdge.as_raw() << shift; + } + let mip = |m: u32| m << SamplerWord::MIP_FILTER_SHIFT; + // A word and whether the device decodes under it. + let words = [ + ("nearest", 0, false), + ("nearest, nearest mip", mip(1), false), + ("nearest, linear mip", mip(2), true), + ("linear minification", SamplerWord::MIN_LINEAR, true), + ("linear", SamplerWord::LINEAR, false), + ("linear, linear mip", SamplerWord::LINEAR | mip(2), true), + ]; + let class = crate::metal::texel_format::texel_format(PixelFormat::RGBA8UnormSRGB); + let p = lavapipe(); + let consts = FunctionConstantValues::defaults(); + let kernels = [ + ("runtime 2d half", kernel(Access::Runtime, true)), + ("runtime 2d float", kernel(Access::Runtime, false)), + ("runtime 3d float", filter_kernel_through(None, 3, false)), + ("runtime 1d half", filter_kernel_through(None, 1, true)), + ]; + for (name, k) in kernels { + let Some(bc) = assemble(name, &k) else { + return; + }; + let a = compile_bitcode( + &bc, + EntryRef::Name("k"), + &consts, + &p, + &inputs(true), + &mut meter(), + SPIRV_WORDS, + ) + .unwrap_or_else(|e| panic!("{name}: {e}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); + let (_, m) = typed_module_with(&bc, "k", &p, &inputs(true)) + .unwrap_or_else(|e| panic!("{name}: {e}")); + let raw = resource(&m, raw_combined).unwrap_or_else(|| panic!("{name}: no raw binding")); + let own = resource( + &m, + |k| matches!(k, ResourceKind::CombinedTextureSampler(c) if !c.raw), + ) + .unwrap_or_else(|| panic!("{name}: no decoding binding")); + assert!(samples_of(&m, raw) >= 1, "{name}: the raw view's sample"); + assert!( + samples_of(&m, own) >= 1, + "{name}: the decoding view's sample" + ); + let Some(note) = a + .specialized + .iter() + .find(|s| s.note == PrecisionNote::SrgbTexelDecode) + else { + panic!("{name}: no conditional decode note: {:?}", a.specialized); + }; + let fields: Vec<(SpecKey, u32)> = a + .interface + .read_keys() + .into_iter() + .filter_map(|k| match k { + SpecKey::SamplerState { fields, .. } => Some((k, fields)), + _ => None, + }) + .collect(); + let [(sampler, fields)] = fields[..] else { + panic!("{name}: the sampler's `SamplerState` specialization: {fields:?}"); + }; + for (what, filter, decodes) in words { + let word = (clamp | filter) & fields; + let holds = note.when.iter().any(|clause| { + clause.all.iter().all(|t| { + let v = match t.key { + k if k == sampler => word, + SpecKey::TexelFormat(_) | SpecKey::BoundTexelFormat(_) => class.0, + k => panic!("{name}: a decode note's test of {k:?}"), + }; + (v & t.mask == t.bits) == t.equal + }) + }); + assert_eq!(holds, decodes, "{name} under a {what} word"); + } + } +} + +/// A kernel sampling element `ks[tid]` (`uint` buffer 2) of an array of `n` `texture2d` +/// slots through the runtime `[[sampler(0)]]` at `float2` buffer 0's lane `tid`, storing the +/// `half4` to buffer 1 (the null texture where `ks[tid]` is past the array): a switch-at-use. +fn switch_kernel(n: u32) -> String { + format!( + r#"%"struct.metal::texture2d" = type {{ ptr addrspace(1) }} + +define void @k(ptr readonly byval([{n} x ptr addrspace(1)]) %t, ptr addrspace(1) %c, ptr addrspace(1) %out, ptr addrspace(1) %ks, ptr addrspace(2) %s, i32 %tid) {{ + %i = zext i32 %tid to i64 + %p = getelementptr inbounds <2 x float>, ptr addrspace(1) %c, i64 %i + %uv = load <2 x float>, ptr addrspace(1) %p, align 8 + %pk = getelementptr inbounds i32, ptr addrspace(1) %ks, i64 %i + %k = load i32, ptr addrspace(1) %pk, align 4 + %past = icmp uge i32 %k, {n} + %kc = select i1 %past, i32 0, i32 %k + %kk = zext i32 %kc to i64 + %e = getelementptr inbounds [{n} x %"struct.metal::texture2d"], ptr %t, i64 0, i64 %kk, i32 0 + %elem = load ptr addrspace(1), ptr %e, align 8 + %h = select i1 %past, ptr addrspace(1) null, ptr addrspace(1) %elem + %r = call {{ <4 x half>, i8 }} @air.sample_texture_2d.v4f16(ptr addrspace(1) %h, ptr addrspace(2) %s, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.0, float 0.0, i32 0) + %v = extractvalue {{ <4 x half>, i8 }} %r, 0 + %q = getelementptr inbounds <4 x half>, ptr addrspace(1) %out, i64 %i + store <4 x half> %v, ptr addrspace(1) %q, align 8 + ret void +}} + +declare {{ <4 x half>, i8 }} @air.sample_texture_2d.v4f16(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32) + +!air.kernel = !{{!0}} +!0 = !{{ptr @k, !1, !2}} +!1 = !{{}} +!2 = !{{!3, !4, !5, !6, !7, !8}} +!3 = !{{i32 0, !"air.texture", !"air.location_index", i32 0, i32 {n}, !"air.sample", !"air.arg_type_name", !"array, {n}>", !"air.arg_name", !"t"}} +!4 = !{{i32 1, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"float2", !"air.arg_name", !"c"}} +!5 = !{{i32 2, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"half4", !"air.arg_name", !"out"}} +!6 = !{{i32 3, !"air.buffer", !"air.location_index", i32 2, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"ks"}} +!7 = !{{i32 4, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"s"}} +!8 = !{{i32 5, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"}} +"# + ) +} + +/// A switch-at-use over texture slots under the variant, sampled through a runtime sampler, reads +/// each slot's raw view where the word reads one texel, as one slot's sample does: on lavapipe the +/// module samples every slot's raw binding, its estimate bounds its emission, and it validates. +#[test] +fn a_switch_of_raw_slots_reads_one_texel_through_each_raw_view() { + let p = lavapipe(); + let consts = FunctionConstantValues::defaults(); + for n in [2u32, 4] { + let name = format!("switch of {n}"); + let Some(bc) = assemble(&name, &switch_kernel(n)) else { + return; + }; + let mut under = LowerInputs::new(); + for index in 0..n { + under.srgb_textures.insert(SlotRef { index, ..TEXTURE }); + } + let entry = EntryRef::Name("k"); + let plan = plan_bitcode(&bc, entry, &consts, &p, &under, &mut meter()) + .unwrap_or_else(|e| panic!("{name}: {e}")); + let a = compile_bitcode(&bc, entry, &consts, &p, &under, &mut meter(), SPIRV_WORDS) + .unwrap_or_else(|e| panic!("{name}: {e}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name}: {e}")); + let words = a.module.words.len() as u64; + assert!( + plan.estimate.words >= words, + "{name}: estimate {} < emitted {words}", + plan.estimate.words + ); + let (_, m) = + typed_module_with(&bc, "k", &p, &under).unwrap_or_else(|e| panic!("{name}: {e}")); + let raw: Vec = m + .globals() + .iter() + .filter_map(|g| match g.kind { + GlobalKind::Resource(s) if raw_combined(&s.kind) => Some(s), + _ => None, + }) + .collect(); + assert_eq!(raw.len(), n as usize, "{name}: the raw bindings {raw:?}"); + for slot in raw { + assert!(samples_of(&m, slot) >= 1, "{name}: {slot:?} is not sampled"); + } + } +} + /// The plan's word estimate bounds the emitted module of every raw form under the variant (a -/// runtime sampler's emulation beside its device arm included), on every committed profile, and +/// runtime sampler's emulation beside its device arm included), with the slot bound to a twin +/// (whose device arm decodes the filtered codes) and without, on every committed profile, and /// every form validates there. #[test] fn the_raw_estimate_bounds_its_emission() { @@ -1220,21 +1553,29 @@ fn the_raw_estimate_bounds_its_emission() { let Some(bc) = assemble(name, &k) else { return; }; - for (stem, p) in committed_exact_profiles().expect("profiles") { - let what = format!("{name} on {stem}"); + // Native sampling's profiles too: a runtime sampler's sample there keeps the device's + // arm alone, which decodes a twin's filtered codes. + let native = crate::spirv::testing::committed_profiles() + .expect("profiles") + .into_iter() + .map(|(stem, p)| (format!("{stem} native"), p)); + for ((stem, p), (twin, under)) in committed_exact_profiles() + .expect("profiles") + .into_iter() + .chain(native) + .flat_map(|sp| { + [ + (sp.clone(), ("", inputs(true))), + (sp, (" twin", twin_inputs())), + ] + }) + { + let what = format!("{name}{twin} on {stem}"); let entry = EntryRef::Name("k"); - let plan = plan_bitcode(&bc, entry, &consts, &p, &inputs(true), &mut meter()) + let plan = plan_bitcode(&bc, entry, &consts, &p, &under, &mut meter()) + .unwrap_or_else(|e| panic!("{what}: {e}")); + let a = compile_bitcode(&bc, entry, &consts, &p, &under, &mut meter(), SPIRV_WORDS) .unwrap_or_else(|e| panic!("{what}: {e}")); - let a = compile_bitcode( - &bc, - entry, - &consts, - &p, - &inputs(true), - &mut meter(), - SPIRV_WORDS, - ) - .unwrap_or_else(|e| panic!("{what}: {e}")); let words = a.module.words.len() as u64; eprintln!("{what}: estimate {} emitted {words}", plan.estimate.words); assert!( @@ -1624,15 +1965,18 @@ fn metals_own_srgb_decode_converts_to_half_as_metal_does() { } /// Under the variant, a form the raw codes do not serve (a runtime sampler's sample) states -/// `RuntimeFact::SrgbDeviceDecode`, so a profile that samples the bound format only through its -/// UNORM twin refuses the texture there, naming the format; the plain pipeline's plan still names -/// the variant. +/// `RuntimeFact::SrgbDeviceDecode`. On a profile that samples the bound format only through its +/// UNORM twin, the plan names the slot in `VariantKey::srgb_twins` beside `srgb_textures`, from +/// the device's format features alone; the pipeline compiled under that key notes +/// `PrecisionNote::SrgbTexelDecode` (the device's filter of the codes, decoded through the table), +/// validates, plans the same key with every binding of the slot viewing the image in the twin's +/// format, and refuses nothing. A profile that samples the format leaves the twins empty. #[test] -fn a_device_decode_refuses_a_format_sampled_only_through_its_twin() { +fn a_device_decode_samples_the_twin_of_a_format_the_device_cannot_sample() { let Some(bc) = assemble("runtime float", &kernel(Access::Runtime, false)) else { return; }; - let mut refused = 0; + let (mut twinned, mut sampled_count) = (0, 0); for (stem, dev) in devices() { let plain = pipeline(&dev, &bc, &inputs(false)); for pf in [ @@ -1651,7 +1995,7 @@ fn a_device_decode_refuses_a_format_sampled_only_through_its_twin() { .is_ok() }; let twin = crate::metal::format::srgb_raw_twin(pf).expect(&what); - if sampled(pf) || !sampled(twin) { + if !sampled(pf) && !sampled(twin) { continue; } let shape = state(Some(pf)).shape(); @@ -1663,6 +2007,12 @@ fn a_device_decode_refuses_a_format_sampled_only_through_its_twin() { BTreeSet::from([TEXTURE]), "{what}" ); + if sampled(pf) { + assert!(plan.variant.srgb_twins.is_empty(), "{what}"); + sampled_count += 1; + continue; + } + assert_eq!(plan.variant.srgb_twins, BTreeSet::from([TEXTURE]), "{what}"); let variant = pipeline(&dev, &bc, &plan.variant.lowering_inputs(Stage::Kernel)); assert!( variant @@ -1671,20 +2021,52 @@ fn a_device_decode_refuses_a_format_sampled_only_through_its_twin() { .any(|d| d.fact == RuntimeFact::SrgbDeviceDecode { slot: TEXTURE }), "{what}" ); - match variant.plan(&dev, &shape) { - Err(crate::error::BindError::Unsupported(u)) - if u.feature == crate::error::Feature::Format => - { - refused += 1 - } - other => panic!("{what}: {other:?}"), - } + let twins = plan.variant.lowering_inputs(Stage::Kernel); + let (lowered, _) = typed_module_with(&bc, "k", dev.profile(), &twins) + .unwrap_or_else(|e| panic!("{what}: {e}")); + assert!( + lowered.precision.contains(&PrecisionNote::SrgbTexelDecode), + "{what}: {:?}", + lowered.precision + ); + let a = compile_bitcode( + &bc, + EntryRef::Name("k"), + &FunctionConstantValues::defaults(), + dev.profile(), + &twins, + &mut meter(), + SPIRV_WORDS, + ) + .unwrap_or_else(|e| panic!("{what}: {e}")); + link_and_validate(&a, dev.profile()).unwrap_or_else(|e| panic!("{what}: {e}")); + let again = variant + .plan(&dev, &shape) + .unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!(again.variant, plan.variant, "{what}"); + let (raw, own) = views(&variant, &again); + let formats: BTreeSet<_> = raw + .iter() + .chain(own.iter()) + .filter_map(view_of) + .map(|v| v.format) + .collect(); + assert_eq!( + formats, + BTreeSet::from([crate::metal::format::direct_format(twin).expect(&what)]), + "{what}" + ); + twinned += 1; } } assert!( - refused > 0, + twinned > 0, "no committed profile samples a format only through its twin" ); + assert!( + sampled_count > 0, + "no committed profile samples the formats" + ); } /// A render pipeline: a vertex function placing vertex `vid`, and a fragment function returning diff --git a/crates/metal2vulkan/src/tests/engine_texture.rs b/crates/metal2vulkan/src/tests/engine_texture.rs index 0591e0a7a..6bddb9a84 100644 --- a/crates/metal2vulkan/src/tests/engine_texture.rs +++ b/crates/metal2vulkan/src/tests/engine_texture.rs @@ -208,7 +208,7 @@ fn bgra8_and_rgba8_storage_textures_compile_to_distinct_modules() { return; }; let slot = texture_slot(0); - let (mut swizzled, mut srgb) = (0, 0); + let (mut swizzled, mut srgb, mut srgb_bgra) = (0, 0, 0); for (stem, p) in committed_profiles().expect("profiles") { let variant = |pf: PixelFormat| { let choice = storage_image_choice(pf, &p).ok()?; @@ -242,24 +242,46 @@ fn bgra8_and_rgba8_storage_textures_compile_to_distinct_modules() { ); } } - if let Some((choice, s)) = variant(PixelFormat::RGBA8UnormSRGB) { + let table = |a: &FunctionArtifact| { + a.strategies + .entries + .contains_key(crate::lower::arith::SRGB_PACK) + }; + let srgb_rgba = variant(PixelFormat::RGBA8UnormSRGB); + if let Some((choice, s)) = &srgb_rgba { if choice.class == StorageImageClass::SrgbEncode { srgb += 1; assert!(!s.precision.contains(&PrecisionNote::DeviceTranscendentals)); assert_ne!(s.key, rgba.key, "{stem}"); // instructions' count: an rgba8 write rounds to Metal's codes in the shader too // where the device is not measured to store them. - let table = |a: &FunctionArtifact| { - a.strategies - .entries - .contains_key(crate::lower::arith::SRGB_PACK) - }; - assert!(table(&s) && !table(&rgba), "{stem}"); + assert!(table(s) && !table(&rgba), "{stem}"); + } + } + // bgra8 sRGB through rgba8: the encode's table, and red and blue exchanged after it. + if let Some((choice, b)) = variant(PixelFormat::BGRA8UnormSRGB) { + if choice.class == StorageImageClass::SrgbEncodeBgra { + srgb_bgra += 1; + assert!(table(&b), "{stem}"); + assert_ne!(b.key, rgba.key, "{stem}"); + if let Some((c, s)) = &srgb_rgba { + if c.class == StorageImageClass::SrgbEncode { + assert_ne!(b.key, s.key, "{stem}"); + assert!( + count(&b, OP_VECTOR_SHUFFLE) > count(s, OP_VECTOR_SHUFFLE), + "{stem}" + ); + } + } } } } assert!(swizzled > 0, "no committed profile exercises SwizzleBgra"); assert!(srgb > 0, "no committed profile exercises SrgbEncode"); + assert!( + srgb_bgra > 0, + "no committed profile exercises SrgbEncodeBgra" + ); } /// A texture buffer is a buffer image; both slots carry the texel-buffer range fact and the storage diff --git a/docs/API.md b/docs/API.md index 756207658..18cb4bad2 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2151,7 +2151,8 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. magnification, or a runtime sampler) on a device that does not sample through Metal's own sampler. - `metal2vulkan-degrade-srgb-texel-decode` (precision). `PrecisionNote::SrgbTexelDecode`: The module reads, samples, or gathers a texture with a `half` or `float` result through the device's sRGB - decode where the texture may be bound in an 8-bit sRGB format. + decode, or decodes the device's filter of its codes, where the texture may be bound in an 8-bit + sRGB format. - `metal2vulkan-degrade-float-sample-filter` (precision). `PrecisionNote::FloatSampleFilter`: The module samples a texture with a `float` result through a filter on a device that does not sample through Metal's own sampler. diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index c61f6ed06..597f2f5de 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -178,6 +178,12 @@ recorded here. Open differences from Metal that no note announces yet, and runtime costs still above the driver's. Each is open work. +- **A runtime sampler's nearest sample of an 8-bit sRGB texture under native sampling.** On a + device that samples the format, the sample keeps the device's sRGB decode (announced as + `SrgbTexelDecode`), where the table's exact decode of the one texel it reads would cost little: + 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. - **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