diff --git a/crates/metal2vulkan-runtime/src/astc.rs b/crates/metal2vulkan-runtime/src/astc.rs new file mode 100644 index 000000000..c8678cf09 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/astc.rs @@ -0,0 +1,182 @@ +//! ASTC LDR textures on a device without their ASTC block: their blocks held as raw bytes in a +//! carrier, which copies move, and their samples read a decoded twin. +//! +//! - **Metal's answers** (an Apple M3 Max under macOS 27.0.1, our own probe): every ASTC LDR +//! format makes a texture, `Shared`, `Private` and memoryless, of every type but 1D and +//! multisampled, of `ShaderWrite` and `RenderTarget` usage too, and views as its sRGB or HDR +//! form. `getBytes` and a blit out of the texture hand back the blocks a write put there; a new +//! texture's blocks are zeros, which read magenta (an error block). Its reads and samples are +//! `bind::AstcDecode`'s. +//! - **The store.** Vulkan copies a compressed image's blocks as bytes. Such a texture holds its +//! blocks in an image of a *carrier*: a compressed format whose blocks are also 16 bytes, over +//! 4 x 4 texels, the first of [`CARRIERS`] the device copies (every Vulkan device has BC or ETC2, +//! which hold one). Each of the texture's blocks lies over 4 x 4 carrier texels, so a region of +//! the texture's blocks is a region of the carrier's ([`image_region`]). A level of the carrier +//! holds at least the blocks the texture's level holds ([`carrier_side`]): the carrier's side is +//! the least whose every level, halved as Vulkan halves it, keeps them (at most about the +//! texture's side in texels, 1 byte a texel), and a copy addresses the first of them. +//! - **What it serves.** Copies between buffers and the texture and between textures (fills +//! included), and the CPU's copies, move its blocks through the carrier, so `getBytes` and a +//! blit out of it hand back the blocks written. Its sampled views present its decoded twin +//! (`texture/decoded_twin.rs`), Metal's decode of the blocks in the texels +//! `DevicePolicy::decoded_texels` names (an sRGB form's 8-bit codes under either, which its +//! slots read raw and decode through Metal's table, exactly), decoded after each write as a BC +//! texture's twin is: on the GPU (`bind::astc_decode_module`), or a host write's on the CPU. +//! A view in the texture's other colour space (its `_sRGB` or LDR form) presents a second twin +//! of that form's decode, made at the first such view. Refused: a heap's or a sparse heap's +//! texture (`RuntimeGap::DecodedHeapTexture`) and a view of another decode (the texture's HDR +//! form, or another footprint; `Feature::TextureView`). A shader write and +//! an attachment take no such image: Metal's functions write no compressed texture, and no pass +//! renders into one. + +use super::copy_plan::ImageRegion; +use super::image_plan::{sample_count, ImageFacts, ImagePlan}; +use super::texture_descriptor::{effective_usage, TextureLayout}; +use metal2vulkan::bind::AstcDecode; +use metal2vulkan::device::FormatUsage; +use metal2vulkan::metal::format::{image_type, vk_format, FormatEmulation, FormatMapping}; +use metal2vulkan::metal::TextureUsage; +use metal2vulkan::vk::{ + Format, FormatFeatureFlags2, ImageAspectFlags, ImageCreateFlags, ImageUsageFlags, +}; + +/// The compressed formats whose blocks are 16 bytes over 4 x 4 texels, in the order an ASTC +/// texture's blocks take the first the device copies: BC7, BC3, BC2 and BC5 (desktop GPUs), then +/// ETC2's and EAC's (mobile GPUs). +pub(super) const CARRIERS: [Format; 6] = [ + Format::BC7_UNORM_BLOCK, + Format::BC3_UNORM_BLOCK, + Format::BC2_UNORM_BLOCK, + Format::BC5_UNORM_BLOCK, + Format::ETC2_R8G8B8A8_UNORM_BLOCK, + Format::EAC_R11G11_UNORM_BLOCK, +]; + +/// The decode of the ASTC texture whose blocks `plan` holds in a carrier; `None` for any other +/// image. +pub(super) fn decode_of(plan: &ImagePlan) -> Option { + AstcDecode::of(plan.pixel_format).filter(|_| CARRIERS.contains(&plan.format)) +} + +/// The least carrier side, in carrier texels, whose `levels` levels each hold the blocks of +/// `block` texels a side that a texture of `side` texels holds at that level: the carrier's level +/// `l`, `max(1, c >> l)` wide, holds `ceil(max(1, c >> l) / 4)` blocks, at least `n` where +/// `c >= (4 n - 3) << l`. The last level's term is at least `2^(levels - 1)`, so the carrier takes +/// every level. +pub(super) fn carrier_side(side: u32, block: u32, levels: u32) -> u32 { + (0..levels) + .map(|l| { + let blocks = (side >> l).max(1).div_ceil(block); + (4 * blocks - 3) << l + }) + .max() + .unwrap_or(1) +} + +/// The image of an ASTC texture of `layout` with Metal `usage` on a device with `facts` that +/// holds its blocks in a carrier (the module docs): `None` for a texture of another format, or of +/// an ASTC format the device holds (its block, or no decoded twin: its refusal stands), or where +/// no carrier is copied (the device's refusal of the format stands). +pub(super) fn plan_blocks( + layout: &TextureLayout, + usage: TextureUsage, + facts: &ImageFacts<'_>, +) -> Option { + let pf = layout.pixel_format; + let decode = AstcDecode::of(pf)?; + let sampled = vk_format(pf, &[FormatUsage::SampledImage].into(), facts.profile).ok()?; + if sampled.emulation != FormatEmulation::Decoded { + return None; + } + let copies = FormatFeatureFlags2::TRANSFER_SRC | FormatFeatureFlags2::TRANSFER_DST; + let carrier = CARRIERS + .into_iter() + .find(|&f| facts.optimal(f).contains(copies))?; + // No create flags, never cube compatible: copies alone reach the carrier and no view of it is + // made, so a cube texture's faces are its layers. + let (image_type, _) = image_type(layout.texture_type)?; + let [width, height, depth] = layout.extent; + let [bw, bh] = decode.block_extent(); + Some(ImagePlan { + pixel_format: pf, + flags: ImageCreateFlags::empty(), + image_type, + format: carrier, + extent: [ + carrier_side(width, bw, layout.levels), + carrier_side(height, bh, layout.levels), + depth, + ], + levels: layout.levels, + layers: layout.layers, + samples: sample_count(layout.samples)?, + usage: ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST, + view_formats: Vec::new(), + mapping: FormatMapping::direct(carrier, ImageAspectFlags::COLOR), + // Its decoded twin serves its samples and reads. (`BlockWritesOnly` plans as + // `ShaderWrite` does, which Metal's functions never use on a compressed texture.) + unavailable: effective_usage(usage).intersection( + TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC | TextureUsage::RENDER_TARGET, + ), + }) +} + +/// `region`, in the texels of the ASTC texture whose carrier `plan` plans (a region of whole +/// blocks, or ending at the level's edge), in the carrier's texels: each block 4 x 4 of them, the +/// region's last block's ending at the carrier level's edge where that comes first. `None` for an +/// image of another kind. +pub(super) fn image_region(plan: &ImagePlan, region: ImageRegion) -> Option { + let decode = decode_of(plan)?; + let [bw, bh] = decode.block_extent(); + let [x, y, z] = region.origin; + let [width, height, depth] = region.size; + let level = |axis: usize| (plan.extent[axis] >> region.level.min(31)).max(1); + let span = |at: u32, size: u32, block: u32, axis: usize| { + let first = at / block; + let end = (at + size).div_ceil(block); + (4 * first, (4 * end).min(level(axis)) - 4 * first) + }; + let (x, width) = span(x, width, bw, 0); + let (y, height) = span(y, height, bh, 1); + Some(ImageRegion { + origin: [x, y, z], + size: [width, height, depth], + ..region + }) +} + +/// [`image_region`]'s inverse: `region` of the carrier `plan` plans, in the texture's texels, its +/// last block's ending at the texture level's edge (`extent`, the texture's level 0). `None` for +/// an image of another kind. +pub(super) fn texture_region( + plan: &ImagePlan, + extent: [u32; 3], + region: ImageRegion, +) -> Option { + let decode = decode_of(plan)?; + let [bw, bh] = decode.block_extent(); + let [x, y, z] = region.origin; + let [width, height, depth] = region.size; + let level = |axis: usize| (extent[axis] >> region.level.min(31)).max(1); + let span = |at: u32, size: u32, block: u32, axis: usize| { + let first = at / 4; + let end = (at + size).div_ceil(4); + ( + block * first, + (block * end).min(level(axis)) - block * first, + ) + }; + let (x, width) = span(x, width, bw, 0); + let (y, height) = span(y, height, bh, 1); + Some(ImageRegion { + origin: [x, y, z], + size: [width, height, depth], + ..region + }) +} + +/// A buffer row length or image height of `texels` texture texels in carrier texels: its blocks +/// of `block` texels, 4 carrier texels each (0, tightly packed, stays 0). +pub(super) fn carrier_texels(texels: u32, block: u32) -> u32 { + texels / block * 4 +} diff --git a/crates/metal2vulkan-runtime/src/blit_plan.rs b/crates/metal2vulkan-runtime/src/blit_plan.rs index 7bc561601..d62cfe2d4 100644 --- a/crates/metal2vulkan-runtime/src/blit_plan.rs +++ b/crates/metal2vulkan-runtime/src/blit_plan.rs @@ -24,6 +24,7 @@ use super::copy_plan::{ }; use super::image_plan::ImagePlan; use super::linear_plan::BufferLayout as TexelsLayout; +use super::pvrtc::is_pvrtc; use super::two_planes; use super::view_plan::ViewRecord; use metal2vulkan::error::{Feature, Unsupported}; @@ -445,7 +446,14 @@ fn texture_unit(pf: PixelFormat) -> Option<(u32, [u32; 2])> { /// Whether Metal copies between textures of `a` and `b` (macOS 26.7's rule): the same format, or /// two formats of one copy unit, whose bytes it copies, a depth or stencil format's among them -/// (probes); formats of different units are refused. +/// (probes), or a compressed format and an uncompressed one whose texel is the bytes of its block +/// (each block into one texel and back, [`source_region`]); formats of units of different bytes +/// are refused. +/// +/// The runtime's gaps: a PVRTC format with an uncompressed one, whose blocks plain Metal moves in +/// an order of its own (our probe on an Apple M3 Max under macOS 27.0.1: neither the rows nor the +/// CPU's Z order), and two compressed formats of one block's bytes and different extents (ASTC +/// 6x5 and BC7), not measured. fn check_formats(a: PixelFormat, b: PixelFormat) -> Result<(), CopyRefusal> { // Between two `YCBCR8_420_2P` textures Metal copies both of the surfaces' planes (EV // XRR2-ycc2-m4), where the runtime's copy moves the luma bytes its texels are: the runtime's @@ -458,8 +466,16 @@ fn check_formats(a: PixelFormat, b: PixelFormat) -> Result<(), CopyRefusal> { if a == b { return Ok(()); } + let not_implemented = + || CopyRefusal::Unsupported(Unsupported::not_implemented(Feature::Format).naming_format(a)); match (texture_unit(a), texture_unit(b)) { (Some(x), Some(y)) if x == y => {} + (Some((x, from)), Some((y, to))) if x == y => { + let texel = |extent: [u32; 2]| extent == [1, 1]; + if texel(from) == texel(to) || is_pvrtc(a) || is_pvrtc(b) { + return Err(not_implemented()); + } + } _ => return Err(CopyProblem::Format.into()), } // Into a 4:2:2 texture from another format of its unit plain Metal writes `0xff` over part @@ -540,7 +556,8 @@ fn pair_unit(record: &ViewRecord, image: Option<&ImagePlan>) -> Result, region: &TextureRegion, @@ -549,7 +566,8 @@ pub(super) fn plan_region_copy( dst_origin: [u32; 3], ) -> Result, CopyRefusal> { let (src_unit, dst_unit) = pair.check()?; - let src = check_region(pair.src, region, &src_unit)?; + let source = source_region(region, &src_unit, &dst_unit)?; + let src = check_region(pair.src, &source, &src_unit)?; let dst_region = TextureRegion { level: dst_level, slice: dst_slice, @@ -563,9 +581,44 @@ pub(super) fn plan_region_copy( Ok(vec![ImageCopyRegion { src, dst }]) } +/// The source's region of a region copy of `region` between textures of units `src` and `dst`: +/// `region` itself between units of one extent. Between a compressed format and an uncompressed +/// one (`check_formats`) every coordinate of the copy is in the destination's texels, the source +/// addressed as if it held the destination's format (our probe on an Apple M3 Max under macOS +/// 27.0.1: BC1 with `RG32Uint` and `RGBA16Uint`, BC7, `EAC_RGBA8` and ASTC 6x5 with +/// `RGBA32Uint`, `ETC2_RGB8` with `RG32Uint`, both ways): out of a compressed texture the origin +/// and size count its blocks (an origin of 4 is the fifth block), into one they count the +/// source's texels as the destination's, the origin rounded down to a block's texel and the size +/// up to whole blocks, each on its own (an origin of 1 and a size of 4 copy texel 0 alone). +/// Refused (`Region`) where the source's texels overflow. +fn source_region( + region: &TextureRegion, + src: &CopyUnit, + dst: &CopyUnit, +) -> Result { + let mut out = *region; + for axis in 0..2 { + let (from, to) = (src.extent[axis], dst.extent[axis]); + if from == to { + continue; + } + let (origin, size) = (region.origin[axis], region.size[axis]); + (out.origin[axis], out.size[axis]) = match to { + 1 => ( + origin.checked_mul(from).ok_or(CopyProblem::Region)?, + size.checked_mul(from).ok_or(CopyProblem::Region)?, + ), + _ => (origin / to, size.div_ceil(to)), + }; + } + Ok(out) +} + /// `copyFromTexture:sourceSlice:sourceLevel:toTexture:destinationSlice:destinationLevel: /// sliceCount:levelCount:`, and `copyFromTexture:toTexture:` (`whole`: every level and slice of -/// two textures of one shape). +/// two textures of one shape). Between a compressed and an uncompressed format (`check_formats`) +/// the runtime's gap (`NotImplemented(Format)`): which level's blocks Metal copies into which +/// level's texels is not measured. pub(super) fn plan_levels_copy( pair: &CopyPair<'_>, src_slice: u32, @@ -576,6 +629,11 @@ pub(super) fn plan_levels_copy( levels: u32, ) -> Result, CopyRefusal> { let (src_unit, dst_unit) = pair.check()?; + if src_unit.extent != dst_unit.extent { + return Err(CopyRefusal::Unsupported( + Unsupported::not_implemented(Feature::Format).naming_format(pair.src.pixel_format), + )); + } let (src, dst) = (pair.src, pair.dst); let in_range = |start: u32, count: u32, limit: u32| { start.checked_add(count).is_some_and(|end| end <= limit) diff --git a/crates/metal2vulkan-runtime/src/blit_texture.rs b/crates/metal2vulkan-runtime/src/blit_texture.rs index 4cf7680a6..4490cba9b 100644 --- a/crates/metal2vulkan-runtime/src/blit_texture.rs +++ b/crates/metal2vulkan-runtime/src/blit_texture.rs @@ -955,13 +955,21 @@ impl BlitCommandEncoder { /// /// The textures have one sample count and formats of one copy unit (macOS 26.7's rule: the /// bytes are copied, `RGBA8Unorm` into `RGBA8Uint` or `R32Uint` among them, and - /// `Depth32Float` into `R32Float` or back). + /// `Depth32Float` into `R32Float` or back), or a compressed format and an uncompressed one + /// whose texel is its block's bytes (BC1 and `RG32Uint`, BC7 and `RGBA32Uint`): each block + /// copies into one texel and back, and the origins and size are the destination's texels, the + /// source addressed as if it held the destination's format (our probe on an Apple M3 Max + /// under macOS 27.0.1: out of BC1 an origin of (4, 4) is the block from texel (16, 16); into + /// it an origin of (1, 2) and a size of 2 x 2 copy `RG32Uint` texel (0, 0) alone, into the + /// block a destination origin of (4, 4) names). /// /// A size of 0 copies as the module docs say, as plain Metal does, and a compressed region /// off its blocks copies the blocks it starts in on each side, a whole block of a level /// smaller than one included, into or out of a larger level too. Refused: what Metal stops /// (`Invalid`: with a [`CopyProblem`], formats of different copy units, different sample - /// counts, a region past either level); a copy between overlapping regions of one + /// counts, a region past either level); a PVRTC format with an uncompressed one, whose blocks + /// plain Metal moves in an order of its own, and two compressed formats of one block's bytes + /// and different extents, not measured (`NotImplemented(Format)`); a copy between overlapping regions of one /// multisampled texture (`NotImplemented(OverlappingTextureCopies)`), other than of a region /// onto itself (one texture's other overlapping regions copy as `memmove` does, the module /// docs); a copy through a scratch buffer of 24-bit depth, whose bytes Metal's reference GPUs @@ -1035,8 +1043,9 @@ impl BlitCommandEncoder { /// /// Refused as [`copy_from_texture_to_texture`](Self::copy_from_texture_to_texture) is, and /// for levels or slices past either texture and compressed levels of different sizes - /// (`Invalid`, unmeasured). A count of 0 copies nothing, wherever its slices or levels lie, - /// as plain Metal does. + /// (`Invalid`, unmeasured), and between a compressed and an uncompressed format + /// (`NotImplemented(Format)`: which levels Metal pairs is not measured). A count of 0 copies + /// nothing, wherever its slices or levels lie, as plain Metal does. pub fn copy_texture_slices( &mut self, source_texture: &Texture, diff --git a/crates/metal2vulkan-runtime/src/chroma_pairs.rs b/crates/metal2vulkan-runtime/src/chroma_pairs.rs index 33e79bc1e..5031836fe 100644 --- a/crates/metal2vulkan-runtime/src/chroma_pairs.rs +++ b/crates/metal2vulkan-runtime/src/chroma_pairs.rs @@ -15,16 +15,27 @@ //! - **What it serves.** Copies: between buffers and the texture, between textures, and the CPU's //! (`copy_plan.rs`). A storage slot whose function only writes the texture binds the slot's //! neutral (the binding plan's `IncompatibleBinding` note): plain Metal completes the writes -//! and stores nothing (EV RRP-probe11-m4). A slot that reads or samples it is refused with the -//! format's own refusal (`metal::format`'s `NotImplemented`; Metal's decode is measured), and so -//! are a render pipeline state of the format, whose descriptor Metal's validation aborts plain -//! too, and a render pass into the texture. +//! and stores nothing. Refused: a render pipeline state of the format, +//! whose descriptor Metal's validation aborts plain too, and a render pass into the texture. +//! - **Reads and samples** present a decoded twin (`texture/decoded_twin.rs`, announced +//! `carried-decoded-twin`): an `R8G8B8A8_UNORM` image of the texels as Metal reads them +//! (`bind::ChromaDecode`: each texel's own green, its red and blue interpolated with the pair +//! beside it, alpha 1; our probe on an Apple M3 Max under macOS 27.0.1 read, sampled (nearest, +//! linear and bicubic) and gathered both formats bit for bit as such an `RGBA8Unorm` texture), +//! exact, decoded after +//! each write as an ETC2 texture's twin is, on the GPU (`bind::chroma_decode_module`) or a host +//! write's on the CPU. A texel reads the pair beside it, so a write's decode is of whole rows +//! (a host write of part of a row decodes its rows as the texture then holds them). Refused: a +//! sparse heap's texture (`RuntimeGap::DecodedHeapTexture`). Without a twin (a heap's texture +//! over the caller's host pages or laid out apart from the heap's bytes) a command that binds +//! it for a read is refused. //! - **Through handles.** A function that reads texture handles from memory reaches such a -//! texture as a PVRTC carrier's (`pvrtc.rs`): the neutral texture, announced once -//! ([`Degradation::UnreadableHandleTexture`](super::degradation::Degradation)). +//! texture without a twin as a PVRTC carrier's (`pvrtc.rs`): the neutral texture, announced +//! once ([`Degradation::UnreadableHandleTexture`](super::degradation::Degradation)). use super::image_plan::{sample_count, ImageFacts, ImagePlan}; use super::texture_descriptor::{effective_usage, TextureLayout}; +use metal2vulkan::bind::ChromaDecode; use metal2vulkan::metal::format::{image_type, FormatMapping}; use metal2vulkan::metal::{PixelFormat, TextureUsage}; use metal2vulkan::vk::{Format, FormatFeatureFlags2, ImageAspectFlags, ImageUsageFlags}; @@ -47,8 +58,9 @@ pub(super) fn is_four_two_two(pf: PixelFormat) -> bool { } /// The image of a 4:2:2 texture of `layout` with Metal `usage` on a device with `facts`: the -/// carrier's (the module docs), for copies; `None` for a texture of another format, or where the -/// device does not copy the carrier (the format's refusal stands). +/// carrier's (the module docs), for copies, its reads and samples its decoded twin's; `None` for a +/// texture of another format, or where the device does not copy the carrier (the device's refusal +/// of the format stands). pub(super) fn plan_pairs( layout: &TextureLayout, usage: TextureUsage, @@ -72,11 +84,9 @@ pub(super) fn plan_pairs( usage: ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST, view_formats: Vec::new(), mapping: FormatMapping::direct(CARRIER, ImageAspectFlags::COLOR), + // Its decoded twin serves its reads and samples. unavailable: effective_usage(usage).intersection( - TextureUsage::SHADER_READ - | TextureUsage::SHADER_WRITE - | TextureUsage::SHADER_ATOMIC - | TextureUsage::RENDER_TARGET, + TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC | TextureUsage::RENDER_TARGET, ), }) } @@ -85,3 +95,9 @@ pub(super) fn plan_pairs( pub(super) fn holds_pairs(plan: &ImagePlan) -> bool { is_four_two_two(plan.pixel_format) && plan.format == CARRIER } + +/// The decode of the 4:2:2 texture whose texels `plan` holds in the carrier; `None` for any other +/// image. +pub(super) fn decode_of(plan: &ImagePlan) -> Option { + ChromaDecode::of(plan.pixel_format).filter(|_| holds_pairs(plan)) +} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 0e8cae3e6..4e6e3ddf3 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -973,10 +973,7 @@ impl State { /// between layouts (whose move back its submission plans before the end). fn may_fold(&self, device: &Device, index: usize) -> bool { let parts = &self.recorded[self.batch_range(index)]; - self.batches.all()[index].signals.is_empty() - && parts - .iter() - .all(|part| part.segments.is_empty() && part.sparse.is_empty()) + && parts.last().is_none_or(|part| part.twin_writes.is_empty()) && device .shared() .interop @@ -1030,10 +1027,10 @@ impl State { self.failed_at_commit = Some(failure.encoders); } - /// A failed encoder's recorded `part` runs nothing: its segments (with their recordings) - /// and sparse updates go to `retained`, released with what the command buffer retained - /// without this lock, its `VkCommandBuffer`s are left unsubmitted, and it keeps its place - /// among the batches with its fences' waits and updates alone. + /// A failed encoder's recorded `part` runs nothing: its segments (with their recordings), + /// sparse updates and writes into ASTC carriers go to `retained`, released with what the + /// command buffer retained without this lock, its `VkCommandBuffer`s are left unsubmitted, + /// and it keeps its place among the batches with its fences' waits and updates alone. pub(super) fn fail_part(part: &mut Recorded, retained: &mut Vec>) { for segment in part.segments.drain(..) { retained.push(Box::new((segment.work, segment.inputs))); @@ -1045,6 +1042,10 @@ impl State { for update in part.sparse.drain(..) { retained.push(Box::new(update)); } + // Its writes into ASTC carriers ran nothing, so nothing of them is decoded. + for write in part.twin_writes.drain(..) { + retained.push(Box::new(write)); + } part.raws.clear(); part.summary = part.summary.fences_only(); } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs b/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs index 4efc8b1eb..fd47e7b61 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs @@ -87,6 +87,7 @@ impl CommandBuffer { segments: Vec::new(), summary: recorded.summary, sparse: Vec::new(), + twin_writes: Vec::new(), }, ); state.retained.extend(recorded.retained.into_entry()); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index 779e26702..6099855a8 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -153,10 +153,12 @@ use crate::event_timeline::Signal; use crate::exit_guard::{self, Call}; use crate::gpu_time; use crate::release; +use crate::resource::ResourceKey; use crate::retained::Retained; use crate::scheduler; use crate::sparse::bind::{bind_batch, BindFailure, Bound}; use crate::sparse::encoder::SparseUpdate; +use crate::texture::decoded_twin::{SecondDecode, TwinWrite}; use crate::texture::wrapped::Transition; use crate::texture::Texture; use crate::tracker::{Barrier, EncoderUses, Point, Summary}; @@ -308,6 +310,9 @@ impl CommandBufferShared { state .runs_nothing_unrunnable(range.clone()) .map_err(|error| recording_error(device, error))?; + // The decodes into ASTC carriers' second decoded twins: those queued, before its work; + // its blits' writes', after each part. + self.record_second_decodes(&mut state, range.clone())?; let at = Point { queue, value: scheduler.values[queue] + 1, @@ -919,6 +924,81 @@ impl CommandBufferShared { Ok(()) } + /// Record the decodes into ASTC carriers' second decoded twins (`texture/decoded_twin.rs`) of + /// the batch of encoders `range`, a batch with work: those queued (as each twin was made, + /// and after host calls wrote its carrier), in one command buffer before the first part's + /// own, their uses joined to its summary, so the barrier and waits planned before that part + /// order them after the earlier writes of their images; but those of an image a part of the + /// batch wrote without a decode (the image had no second twin as the write was encoded), which + /// stay queued for a later batch: a twin made since reads the carrier as this batch leaves it. + /// Then after each part's own command buffers, the decodes its writes made as they were + /// encoded, their uses joined to its summary. Nothing, and no command buffer, where there is + /// none (counted: `WorkCounts::second_twin_checks`, `WorkCounts::second_twin_decodes`). + fn record_second_decodes( + &self, + state: &mut State, + range: std::ops::Range, + ) -> Result<(), CommandBufferError> { + let device = &self.device; + let counts = &device.shared().counts; + if range.is_empty() { + return Ok(()); + } + let held: Vec = state.recorded[range.clone()] + .iter() + .flat_map(|part| &part.twin_writes) + .filter_map(TwinWrite::without_decode) + .collect(); + let queued = device.take_second_decodes(|key| held.contains(&key)); + if !queued.is_empty() { + let raw = self.record_raw(state, |_, buffer| { + for decode in &queued { + // SAFETY: the command buffer is recording, outside a render pass, on the + // device's queue family; the decode is retained until the command buffer + // completes. + unsafe { decode.record(device.shared().vk(), buffer) }; + } + Ok(()) + })?; + let uses = queued.iter().flat_map(|decode| decode.uses()).cloned(); + let first = &mut state.recorded[range.start]; + first.raws.insert(0, raw); + first + .summary + .join(Summary::outside_encoders(uses.collect())); + counts.second_twin_decodes(queued.len()); + state.retained.push(Box::new(queued)); + } + for part in range { + let mut checked = 0; + let mut decodes: Vec = Vec::new(); + for write in state.recorded[part].twin_writes.drain(..) { + checked += 1; + decodes.extend(write.into_decode()); + } + counts.second_twin_checks(checked); + if decodes.is_empty() { + continue; + } + let raw = self.record_raw(state, |_, buffer| { + for decode in &decodes { + // SAFETY: as above. + unsafe { decode.record(device.shared().vk(), buffer) }; + } + Ok(()) + })?; + let uses = decodes.iter().flat_map(|decode| decode.uses()).cloned(); + let recorded = &mut state.recorded[part]; + recorded.raws.push(raw); + recorded + .summary + .join(Summary::outside_encoders(uses.collect())); + counts.second_twin_decodes(decodes.len()); + state.retained.push(Box::new(decodes)); + } + Ok(()) + } + /// A command buffer holding only `barriers`, in order, then `transitions` of the caller's /// images, between the `stamps` it writes, for the batch that signals `at`: where it moves no /// image, one the scheduler keeps (`kept_barriers.rs`; one that writes timestamps, kept for diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 238a406ea..75373f69d 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1479,6 +1479,44 @@ degradations! { staging queue: the first command buffer that may read the texture waits at its \ submission for that, and the call waits for it where a command buffer that may read \ the texture is submitted and not yet complete, or the texture is untracked"; + /// A texture of an ASTC LDR format (`ASTC_4x4_LDR` to `ASTC_12x12_LDR`, the sRGB forms + /// too) made on a device without that ASTC format (`textureCompressionASTC_LDR`), of a + /// PVRTC format on a device without it (`VK_IMG_format_pvrtc`'s RGBA formats; the RGB ones + /// on every device), or of an ETC2 or EAC format on a device without them + /// (`textureCompressionETC2`): its blocks lie in an image of a carrier format whose blocks + /// are also 16 (ASTC, `EAC_RGBA8`, `RG11`) or 8 (PVRTC, the other ETC2 and EAC formats) + /// bytes, which copies and `get_bytes` move unchanged, and its samples read a decoded + /// twin, Metal's decode of the blocks (an ASTC error block's magenta included) in the + /// texels [`metal2vulkan::device::DecodedTexelsPolicy`] names (a PVRTC texture's, an ASTC + /// sRGB one's and an 8-bit ETC2 or EAC one's, 8-bit codes, exact, under either), decoded + /// after each write into it as a BC texture's twin is (`decoded-block-twin`; a PVRTC + /// texture's whole levels). An ASTC texture's first view in its other colour space gives + /// it a second twin of that form's decode. Also a texture of a 4:2:2 format (`GBGR422`, + /// `BGRG422`) on every device, whose Vulkan formats reconstruct chroma by the + /// implementation's rules: its texels' bytes lie in an `R8G8_UNORM` carrier, and its twin + /// holds Metal's texels as 8-bit codes, exact, decoded in whole rows. + CarriedDecodedTwin = "carried-decoded-twin", Performance, + "a carrier image of its blocks, at most about 1 byte a texel, and a decoded twin of \ + 4 bytes a texel (R8G8B8A8, `DecodedTexelsPolicy::Compact`; an EAC 11-bit texture's \ + 16-bit codes, 2 bytes a channel) or 16 (R32G32B32A32_SFLOAT, \ + `DecodedTexelsPolicy::Exact`; an EAC 11-bit texture's floats, 4 bytes a channel), \ + two for an ASTC texture viewed in both colour spaces, and a decode after each write \ + into it: a pass on the GPU for a blit, a copy from a texture or a CPU copy through a \ + submission; on the CPU, on the device's decode thread, where its CPU copies go on \ + the host or the staging queue"; + /// A texture with an ASTC LDR decoded twin (`carried-decoded-twin`) of 8-bit codes, or an + /// EAC 11-bit one of 16-bit codes, under + /// [`metal2vulkan::device::DecodedTexelsPolicy::Compact`]: Metal decodes an ASTC LDR channel + /// to a 12-bit value (`C >> 4` over 4095 of the 16-bit interpolated channel `C`), which the + /// twin's R8G8B8A8 texels hold as the nearest 8-bit code (at most 1/510 off Metal's value). + /// It reads an EAC 11-bit channel as `c / 2047` (signed `c / 1023`), which the twin holds + /// as the nearest 16-bit normalized code (at most half a 16-bit step off). + /// `DecodedTexelsPolicy::Exact` holds Metal's values instead. (An ASTC sRGB texture's twin + /// holds Metal's own 8-bit codes, which its slots decode through Metal's table: exact.) + DecodedTexelPrecision = "decoded-texel-precision", Precision, + "a read, sample or gather of its texels answers the nearest 8-bit code to Metal's \ + 12-bit value, at most 1/510 off it; an EAC 11-bit texture's, the nearest 16-bit \ + normalized code to Metal's 11-bit value, at most half a 16-bit step off it"; /// A command queue made for presenting /// ([`Device::new_command_queue_for_presenting`](crate::Device::new_command_queue_for_presenting)) /// on a device that reserved no `VkQueue` for presenting: its queue family has no queue diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index c92db6afb..1c46cf875 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -43,6 +43,7 @@ use super::retained::Retained; use super::shadow::{ShadowCopy, ShadowSync, ShadowUse, Step, Within}; use super::shadow_merge::ShadowMerge; use super::sparse::encoder::SparseUpdate; +use super::texture::decoded_twin::TwinWrite; use super::tracker::{Barrier, EncoderUses, Summary, Use, UseRange}; use super::used_resources::EncoderKind; use super::Device; @@ -74,6 +75,10 @@ pub(super) struct Recorded { /// A resource state encoder's sparse mapping updates, which its batch binds before its work /// (`sparse/`); none for any other encoder. pub(super) sparse: Vec, + /// A blit encoder's writes into ASTC carriers, which its batch's submission decodes into + /// their second decoded twins after its work (`texture/decoded_twin.rs`); none for any other + /// encoder. + pub(super) twin_writes: Vec, } /// Commands an encoder left to record later (`deferred.rs`). @@ -211,6 +216,9 @@ pub(super) struct EncoderCore { /// made without `supportIndirectCommandBuffers`): `end` says so to the command buffer, whose /// commit runs nothing of it (`State::fault`). faults: bool, + /// Its writes into ASTC carriers ([`wrote_twin`](Self::wrote_twin)): `end` hands them to the + /// command buffer with its last part. + twin_writes: Vec, /// The core's own number in the process ([`id`](Self::id)). id: u64, /// It encodes an ended encoder's calls again, its command buffer committed (`replay.rs`): @@ -303,6 +311,7 @@ impl EncoderCore { taken: Taken::default(), fails_command_buffer: None, faults: false, + twin_writes: Vec::new(), id: CORES.fetch_add(1, Ordering::Relaxed), replaying: false, _not_sync: PhantomData, @@ -375,6 +384,7 @@ impl EncoderCore { taken: Taken::default(), fails_command_buffer: None, faults: false, + twin_writes: Vec::new(), id: CORES.fetch_add(1, Ordering::Relaxed), replaying: false, _not_sync: PhantomData, @@ -423,6 +433,12 @@ impl EncoderCore { self.retained.boxed(Box::new(object)); } + /// A command of the encoder wrote `write` into an ASTC carrier's blocks: its batch's + /// submission decodes it into the image's second decoded twin (`texture/decoded_twin.rs`). + pub(super) fn wrote_twin(&mut self, write: TwinWrite) { + self.twin_writes.push(write); + } + /// Hold `object`, a shared one (`Buffer::held` and its kin), until the command buffer /// completes: by another reference to it, without a box of its own (`retained.rs`). pub(super) fn retain_shared(&mut self, object: Arc) { @@ -1172,6 +1188,7 @@ impl EncoderCore { taken, fails_command_buffer, faults, + twin_writes, .. } = self; ended.push(raw); @@ -1220,6 +1237,9 @@ impl EncoderCore { current.push(segment); } parts.push((raws.collect(), current)); + // The writes into ASTC carriers go with the last part (a blit encoder's only one). + let count = parts.len(); + let mut twin_writes = Some(twin_writes); for (at, (raws, segments)) in parts.into_iter().enumerate() { let summary = summaries .next() @@ -1227,6 +1247,10 @@ impl EncoderCore { if at > 0 { state.host_step(); } + let twin_writes = match at + 1 == count { + true => twin_writes.take().unwrap_or_default(), + false => Vec::new(), + }; state.end_encoder( &open.command_buffer, Recorded { @@ -1235,6 +1259,7 @@ impl EncoderCore { segments, summary, sparse: Vec::new(), + twin_writes, }, ); } diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 3ee6bbf3f..df7277cea 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1325,6 +1325,14 @@ pub enum RuntimeGap { /// `MTLBlitOptionRowLinearPVRTC` or without it, as plain Metal's does (its API validation stops /// all but the first with the option). PvrtcBlockOrder, + /// A heap's or a sparse heap's texture of an ASTC format on a device without that ASTC format + /// (`astc.rs`), or a sparse heap's texture of an ETC2 or EAC format on a device without them + /// (`etc.rs`) or of a 4:2:2 format (`chroma_pairs.rs`), which Metal makes: an ASTC texture's + /// blocks would lie in the heap's bytes, which its decoded twin would decode as the texture is + /// placed, and a sparse heap's tiles are mapped by GPU commands. A heap's size query for an + /// ASTC one is refused alike. A texture of its own takes them + /// (`Degradation::CarriedDecodedTwin`), and so does an ETC2, EAC or 4:2:2 texture of a heap. + DecodedHeapTexture, /// A draw (`drawPrimitives:` and its forms, or an indirect command buffer's command) that /// may read a vertex attribute the pipeline fetches in its vertex function past `2^32` bytes /// of its buffer's bind offset, in a buffer that runs past them: Metal reads the attribute at diff --git a/crates/metal2vulkan-runtime/src/etc.rs b/crates/metal2vulkan-runtime/src/etc.rs new file mode 100644 index 000000000..9ed9a9426 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/etc.rs @@ -0,0 +1,111 @@ +//! ETC2 and EAC textures on a device without the formats: their blocks held as raw bytes in a +//! carrier, which copies move, and their samples read a decoded twin. +//! +//! - **Metal's answers** (an Apple M3 Max under macOS 27.0.1, our own probe: 4096 random blocks +//! of each of the ten formats, every texel read as `float`): Metal reads them as +//! `bind::EtcDecode` decodes them, an 8-bit channel `c / 255`, an sRGB form's colour through its +//! twelve-bit table, an 11-bit channel `c / 2047` (signed `c / 1023`). +//! - **The store.** A device without `textureCompressionETC2` has none of the formats. Such a +//! texture holds its blocks in an image of a *carrier*: a compressed format whose blocks are +//! also 4 x 4 texels and of the same bytes (8, or 16 for `EAC_RGBA8` and the `RG11` formats), +//! the first of [`CARRIERS_8`] or [`CARRIERS_16`] the device copies. Vulkan copies a compressed +//! image's blocks as bytes, so the carrier keeps every block a copy writes, whatever its bits +//! would mean to the carrier's decoder; its image is the texture's shape, so every region a copy +//! names is the texture's. +//! - **What it serves.** Copies between buffers and the texture and between textures (fills +//! included), and the CPU's copies, move its blocks through the carrier, so `getBytes` and a +//! blit out of it hand back the blocks written. Its sampled views, of its linear and sRGB forms +//! alike (the same codes), present its decoded twin (`texture/decoded_twin.rs`): Metal's decode +//! of the blocks, decoded after each write as a BC texture's twin is, on the GPU +//! (`bind::etc_decode_module`), or a host write's on the CPU. An 8-bit format's twin holds its +//! codes, exact (an sRGB form's slots read them raw and decode them through Metal's table, +//! `metal::texel_format::srgb_raw`); an 11-bit format's holds the texels +//! `DevicePolicy::decoded_texels` names (`bind::EtcTexels`: 16-bit normalized codes, announced +//! `decoded-texel-precision`, or Metal's values exactly). Announced `carried-decoded-twin`. +//! Refused: a view of another decode (an `R11` or `RG11` format's other signedness; +//! `Feature::TextureView`) and a sparse heap's texture (`RuntimeGap::DecodedHeapTexture`). A +//! texture without a twin (a heap's over the caller's host pages or laid out apart from the +//! heap's bytes) holds its blocks for copies alone, and a command that binds it for a read is +//! refused. A shader write and an attachment take no such image: Metal's functions write no +//! compressed texture, and no pass renders into one. + +use super::image_plan::{sample_count, ImageFacts, ImagePlan}; +use super::texture_descriptor::{effective_usage, TextureLayout}; +use metal2vulkan::bind::EtcDecode; +use metal2vulkan::device::FormatUsage; +use metal2vulkan::metal::format::{image_type, vk_format, FormatEmulation, FormatMapping}; +use metal2vulkan::metal::TextureUsage; +use metal2vulkan::vk::{ + Format, FormatFeatureFlags2, ImageAspectFlags, ImageCreateFlags, ImageUsageFlags, +}; + +/// The compressed formats of 8-byte blocks over 4 x 4 texels other than ETC2's and EAC's, in the +/// order an ETC2 or EAC texture of such blocks takes the first the device copies. +pub(super) const CARRIERS_8: [Format; 2] = [Format::BC1_RGBA_UNORM_BLOCK, Format::BC4_UNORM_BLOCK]; + +/// The compressed formats of 16-byte blocks over 4 x 4 texels other than ETC2's and EAC's, in the +/// order an `EAC_RGBA8` or `RG11` texture takes the first the device copies: BC7, BC3, BC2 and +/// BC5, then ASTC's 4x4 (a device with neither BC nor ETC2). +pub(super) const CARRIERS_16: [Format; 5] = [ + Format::BC7_UNORM_BLOCK, + Format::BC3_UNORM_BLOCK, + Format::BC2_UNORM_BLOCK, + Format::BC5_UNORM_BLOCK, + Format::ASTC_4X4_UNORM_BLOCK, +]; + +/// The carriers of `decode`'s blocks. +fn carriers(decode: EtcDecode) -> &'static [Format] { + match decode.block_bytes() { + 8 => &CARRIERS_8, + _ => &CARRIERS_16, + } +} + +/// The decode of the ETC2 or EAC texture whose blocks `plan` holds in a carrier (an sRGB form's +/// its unorm form's: the same codes); `None` for any other image. +pub(super) fn decode_of(plan: &ImagePlan) -> Option { + EtcDecode::of(plan.pixel_format).filter(|&decode| carriers(decode).contains(&plan.format)) +} + +/// The image of an ETC2 or EAC texture of `layout` with Metal `usage` on a device with `facts` +/// that holds its blocks in a carrier (the module docs): `None` for a texture of another format, +/// or of one the device holds (its format, or no decoded twin's view: its refusal stands), or +/// where no carrier is copied (the device's refusal of the format stands). +pub(super) fn plan_blocks( + layout: &TextureLayout, + usage: TextureUsage, + facts: &ImageFacts<'_>, +) -> Option { + let pf = layout.pixel_format; + let decode = EtcDecode::of(pf)?; + let sampled = vk_format(pf, &[FormatUsage::SampledImage].into(), facts.profile).ok()?; + if sampled.emulation != FormatEmulation::Decoded { + return None; + } + let copies = FormatFeatureFlags2::TRANSFER_SRC | FormatFeatureFlags2::TRANSFER_DST; + let carrier = (carriers(decode).iter()) + .copied() + .find(|&f| facts.optimal(f).contains(copies))?; + // No create flags, never cube compatible: copies alone reach the carrier and no view of it is + // made, so a cube texture's faces are its layers. + let (image_type, _) = image_type(layout.texture_type)?; + Some(ImagePlan { + pixel_format: pf, + flags: ImageCreateFlags::empty(), + image_type, + format: carrier, + extent: layout.extent, + levels: layout.levels, + layers: layout.layers, + samples: sample_count(layout.samples)?, + usage: ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST, + view_formats: Vec::new(), + mapping: FormatMapping::direct(carrier, ImageAspectFlags::COLOR), + // Its decoded twin serves its samples and reads. (`BlockWritesOnly` plans as + // `ShaderWrite` does, which Metal's functions never use on a compressed texture.) + unavailable: effective_usage(usage).intersection( + TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC | TextureUsage::RENDER_TARGET, + ), + }) +} diff --git a/crates/metal2vulkan-runtime/src/heap_sets.rs b/crates/metal2vulkan-runtime/src/heap_sets.rs index 270994a7a..2cbd368d3 100644 --- a/crates/metal2vulkan-runtime/src/heap_sets.rs +++ b/crates/metal2vulkan-runtime/src/heap_sets.rs @@ -836,13 +836,9 @@ impl Notes { /// `texture` placed, into a set where `in_set`. fn placed(&mut self, texture: &Texture, in_set: bool) { - if in_set && self.unreadable.is_none() { - let blocks = texture - .image_plan() - .is_ok_and(super::pvrtc::holds_for_copies); - if blocks { - self.unreadable = Some(texture.clone()); - } + let held = || super::pvrtc::held_for_copies(texture).is_some(); + if in_set && self.unreadable.is_none() && held() { + self.unreadable = Some(texture.clone()); } } diff --git a/crates/metal2vulkan-runtime/src/image_plan.rs b/crates/metal2vulkan-runtime/src/image_plan.rs index 53bad40d4..d0fe2a9b2 100644 --- a/crates/metal2vulkan-runtime/src/image_plan.rs +++ b/crates/metal2vulkan-runtime/src/image_plan.rs @@ -607,6 +607,15 @@ fn plan_held( if let Some(plan) = plan_blocks(layout, usage, facts) { return Ok(plan); } + // An ASTC texture the device has no block for holds its blocks in a carrier, sampled + // through a decoded twin (`astc.rs`). + if let Some(plan) = super::astc::plan_blocks(layout, usage, facts) { + return Ok(plan); + } + // So does an ETC2 or EAC texture on a device without the formats (`etc.rs`). + if let Some(plan) = super::etc::plan_blocks(layout, usage, facts) { + return Ok(plan); + } // A 4:2:2 texture holds its texels in a carrier (`chroma_pairs.rs`). if let Some(plan) = plan_pairs(layout, usage, facts) { return Ok(plan); @@ -728,8 +737,13 @@ fn plan_held( // one. _ => any, }; - if mapping.emulation == FormatEmulation::DepthWidened { - // 24-bit depth held as 32-bit float depth is not exact: the texture needs its own format. + // 24-bit depth held as 32-bit float depth is not exact, and an ASTC, PVRTC, ETC2 or EAC + // format's decoded twin's view holds no blocks (a memoryless texture, or a device with no + // carrier, `astc.rs`, `pvrtc.rs`, `etc.rs`): the texture needs its own format. + if matches!( + mapping.emulation, + FormatEmulation::DepthWidened | FormatEmulation::Decoded + ) { return Err(ImageRefusal::Unsupported(Unsupported::needs( Feature::Format, Capability::Format { @@ -1036,6 +1050,15 @@ pub(super) fn takes_views_of(plan: &ImagePlan, pf: PixelFormat, profile: &Device }) } +/// The cube compatibility a sampled image of a texture of `layout` takes: a cube's, and a square +/// 2D array's of six layers or more ([`cube_compatible`]), which a cube view may present. +pub(super) fn cube_flags(layout: &TextureLayout) -> ImageCreateFlags { + match cube_compatible(layout) { + true => ImageCreateFlags::CUBE_COMPATIBLE, + false => ImageCreateFlags::empty(), + } +} + /// Whether the image of `layout` is cube-compatible: a cube or cube array, or a square 2D array /// of at least six single-sample layers (Metal views those as cubes). pub(super) fn cube_compatible(layout: &TextureLayout) -> bool { diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 2f3d276a2..15f459cc8 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -30,6 +30,7 @@ mod amplification; mod apple_only; mod argument_encoder; mod argument_table; +mod astc; mod attachment_stand_in; mod attachmentless; mod attributes; @@ -78,6 +79,7 @@ mod dynamic_state; mod enables; mod encoder; mod error; +mod etc; mod event; mod event_timeline; mod exactness; diff --git a/crates/metal2vulkan-runtime/src/owned_kernel.rs b/crates/metal2vulkan-runtime/src/owned_kernel.rs index 55c9df4d7..3265ce308 100644 --- a/crates/metal2vulkan-runtime/src/owned_kernel.rs +++ b/crates/metal2vulkan-runtime/src/owned_kernel.rs @@ -18,6 +18,7 @@ use super::device::lock; use super::error::{internal, vulkan, Error}; use super::exit_guard; use super::release; +use super::texture::decoded_twin::TwinDecode; use super::Device; use crate::shader_cache::driver::Making; use ash::vk; @@ -121,9 +122,11 @@ pub(super) enum OwnedModule { /// moved and its dispatches gated (`predication.rs`). No descriptor: it reaches memory by /// device address. PredicationStep, - /// `bind::block_decode_module` of one decode: a BC1 to BC5 texture's written region decoded - /// as Metal decodes it into its decoded twin (`texture/decoded_twin.rs`). - BlockDecode(BlockDecode), + /// The GPU decode of one decoded twin's blocks (`TwinDecode::module`: + /// `bind::block_decode_module`, `bind::astc_decode_module`): a BC1 to BC5 texture's or an + /// ASTC carrier's written region decoded as Metal decodes it into its decoded twin + /// (`texture/decoded_twin.rs`). + TwinDecode(TwinDecode), /// `bind::tessellation_scan_module` of one pipeline's tessellation state: an emulated patch /// draw's records and chunk draws (`render/tessellation_scan.rs`). One per state a pipeline /// of the device draws with (its domain, partition, winding, maximum factor, step function @@ -305,10 +308,10 @@ impl OwnedModule { let push_bytes = metal2vulkan::bind::PredicationStepModule::PUSH_BYTES; Ok((module.spirv.to_vec(), 0, push_bytes)) } - OwnedModule::BlockDecode(decode) => { - let module = - metal2vulkan::bind::block_decode_module(device.compile_device(), decode) - .map_err(Error::Compile)?; + OwnedModule::TwinDecode(decode) => { + let module = decode + .module(device.compile_device()) + .map_err(Error::Compile)?; Ok((module.spirv.to_vec(), 3, 0)) } OwnedModule::TessellationScan(kernel) => { @@ -380,7 +383,7 @@ pub(super) struct OwnedKernels { capture_settle: Option, extended_shadow_loads: HashMap, predication_step: Option, - block_decodes: HashMap, + twin_decodes: HashMap, tessellation_scans: HashMap, } @@ -418,7 +421,7 @@ impl OwnedKernels { .chain(self.unused_bits.values().copied()) .chain(self.compressed_blits.values().copied()) .chain(self.extended_shadow_loads.values().copied()) - .chain(self.block_decodes.values().copied()) + .chain(self.twin_decodes.values().copied()) .chain(self.tessellation_scans.values().copied()) { kernel.destroy(raw); @@ -437,7 +440,7 @@ impl OwnedKernels { OwnedModule::UnusedBits(form, words) => self.unused_bits.get(&(form, words)).copied(), OwnedModule::CompressedBlit(rule) => self.compressed_blits.get(&rule).copied(), OwnedModule::ExtendedShadowLoad(form) => self.extended_shadow_loads.get(&form).copied(), - OwnedModule::BlockDecode(decode) => self.block_decodes.get(&decode).copied(), + OwnedModule::TwinDecode(decode) => self.twin_decodes.get(&decode).copied(), OwnedModule::TessellationScan(kernel) => self.tessellation_scans.get(&kernel).copied(), _ => self.slot(which).and_then(|slot| *slot), } @@ -467,8 +470,8 @@ impl OwnedKernels { OwnedModule::ExtendedShadowLoad(form) => { self.extended_shadow_loads.insert(form, kernel); } - OwnedModule::BlockDecode(decode) => { - self.block_decodes.insert(decode, kernel); + OwnedModule::TwinDecode(decode) => { + self.twin_decodes.insert(decode, kernel); } OwnedModule::TessellationScan(key) => { self.tessellation_scans.insert(key, kernel); @@ -481,9 +484,7 @@ impl OwnedKernels { } } - /// The slot of a kernel the device makes once (none for the shadow copy back's, the mipmap - /// filter's, the index rewrite's, the YCbCr conversion's, the unused bits', the compressed - /// blit's, the extended shadow load's, the block decode's or the tessellation scan's, one + /// blit's, the extended shadow load's, the twin decode's or the tessellation scan's, one /// per key). fn slot(&mut self, which: OwnedModule) -> Option<&mut Option> { Some(match which { @@ -502,7 +503,7 @@ impl OwnedKernels { | OwnedModule::UnusedBits(..) | OwnedModule::CompressedBlit(_) | OwnedModule::ExtendedShadowLoad(_) - | OwnedModule::BlockDecode(_) + | OwnedModule::TwinDecode(_) | OwnedModule::TessellationScan(_) => return None, OwnedModule::MeshScan => &mut self.mesh_scan, OwnedModule::PlaneWords => &mut self.plane_words, diff --git a/crates/metal2vulkan-runtime/src/pvrtc.rs b/crates/metal2vulkan-runtime/src/pvrtc.rs index 8815f2730..bc308aa63 100644 --- a/crates/metal2vulkan-runtime/src/pvrtc.rs +++ b/crates/metal2vulkan-runtime/src/pvrtc.rs @@ -1,5 +1,5 @@ //! PVRTC textures on a device without a format for them: their blocks held as raw bytes, which -//! copies move and nothing reads. +//! copies move, and their samples read a decoded twin. //! //! - **Metal's answers** (an M4 under macOS 27.0.1, EV SPCrp-probe7-m4, alike plain twice and //! under API validation where it passes): every PVRTC format makes a texture, `Private` and @@ -35,16 +35,22 @@ //! than one: a PVRTC texture is square with a power-of-two side (`texture_descriptor`), so the //! half-width image's level `l`, `max(1, w / 2^(l+1))` wide, holds `ceil(max(1, w / 2^l) / 8)` //! blocks across, as the texture's does. -//! - **What it serves.** Copies only: copies between buffers and the texture, row by row and in -//! block order, and copies between textures (`blit_texture.rs`), and the CPU's copies of whole -//! levels in their order (`Texture::replace_region` and `get_bytes`, through rows, -//! [`rows_of_cpu_order`]). Sampling, shader reads and writes and -//! rendering need a decoder the runtime does not have: the texture is made, as Metal makes it, -//! and a command that binds it is refused with the format's own refusal (its representation's -//! `NotImplemented`, or the extension it needs). -//! - **Through handles.** A function that reads texture handles from memory may reach such a -//! texture made resident, or bound in a stage that reads handles, and the runtime does not know -//! which of the textures it reaches the function reads: the handle's element is the neutral +//! - **What it serves.** Copies between buffers and the texture, row by row and in block order, +//! and copies between textures (`blit_texture.rs`), and the CPU's copies of whole levels in +//! their order (`Texture::replace_region` and `get_bytes`, through rows, [`rows_of_cpu_order`]). +//! Its sampled views, of the format's linear and sRGB forms alike, present its decoded twin +//! (`texture/decoded_twin.rs`): Metal's decode of the blocks (`bind::PvrtcDecode`, fitted on an +//! Apple M3 Max) as 8-bit codes, exact, decoded after each write into it, whole levels at a time +//! (each texel's colors come from the blocks around it, wrapping): on the GPU +//! (`bind::pvrtc_decode_module`), or a host write's on the CPU. Announced +//! `carried-decoded-twin` (the twin's memory and the decodes). A shader write and an attachment +//! take no such image: Metal's functions write no compressed texture, and no pass renders into +//! one. A texture without a twin (memoryless, sparse, or a heap's over the caller's host pages or +//! laid out apart from the heap's bytes) holds its blocks for copies alone, and a command that +//! binds it for a read is refused (the twin's format's sampled usage, which its image lacks). +//! - **Through handles.** A function that reads texture handles from memory may reach a texture +//! without a twin made resident, or bound in a stage that reads handles, and the runtime does not +//! know which of the textures it reaches the function reads: the handle's element is the neutral //! texture, nothing is refused, and the command announces it once //! ([`Degradation::UnreadableHandleTexture`], `degrade_unreadable`). //! - **Not yet:** the CPU's copies of a region other than a whole level, and of a whole level at @@ -58,7 +64,8 @@ use super::device::Device; use super::image_plan::{block_family, sample_count, ImageFacts, ImagePlan}; use super::texture::Texture; use super::texture_descriptor::{effective_usage, TextureLayout}; -use metal2vulkan::metal::format::{image_type, vk_format, FormatMapping}; +use metal2vulkan::bind::PvrtcDecode; +use metal2vulkan::metal::format::{image_type, vk_format, FormatEmulation, FormatMapping}; use metal2vulkan::metal::{PixelFormat, TextureUsage}; use metal2vulkan::vk::{ Format, FormatFeatureFlags2, ImageAspectFlags, ImageCreateFlags, ImageUsageFlags, @@ -107,8 +114,12 @@ fn texels_across(plan: &ImagePlan) -> u32 { /// `region`, in the texels of a texture whose image `plan` plans, in the image's texels: a 2-bit /// PVRTC texture's carrier halves x and the width, the width rounded up (a region of whole /// blocks starts at a multiple of 8 and is 8 texels a block wide, or ends at the level's edge, -/// which rounding up keeps at the image level's); every other image's region is the texture's. +/// which rounding up keeps at the image level's); an ASTC texture's carrier holds each block in +/// 4 x 4 of its texels (`astc::image_region`); every other image's region is the texture's. pub(super) fn image_region(plan: &ImagePlan, region: ImageRegion) -> ImageRegion { + if let Some(carried) = super::astc::image_region(plan, region) { + return carried; + } let n = texels_across(plan); let [x, y, z] = region.origin; let [width, height, depth] = region.size; @@ -125,6 +136,16 @@ pub(super) fn image_buffer_region( plan: &ImagePlan, region: BufferImageRegion, ) -> BufferImageRegion { + // An ASTC texture's carrier: rows and images of its blocks, 4 x 4 carrier texels each. + if let Some(decode) = super::astc::decode_of(plan) { + let [bw, bh] = decode.block_extent(); + return BufferImageRegion { + row_length: super::astc::carrier_texels(region.row_length, bw), + image_height: super::astc::carrier_texels(region.image_height, bh), + image: image_region(plan, region.image), + ..region + }; + } BufferImageRegion { row_length: region.row_length / texels_across(plan), image: image_region(plan, region.image), @@ -167,10 +188,13 @@ pub(super) fn cpu_order_of_rows(rows: &[u8], blocks: [u64; 2], level: &mut [u8]) } /// The block extent, in texels of an image of `format` holding a texture of `pf`, of the blocks -/// Vulkan copies: a carrier's 4 x 4 (a 2-bit PVRTC texture's 8 x 4 blocks lie over 4 x 4 of its -/// carrier's texels), else `pf`'s own. +/// Vulkan copies: a carrier's 4 x 4 (a 2-bit PVRTC texture's 8 x 4 blocks and an ASTC texture's +/// blocks lie over 4 x 4 of its carrier's texels), else `pf`'s own. pub(super) fn image_block_extent(format: Format, pf: PixelFormat) -> Option<[u32; 2]> { - if is_pvrtc(pf) && CARRIERS.contains(&format) { + let astc = metal2vulkan::bind::AstcDecode::of(pf).is_some(); + if (is_pvrtc(pf) && CARRIERS.contains(&format)) + || (astc && super::astc::CARRIERS.contains(&format)) + { Some([4, 4]) } else { block_extent(pf) @@ -186,7 +210,9 @@ pub(super) fn plan_blocks( facts: &ImageFacts<'_>, ) -> Option { let pf = layout.pixel_format; - if !is_pvrtc(pf) || vk_format(pf, &BTreeSet::new(), facts.profile).is_ok() { + let direct = vk_format(pf, &BTreeSet::new(), facts.profile) + .is_ok_and(|m| m.emulation == FormatEmulation::Direct); + if !is_pvrtc(pf) || direct { return None; } let copies = FormatFeatureFlags2::TRANSFER_SRC | FormatFeatureFlags2::TRANSFER_DST; @@ -217,11 +243,9 @@ pub(super) fn plan_blocks( usage: ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST, view_formats: Vec::new(), mapping: FormatMapping::direct(carrier, ImageAspectFlags::COLOR), + // Its decoded twin serves its samples and reads (`texture/decoded_twin.rs`). unavailable: usage.intersection( - TextureUsage::SHADER_READ - | TextureUsage::SHADER_WRITE - | TextureUsage::SHADER_ATOMIC - | TextureUsage::RENDER_TARGET, + TextureUsage::SHADER_WRITE | TextureUsage::SHADER_ATOMIC | TextureUsage::RENDER_TARGET, ), }) } @@ -231,25 +255,38 @@ pub(super) fn holds_blocks(plan: &ImagePlan) -> bool { is_pvrtc(plan.pixel_format) && CARRIERS.contains(&plan.format) } -/// Whether `plan` holds a texture's bytes in a carrier for copies alone: a PVRTC texture's blocks -/// (the module docs), or a 4:2:2 texture's texels (`chroma_pairs.rs`). -pub(super) fn holds_for_copies(plan: &ImagePlan) -> bool { - holds_blocks(plan) || super::chroma_pairs::holds_pairs(plan) +/// The decode of the PVRTC texture whose blocks `plan` holds in a carrier, its linear form's (an +/// sRGB form's codes are the same); `None` for any other image. +pub(super) fn decode_of(plan: &ImagePlan) -> Option { + PvrtcDecode::of(plan.pixel_format) + .filter(|_| holds_blocks(plan)) + .map(PvrtcDecode::linear) +} + +/// The carrier's format of `texture`, whose bytes a carrier holds for copies alone: a PVRTC, +/// ETC2 or EAC texture's blocks, or a 4:2:2 texture's texels (`chroma_pairs.rs`), without a +/// decoded twin (the module docs, `etc.rs`); `None` for any other texture. +pub(super) fn held_for_copies(texture: &Texture) -> Option { + let plan = texture.image_plan().ok()?; + let carried = holds_blocks(plan) + || super::etc::decode_of(plan).is_some() + || super::chroma_pairs::holds_pairs(plan); + (carried && !texture.has_decoded_twin()).then_some(plan.format) } /// Announce once ([`Degradation::UnreadableHandleTexture`]) that `command` (named), encoded, whose /// functions read texture handles from memory, reaches a texture among `textures` (those made /// resident, and those bound in a stage that reads handles) whose bytes a carrier holds for -/// copies alone ([`holds_for_copies`]). +/// copies alone ([`held_for_copies`]). pub(super) fn degrade_unreadable<'a>( device: &Device, textures: impl IntoIterator, command: &str, ) { - let Some((texture, carrier)) = textures.into_iter().find_map(|texture| { - let plan = texture.image_plan().ok()?; - holds_for_copies(plan).then_some((texture, plan.format)) - }) else { + let Some((texture, carrier)) = textures + .into_iter() + .find_map(|texture| Some((texture, held_for_copies(texture)?))) + else { return; }; device.degrade(Degradation::UnreadableHandleTexture, || { diff --git a/crates/metal2vulkan-runtime/src/sparse/encoder.rs b/crates/metal2vulkan-runtime/src/sparse/encoder.rs index 194845316..21804d932 100644 --- a/crates/metal2vulkan-runtime/src/sparse/encoder.rs +++ b/crates/metal2vulkan-runtime/src/sparse/encoder.rs @@ -416,6 +416,7 @@ impl ResourceStateCommandEncoder { segments: Vec::new(), summary: Summary::of_fences(waits, fence_updates), sparse: updates, + twin_writes: Vec::new(), }, ); drop(state); diff --git a/crates/metal2vulkan-runtime/src/tests/blit_plan.rs b/crates/metal2vulkan-runtime/src/tests/blit_plan.rs index a970f9238..4fc1db4f4 100644 --- a/crates/metal2vulkan-runtime/src/tests/blit_plan.rs +++ b/crates/metal2vulkan-runtime/src/tests/blit_plan.rs @@ -1239,6 +1239,110 @@ fn pvrtc_copies_at_a_pitch_of_0_follow_metals_block_order() { assert!(plan(region([8, 4, 0], [12, 8, 1]), 0, 0, 56).is_ok()); } +/// Between a compressed format and an uncompressed one whose texel is its block's bytes, a region +/// copy's coordinates are the destination's texels, as our probe on an Apple M3 Max under macOS +/// 27.0.1 read them: out of BC1 into `RG32Uint` an origin of (4, 4) and a size of 2 x 2 copy the +/// blocks from the fifth across and down (texels from 16), into BC1 from `RG32Uint` an origin of +/// (1, 2) and a size of 2 x 2 copy texel (0, 0) alone into the block at (4, 4); ASTC 6x5's +/// blocks likewise. Units of other bytes stay Metal's refusal; a PVRTC format with an +/// uncompressed one, two compressed formats of different extents, and a level copy between a +/// compressed and an uncompressed format, the runtime's gap. +#[test] +fn compressed_and_uncompressed_textures_copy_in_the_destination_s_texels() { + use PixelFormat as P; + let t = |pf, w, h| tex(pf, TextureType::Type2D, [w, h, 1]); + let (bc1, rg32) = (t(P::BC1RGBA, 32, 32), t(P::RG32Uint, 8, 8)); + let out = plan_region_copy( + &pair(&bc1, &rg32), + ®ion([4, 4, 0], [2, 2, 1]), + 0, + 0, + [1, 2, 0], + ) + .unwrap(); + assert_eq!( + (out[0].src.origin, out[0].src.size), + ([16, 16, 0], [8, 8, 1]) + ); + assert_eq!((out[0].dst.origin, out[0].dst.size), ([1, 2, 0], [2, 2, 1])); + let into = + |origin, size, at| plan_region_copy(&pair(&rg32, &bc1), ®ion(origin, size), 0, 0, at); + let out = into([1, 2, 0], [2, 2, 1], [4, 4, 0]).unwrap(); + assert_eq!((out[0].src.origin, out[0].src.size), ([0, 0, 0], [1, 1, 1])); + assert_eq!((out[0].dst.origin, out[0].dst.size), ([4, 4, 0], [4, 4, 1])); + let out = into([1, 1, 0], [4, 2, 1], [4, 0, 0]).unwrap(); + assert_eq!((out[0].src.origin, out[0].src.size), ([0, 0, 0], [1, 1, 1])); + assert_eq!((out[0].dst.origin, out[0].dst.size), ([4, 0, 0], [4, 4, 1])); + let out = into([0, 0, 0], [8, 8, 1], [0, 0, 0]).unwrap(); + assert_eq!((out[0].src.size, out[0].dst.size), ([2, 2, 1], [8, 8, 1])); + // Past the source's blocks: Metal's refusal. + assert_eq!( + plan_region_copy( + &pair(&bc1, &rg32), + ®ion([7, 0, 0], [2, 1, 1]), + 0, + 0, + [0, 0, 0] + ), + Err(CopyRefusal::Invalid(CopyProblem::Region)) + ); + let (astc, rgba32) = (t(P::ASTC6x5LDR, 48, 40), t(P::RGBA32Uint, 8, 8)); + let out = plan_region_copy( + &pair(&astc, &rgba32), + ®ion([6, 5, 0], [2, 2, 1]), + 0, + 0, + [1, 2, 0], + ) + .unwrap(); + assert_eq!( + (out[0].src.origin, out[0].src.size), + ([36, 25, 0], [12, 10, 1]) + ); + let out = plan_region_copy( + &pair(&rgba32, &astc), + ®ion([1, 2, 0], [2, 2, 1]), + 0, + 0, + [6, 5, 0], + ) + .unwrap(); + assert_eq!((out[0].src.origin, out[0].src.size), ([0, 0, 0], [1, 1, 1])); + assert_eq!((out[0].dst.origin, out[0].dst.size), ([6, 5, 0], [6, 5, 1])); + let full = region([0, 0, 0], [2, 2, 1]); + assert_eq!( + plan_region_copy(&pair(&bc1, &t(P::RGBA8Unorm, 8, 8)), &full, 0, 0, [0, 0, 0]), + Err(CopyRefusal::Invalid(CopyProblem::Format)) + ); + let gap = |r: Result, CopyRefusal>| matches!(&r, Err(CopyRefusal::Unsupported(u)) if u.feature == Feature::Format); + let pvrtc = t(P::PVRTCRGBA4BPP, 32, 32); + assert!(gap(plan_region_copy( + &pair(&pvrtc, &rg32), + &full, + 0, + 0, + [0, 0, 0] + ))); + assert!(gap(plan_region_copy( + &pair(&rg32, &pvrtc), + &full, + 0, + 0, + [0, 0, 0] + ))); + let bc7 = t(P::BC7RGBAUnorm, 48, 40); + assert!(gap(plan_region_copy( + &pair(&astc, &bc7), + &full, + 0, + 0, + [0, 0, 0] + ))); + assert!(gap(plan_levels_copy(&pair(&bc1, &rg32), 0, 0, 0, 0, 1, 1))); + let small = t(P::BC1RGBA, 8, 8); + assert!(gap(plan_whole_copy(&pair(&rg32, &small)))); +} + /// A 4:2:2 texture copies into the other order, `RG8Unorm` and `R16Uint` byte for byte (macOS /// 26.7's rule of one copy unit); a copy into one from another format of its unit is the /// runtime's refusal (plain Metal writes `0xff` over part of each row, EV RRP-probe11-m4), and diff --git a/crates/metal2vulkan-runtime/src/tests/image_plan.rs b/crates/metal2vulkan-runtime/src/tests/image_plan.rs index efe7bfb34..e8dac4b8d 100644 --- a/crates/metal2vulkan-runtime/src/tests/image_plan.rs +++ b/crates/metal2vulkan-runtime/src/tests/image_plan.rs @@ -221,10 +221,17 @@ fn check_plan( } // `PixelFormatView` and `Unknown` take any compatible format; a PVRTC texture's carrier // has no other view (`pvrtc.rs`). - // A 4:2:2 texture's carrier likewise (`chroma_pairs.rs`). + // A 4:2:2 texture's carrier likewise (`chroma_pairs.rs`), and an ASTC texture's, whose + // sampled views present its decoded twin (`astc.rs`), as a PVRTC texture's do, and an ETC2 + // or EAC texture's (`etc.rs`). + let astc = super::super::astc::decode_of(plan).is_some(); + let etc = super::super::etc::decode_of(plan).is_some(); + let carried = astc || etc || holds_blocks(plan) || holds_pairs(plan); if (unknown || usage.contains(TextureUsage::PIXEL_FORMAT_VIEW)) && !holds_blocks(plan) && !holds_pairs(plan) + && !astc + && !etc { assert!(mutable && plan.view_formats.is_empty(), "{what}"); } @@ -239,6 +246,11 @@ fn check_plan( ImageUsageFlags::COLOR_ATTACHMENT | ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT, ), ] { + // An ASTC, PVRTC, ETC2, EAC or 4:2:2 carrier's reads are its decoded twin's. + if carried && bit == TextureUsage::SHADER_READ { + assert!(!plan.unavailable.contains(bit), "{what}"); + continue; + } if usage.contains(bit) { assert!( plan.usage.intersects(flags) != plan.unavailable.contains(bit), @@ -1400,7 +1412,8 @@ fn extended_range_textures_hold_their_bytes_raw() { } /// A PVRTC texture a device has no format for holds its blocks in the first carrier the device -/// copies, for copies alone: every usage a shader or a pass needs is unavailable. A 4-bit +/// copies, which copies alone reach: its reads are its decoded twin's, so no usage it asks for is +/// unavailable (none a shader write or a pass needs is asked for here). A 4-bit /// texture's image is the texture's extent; a 2-bit texture's is half as wide, rounded up, its 8 /// x 4 blocks each over 4 x 4 carrier texels. A device with `VK_IMG_format_pvrtc` keeps its RGBA /// formats' own images, 2- and 4-bit; no device refuses a PVRTC format where a carrier copies. @@ -1456,7 +1469,7 @@ fn a_pvrtc_texture_without_a_format_holds_its_blocks_in_a_carrier() { ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST, "{what}" ); - assert_eq!(plan.unavailable, TextureUsage::SHADER_READ, "{what}"); + assert_eq!(plan.unavailable, TextureUsage::empty(), "{what}"); check_plan(&name, pf, usage, &plan, &facts); // A cube's carrier holds its faces as layers, of no create flags: no view of it is // made, and a 2-bit one's half-width carrier is no square. @@ -1478,6 +1491,75 @@ fn a_pvrtc_texture_without_a_format_holds_its_blocks_in_a_carrier() { assert!(carried >= 40, "{carried}"); } +/// An ETC2 or EAC texture a device has no format for holds its blocks in the first carrier of +/// its blocks' bytes the device copies (`etc.rs`): of the texture's extent, levels and layers +/// (a cube's faces as layers, of no create flags), which copies alone reach, its reads its +/// decoded twin's. A device with the formats keeps each texture's own image. +#[test] +fn an_etc_texture_without_a_format_holds_its_blocks_in_a_carrier() { + use super::super::etc::{decode_of, CARRIERS_16, CARRIERS_8}; + use metal2vulkan::bind::EtcDecode; + let mut carried = 0; + for (name, desc, device) in committed() { + let facts = facts(&desc, &device); + let copies = FormatFeatureFlags2::TRANSFER_SRC | FormatFeatureFlags2::TRANSFER_DST; + for &pf in PixelFormat::ALL { + let Some(decode) = EtcDecode::of(pf) else { + continue; + }; + let what = format!("{name} {pf:?}"); + let usage = TextureUsage::SHADER_READ | TextureUsage::PIXEL_FORMAT_VIEW; + let mut l = layout(TextureType::Type2D, pf, 1, 1); + l.extent = [20, 12, 1]; + l.levels = 3; + let sampled = vk_format(pf, &[FormatUsage::SampledImage].into(), device.profile()); + let plan = plan_image(&l, usage, false, &facts); + // A device that samples neither the format nor its twin's view refuses it. + let Ok(sampled) = sampled else { + assert!(plan.is_err(), "{what}"); + continue; + }; + if sampled.emulation == metal2vulkan::metal::format::FormatEmulation::Direct { + let plan = plan.expect(&what); + assert_eq!(decode_of(&plan), None, "{what}"); + continue; + } + let carriers: &[Format] = match decode.block_bytes() { + 8 => &CARRIERS_8, + _ => &CARRIERS_16, + }; + let Some(&carrier) = carriers + .iter() + .find(|&&f| facts.optimal(f).contains(copies)) + else { + assert!(plan.is_err(), "{what}"); + continue; + }; + let plan = plan.expect(&what); + carried += 1; + assert_eq!(decode_of(&plan), Some(decode), "{what}"); + assert_eq!(plan.format, carrier, "{what}"); + assert_eq!((plan.extent, plan.levels), ([20, 12, 1], 3), "{what}"); + assert_eq!( + plan.usage, + ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST, + "{what}" + ); + assert_eq!(plan.unavailable, TextureUsage::empty(), "{what}"); + check_plan(&name, pf, usage, &plan, &facts); + let mut l = layout(TextureType::Cube, pf, 1, 1); + l.extent = [16, 16, 1]; + let plan = plan_image(&l, usage, false, &facts).expect(&what); + assert_eq!(decode_of(&plan), Some(decode), "{what} cube"); + assert_eq!(plan.flags, ImageCreateFlags::empty(), "{what} cube"); + assert_eq!((plan.extent, plan.layers), ([16, 16, 1], 6), "{what} cube"); + check_plan(&name, pf, usage, &plan, &facts); + } + } + // Ten formats on each committed profile without ETC2 (lavapipe, RADV, NVIDIA). + assert!(carried >= 50, "{carried}"); +} + /// Each level of a 2-bit PVRTC texture's half-width carrier holds the blocks the texture's level /// holds, at every power-of-two side from 1 to 4096 and every level: `ceil(w / 8)` across and /// `ceil(h / 4)` down, one block once the level is no larger than one; a region of whole blocks @@ -1544,11 +1626,17 @@ fn a_two_bit_pvrtc_carrier_holds_each_level_s_blocks() { } } -/// A 4:2:2 texture holds its 2-byte texels in an `R8G8_UNORM` image of its extent, for copies -/// alone, on every committed profile (each copies the format): every usage a shader or a pass -/// needs is unavailable, whatever its storage and usage. +/// A 4:2:2 texture holds its 2-byte texels in an `R8G8_UNORM` image of its extent, for copies, on +/// every committed profile (each copies the format), its reads and samples its decoded twin's: +/// every other usage a shader or a pass needs is unavailable, whatever its storage and usage. Its +/// twin is an `R8G8B8A8_UNORM` image of the texture's extent and level, its copies' unit an +/// `RGBA8Unorm` texel, and its decode the format's. #[test] fn a_four_two_two_texture_holds_its_texels_in_a_carrier() { + use super::super::chroma_pairs::decode_of; + use super::super::texture::copy_units; + use super::super::texture::decoded_twin::{twin_plan, TwinDecode}; + use metal2vulkan::bind::ChromaDecode; let mut carried = 0; for (name, desc, device) in committed() { let facts = facts(&desc, &device); @@ -1574,13 +1662,24 @@ fn a_four_two_two_texture_holds_its_texels_in_a_carrier() { ); assert_eq!( plan.unavailable, - effective_usage(usage).intersection( - TextureUsage::SHADER_READ - | TextureUsage::SHADER_WRITE - | TextureUsage::RENDER_TARGET - ), + effective_usage(usage) + .intersection(TextureUsage::SHADER_WRITE | TextureUsage::RENDER_TARGET), "{what}" ); + let decode = decode_of(&plan).expect(&what); + assert_eq!(Some(decode), ChromaDecode::of(pf), "{what}"); + for routed in [false, true] { + let twin = twin_plan(&plan, &l, TwinDecode::Chroma(decode), routed); + assert_eq!( + (twin.pixel_format, twin.format), + (PixelFormat::RGBA8Unorm, Format::R8G8B8A8_UNORM), + "{what}" + ); + let unit = (ImageAspectFlags::COLOR, 4, [1, 1]); + assert_eq!(copy_units(twin.format, twin.pixel_format), [unit], "{what}"); + assert!(twin.usage.contains(ImageUsageFlags::SAMPLED), "{what}"); + assert_eq!((twin.extent, twin.levels), ([18, 6, 1], 1), "{what}"); + } check_plan(&name, pf, usage, &plan, &facts); carried += 1; } @@ -1713,7 +1812,7 @@ fn padded_formats_are_held_only_over_given_memory() { #[test] fn decoded_twins_are_planned_in_their_texels_format() { use super::super::texture::copy_units; - use super::super::texture::decoded_twin::twin_plan; + use super::super::texture::decoded_twin::{twin_plan, TwinDecode}; use metal2vulkan::bind::BlockDecode; let both = ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST; let mut planned = 0; @@ -1738,7 +1837,7 @@ fn decoded_twins_are_planned_in_their_texels_format() { }; planned += 1; for routed in [false, true] { - let twin = twin_plan(&plan, decode, routed); + let twin = twin_plan(&plan, &l, TwinDecode::Block(decode), routed); let what = format!("{name}: {pf:?}, routed {routed}"); assert_eq!( (twin.pixel_format, twin.format), @@ -1760,13 +1859,17 @@ fn decoded_twins_are_planned_in_their_texels_format() { /// A decode pass's bands of a region cover each of its texels once, and each band's blocks and /// texels take at most the budget together, so a pass in the device's decode scratch /// (`PassScratch::Device`, of the budget and an alignment) holds any band; only a single block -/// row of one image past the budget is a band alone. Regions of every decode, square and -/// narrow, of sides off a multiple of 4, of layers and of depth slices, under the band budget -/// and two small ones that make them band. +/// row of one image past the budget is a band alone. Regions of BC decodes, of ASTC ones +/// (blocks of 12 x 10 and 4 x 4, texels of 16 and 4 bytes), PVRTC ones, ETC2 and EAC ones +/// (texels of 2, 8 and 4 bytes) and 4:2:2 ones (pairs of 2 x 1), square and narrow, of sides off a +/// multiple of the block, of layers and of depth slices, under the band budget and two small ones +/// that make them band. #[test] fn decode_bands_cover_each_texel_once_within_the_budget() { - use super::super::texture::decoded_twin::{bands, BAND_BYTES}; - use metal2vulkan::bind::BlockDecode; + use super::super::texture::decoded_twin::{bands, TwinDecode, BAND_BYTES}; + use metal2vulkan::bind::{ + AstcDecode, AstcTexels, BlockDecode, ChromaDecode, EtcDecode, EtcTexels, PvrtcDecode, + }; let shapes: [([u32; 3], u32); 7] = [ ([2048, 2048, 1], 1), ([16384, 16, 1], 1), @@ -1776,11 +1879,26 @@ fn decode_bands_cover_each_texel_once_within_the_budget() { ([64, 64, 32], 1), ([3, 1, 1], 1), ]; - for decode in [BlockDecode::Bc1, BlockDecode::Bc3, BlockDecode::Bc5Unorm] { + let astc = |pf| AstcDecode::of(pf).expect("an ASTC decode"); + let decodes = [ + TwinDecode::Block(BlockDecode::Bc1), + TwinDecode::Block(BlockDecode::Bc3), + TwinDecode::Block(BlockDecode::Bc5Unorm), + TwinDecode::Astc(astc(PixelFormat::ASTC12x10LDR), AstcTexels::Float), + TwinDecode::Astc(astc(PixelFormat::ASTC4x4SRGB), AstcTexels::Unorm8), + TwinDecode::Pvrtc(PvrtcDecode::of(PixelFormat::PVRTCRGBA2BPP).expect("a PVRTC decode")), + TwinDecode::Pvrtc(PvrtcDecode::of(PixelFormat::PVRTCRGB4BPP).expect("a PVRTC decode")), + TwinDecode::Etc(EtcDecode::R11Unorm, EtcTexels::Compact), + TwinDecode::Etc(EtcDecode::Rg11Snorm, EtcTexels::Float), + TwinDecode::Etc(EtcDecode::Rgba8, EtcTexels::Compact), + TwinDecode::Chroma(ChromaDecode::Gbgr), + ]; + for decode in decodes { let (texel, block) = ( u64::from(decode.texel_bytes()), u64::from(decode.block_bytes()), ); + let [bw, bh] = decode.block_extent().map(u64::from); for (size, layers) in shapes { for most in [BAND_BYTES, 1 << 20, 64 << 10] { let region = ImageRegion { @@ -1793,11 +1911,16 @@ fn decode_bands_cover_each_texel_once_within_the_budget() { }; let what = format!("{decode:?} {size:?} x{layers} in {most}"); let mut covered = std::collections::BTreeMap::new(); - for band in bands(®ion, texel, block, most) { + for band in bands(®ion, decode, most) { let [w, h, d] = band.size.map(u64::from); - let bytes = w.div_ceil(4) * h.div_ceil(4) * d * u64::from(band.layers) * block + // A whole-level decode's band reads all its images' blocks, of any rows. + let (block_rows, row) = match decode.whole_levels() { + true => (u64::from(size[1]).div_ceil(bh), 1), + false => (h.div_ceil(bh), bh), + }; + let bytes = w.div_ceil(bw) * block_rows * d * u64::from(band.layers) * block + w * h * d * u64::from(band.layers) * texel; - let one_row = band.size[1] <= 4 && d * u64::from(band.layers) == 1; + let one_row = h <= row && d * u64::from(band.layers) == 1; assert!(bytes <= most || one_row, "{what}: {band:?} takes {bytes}"); assert_eq!(band.size[0], size[0], "{what}"); assert_eq!(band.origin[0], region.origin[0], "{what}"); @@ -1820,3 +1943,78 @@ fn decode_bands_cover_each_texel_once_within_the_budget() { } } } + +/// On every committed device without ASTC, every ASTC LDR format's texture, of every usage Metal +/// takes, holds its blocks in a carrier (`astc.rs`) whose every level keeps the blocks the +/// texture's level holds, at sides no multiple of the block too: a whole level's region (and one +/// starting at its second block) maps to the carrier's region of the same blocks, inside the +/// carrier's level, and back. A profile that lists no carrier's copies refuses the texture: the +/// decoded twin's view holds no blocks. +#[test] +fn astc_carriers_hold_each_level_s_blocks() { + use super::super::astc::{decode_of, texture_region, CARRIERS as ASTC_CARRIERS}; + use metal2vulkan::bind::AstcDecode; + use metal2vulkan::metal::format::FormatEmulation; + let mut carried = 0; + for (name, desc, device) in committed() { + let facts = facts(&desc, &device); + let profile = device.profile(); + for &pf in PixelFormat::ALL { + let Some(decode) = AstcDecode::of(pf) else { + continue; + }; + let sampled = vk_format(pf, &[FormatUsage::SampledImage].into(), profile); + if sampled.map(|m| m.emulation) != Ok(FormatEmulation::Decoded) { + continue; + } + let [bw, bh] = decode.block_extent(); + let copies = FormatFeatureFlags2::TRANSFER_SRC | FormatFeatureFlags2::TRANSFER_DST; + let carriers = (ASTC_CARRIERS.iter()).any(|&f| facts.optimal(f).contains(copies)); + for (width, height) in [(1, 1), (7, 3), (16, 16), (37, 23), (100, 257)] { + let what = format!("{name} {pf:?} {width}x{height}"); + let mut l = layout(TextureType::Type2D, pf, 1, 1); + l.extent = [width, height, 1]; + l.levels = width.max(height).ilog2() + 1; + let usage = TextureUsage::SHADER_READ + | TextureUsage::SHADER_WRITE + | TextureUsage::RENDER_TARGET; + let planned = plan_image(&l, usage, false, &facts); + if !carriers { + assert!(planned.is_err(), "{what}: {planned:?}"); + continue; + } + let plan = planned.expect(&what); + assert_eq!(decode_of(&plan), Some(decode), "{what}"); + assert!(ASTC_CARRIERS.contains(&plan.format), "{what}"); + carried += 1; + for level in 0..l.levels { + let [w, h] = [width, height].map(|side| (side >> level).max(1)); + let carrier = [0, 1].map(|axis| (plan.extent[axis] >> level).max(1)); + let blocks = [w.div_ceil(bw), h.div_ceil(bh)]; + assert!(carrier[0].div_ceil(4) >= blocks[0], "{what} level {level}"); + assert!(carrier[1].div_ceil(4) >= blocks[1], "{what} level {level}"); + let starts = [(0, 0), (bw.min(w - 1) / bw * bw, 0)]; + for (x, y) in starts { + let region = ImageRegion { + aspect: ImageAspectFlags::COLOR, + level, + layer: 0, + layers: 1, + origin: [x, y, 0], + size: [w - x, h - y, 1], + }; + let image = image_region(&plan, region); + let end = [0, 1].map(|axis| image.origin[axis] + image.size[axis]); + assert!(end[0] <= carrier[0] && end[1] <= carrier[1], "{what}"); + let across = image.size[0].div_ceil(4); + assert_eq!(across, (w - x).div_ceil(bw), "{what} level {level}"); + assert_eq!(image.size[1].div_ceil(4), blocks[1], "{what}"); + let back = texture_region(&plan, l.extent, image); + assert_eq!(back, Some(region), "{what} level {level} at {x}"); + } + } + } + } + } + assert!(carried > 0, "no committed device holds ASTC in a carrier"); +} diff --git a/crates/metal2vulkan-runtime/src/tests/pixel_format_info.rs b/crates/metal2vulkan-runtime/src/tests/pixel_format_info.rs index 5bea7b716..f9de7b53d 100644 --- a/crates/metal2vulkan-runtime/src/tests/pixel_format_info.rs +++ b/crates/metal2vulkan-runtime/src/tests/pixel_format_info.rs @@ -293,3 +293,45 @@ fn extents_near_two_to_the_64_wrap_the_block_count() { } } } + +/// Every ASTC LDR format, and its sRGB form, is described as Metal describes it whatever the +/// device holds its blocks in (its ASTC format, or a carrier, `astc.rs`): a format of blocks (flags +/// bit 0x400) of 16 bytes, its footprint, depth 1; and a level's layout counts its blocks, a side +/// no multiple of the block rounded up, rows of 16-byte blocks, an image of those rows. +#[test] +fn astc_formats_answer_metal_s_blocks_and_levels() { + use metal2vulkan::bind::AstcDecode; + let formats = P::ALL + .iter() + .filter_map(|&pf| AstcDecode::of(pf).map(|decode| (pf, decode))); + let mut seen = 0; + for (pf, decode) in formats { + seen += 1; + let [bw, bh] = decode.block_extent().map(u64::from); + for level in MetalLevel::ALL { + let raw = u64::from(pf.as_raw()); + let info = level.pixel_format_info(raw); + assert_ne!(info.flags & 0x400, 0, "{level} {pf:?}"); + assert_eq!(info.words, [16, bw, bh, 1], "{level} {pf:?}"); + for (width, height, mip) in [(37, 23, 0), (37, 23, 2), (1000, 7, 1), (1, 1, 0)] { + let at = |side: u64| (side >> mip).max(1); + let (w, h) = (at(width), at(height)); + let [across, down] = [w.div_ceil(bw), h.div_ceil(bh)]; + let mut query = TextureLevelQuery::plane_2d(raw, width, height); + query.level = mip; + let answer = level.texture_level_info(&query); + let what = format!("{level} {pf:?} {width}x{height} level {mip}"); + assert_eq!([answer.width, answer.height], [w, h], "{what}"); + assert_eq!( + [answer.blocks_across, answer.blocks_down], + [across, down], + "{what}" + ); + assert_eq!(answer.bytes_per_block, 16, "{what}"); + assert_eq!(answer.bytes_per_row, 16 * across, "{what}"); + assert_eq!(answer.bytes_per_image, 16 * across * down, "{what}"); + } + } + } + assert_eq!(seen, 28); +} diff --git a/crates/metal2vulkan-runtime/src/tests/view_plan.rs b/crates/metal2vulkan-runtime/src/tests/view_plan.rs index 638d9da21..37e7d4600 100644 --- a/crates/metal2vulkan-runtime/src/tests/view_plan.rs +++ b/crates/metal2vulkan-runtime/src/tests/view_plan.rs @@ -200,7 +200,7 @@ fn view_formats_follow_metals_measured_verdicts() { ); match check_view( &source, - &ViewRequest::of_format(&source, P::PVRTCRGB2BPP), + &ViewRequest::of_format(&source, P::ASTC4x2HDR), device.profile(), ) { Err(ViewRefusal::Unsupported(u)) => assert_eq!(u.feature, Feature::Format), diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 705cd3f3c..be8fbd48c 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -123,7 +123,7 @@ use ash::vk::Handle; use decoded_twin::{Decoded, PassScratch}; use first_move::{FirstMove, Fresh, Keep, Pattern, Patterned, TexelCopy, PATTERN_BYTES}; use heap_tiled::{FreshDepth, FreshPattern}; -use metal2vulkan::bind::{ImageViewDesc, TextureFacts}; +use metal2vulkan::bind::{AstcDecode, EtcDecode, ImageViewDesc, PvrtcDecode, TextureFacts}; use metal2vulkan::device::{ DeviceDescription, DeviceProfile, DriverFact, FormatSupport, VkFeature, }; @@ -221,6 +221,9 @@ pub(super) struct TextureState { pub(super) first_moves: first_move::FirstMoves, /// The decoded twins' CPU decodes and the thread that runs them (`texture/twin_decode.rs`). pub(super) twin_decodes: twin_decode::TwinDecodes, + /// The decodes queued for ASTC carriers' second decoded twins, which the device's next batch + /// with work records (`texture/decoded_twin.rs`). + pub(super) second_decodes: decoded_twin::SecondDecodes, } impl TextureState { @@ -252,6 +255,7 @@ impl TextureState { storage_forms: storage_form::StorageForms::default(), first_moves: first_move::FirstMoves::default(), twin_decodes: twin_decode::TwinDecodes::default(), + second_decodes: Mutex::new(Vec::new()), } } @@ -483,8 +487,12 @@ struct Image { twin: Option>, /// The image's decoded twin (`texture/decoded_twin.rs`): a BC1 to BC5 image's texels as /// Metal decodes them, which its sampled views present, on a device whose driver is not - /// measured to decode them so. + /// measured to decode them so; an ASTC or PVRTC carrier's. decoded: Option>, + /// An ASTC carrier's second decoded twin (`texture/decoded_twin.rs`): its blocks' decode in + /// the texture's other colour space (its LDR form's for an sRGB texture, its sRGB form's for + /// an LDR one), made at the first view of the texture in that form. + second: OnceLock>, /// The storage form a fetched render target's image may take once (`texture/storage_form.rs`). form: storage_form::Form, /// Whether a blit wrote bytes outside the image's texels, which Metal's blit of a two-plane @@ -1084,11 +1092,13 @@ impl Image { self.device.shared().textures.first_moves.register(fresh); } - /// Whether its move, or its depth twin's or its decoded twin's, waits for a submission. + /// Whether its move, or its depth twin's or one of its decoded twins', waits for a + /// submission. fn move_waits(&self) -> bool { lock(&self.first_move).is_some() || (self.twin.as_ref()).is_some_and(|twin| lock(&twin.first_move).is_some()) || (self.decoded.as_ref()).is_some_and(|d| lock(&d.image.first_move).is_some()) + || (self.second.get()).is_some_and(|d| lock(&d.image.first_move).is_some()) } /// Make its move now where it waits, by an internal submission waited for: for a `VkImage` @@ -1274,20 +1284,23 @@ impl Fresh for Image { .take() .filter(|first| twin.holds(first.image)) }); - let decoded = (self.decoded.as_ref()).and_then(|decoded| { - lock(&decoded.image.first_move) - .take() - .filter(|first| decoded.image.holds(first.image)) - }); + let decoded = (self.decoded.as_deref().into_iter()) + .chain(self.second.get().map(Box::as_ref)) + .filter_map(|decoded| { + lock(&decoded.image.first_move) + .take() + .filter(|first| decoded.image.holds(first.image)) + }); own.into_iter().chain(twin).chain(decoded).collect() } fn give_back(&self, moves: Vec) { for first in moves { let twin = (self.twin.as_deref()).filter(|twin| twin.raw.get() == first.image); - let decoded = (self.decoded.as_deref()) + let decoded = (self.decoded.as_deref().into_iter()) + .chain(self.second.get().map(Box::as_ref)) .map(|decoded| &decoded.image) - .filter(|decoded| decoded.raw.get() == first.image); + .find(|decoded| decoded.raw.get() == first.image); let image = twin.or(decoded).unwrap_or(self); // A rebind may have swapped another `VkImage` in meanwhile, whose move it noted. if image.holds(first.image) { @@ -1630,6 +1643,14 @@ impl Device { // A depth twin would need its own memory bound alike. return Err(Error::NotImplemented(RuntimeGap::SparseHeaps)); } + // An ASTC, ETC2, EAC or 4:2:2 carrier's samples read a decoded twin, which tiles GPU + // commands map would leave behind (`astc.rs`, `etc.rs`, `chroma_pairs.rs`). + if super::astc::decode_of(&plan).is_some() + || super::etc::decode_of(&plan).is_some() + || super::chroma_pairs::decode_of(&plan).is_some() + { + return Err(Error::NotImplemented(RuntimeGap::DecodedHeapTexture)); + } let mask: vk::ImageAspectFlags = image_aspects(plan.format).into(); let [width, height, depth] = layout.extent; let shape = SparseShape { @@ -1771,6 +1792,7 @@ impl Device { resolves: KeptResolves::new(), twin: None, decoded: None, + second: OnceLock::new(), form: Default::default(), kept_outside: AtomicBool::new(false), signed_depth: AtomicBool::new(false), @@ -1897,6 +1919,7 @@ impl Device { resolves: KeptResolves::new(), twin: None, decoded: None, + second: OnceLock::new(), form: Default::default(), kept_outside: AtomicBool::new(false), signed_depth: AtomicBool::new(false), @@ -2517,6 +2540,7 @@ impl Device { resolves: KeptResolves::new(), twin: None, decoded: None, + second: OnceLock::new(), form: Default::default(), kept_outside: AtomicBool::new(false), signed_depth: AtomicBool::new(false), @@ -2861,6 +2885,7 @@ impl Device { resolves: KeptResolves::new(), twin: None, decoded: None, + second: OnceLock::new(), form: Default::default(), kept_outside: AtomicBool::new(false), signed_depth: AtomicBool::new(false), @@ -3692,6 +3717,7 @@ impl Device { resolves: KeptResolves::new(), twin: None, decoded: None, + second: OnceLock::new(), form: Default::default(), kept_outside: AtomicBool::new(false), signed_depth: AtomicBool::new(false), @@ -5714,6 +5740,32 @@ impl Texture { Problem::TextureView(ViewProblem::BufferSlices), )); } + // A carrier's decoded twin holds its own blocks' decode alone: a view of another decode + // (an ASTC format's HDR form or another footprint, another PVRTC block, an EAC 11-bit + // format's other signedness) reads no twin (`astc.rs`, `pvrtc.rs`, `etc.rs`; a PVRTC, + // ETC2 or EAC format's sRGB form's codes are its linear form's). A view of an ASTC + // texture in its other colour space reads the carrier's second twin, made now where it + // has none (`texture/decoded_twin.rs`). + if let Storage::Image(image) = &self.0.storage { + let truth = view_shadow::truth(image); + let pf = record.pixel_format; + let astc = super::astc::decode_of(truth.plan()).map(|held| (held, AstcDecode::of(pf))); + let other_space = matches!(astc, Some((held, Some(view))) + if view.srgb != held.srgb && [view.width, view.height] == [held.width, held.height]); + let astc = astc.is_some_and(|(held, view)| view != Some(held)) && !other_space; + let pvrtc = super::pvrtc::decode_of(truth.plan()) + .is_some_and(|held| PvrtcDecode::of(pf).map(PvrtcDecode::linear) != Some(held)); + let etc = super::etc::decode_of(truth.plan()) + .is_some_and(|held| EtcDecode::of(pf) != Some(held)); + if astc || pvrtc || etc { + return Err(Error::Unsupported(Unsupported::not_implemented( + Feature::TextureView, + ))); + } + if other_space { + truth.make_second_twin(pf)?; + } + } // A view shares its texture's storage: its image, its buffer's bytes, and a shadowed // texture's copies, so its uses are its texture's. Where the image takes no Vulkan view // of the view's format (the device reinterprets no image's components, or the texture's @@ -5909,7 +5961,8 @@ impl Texture { if firsts.register_texels(keeper, staged) { truth.submit_copy(|_, _| {})?; } - return Ok(()); + // An ASTC carrier's second twin's decode, for the next batch, after the copy. + return truth.queue_second_decode(regions); } let mut staging = Staging::new(device, host.packed_len())?; host.pack(bytes, staging.bytes()); @@ -5944,7 +5997,9 @@ impl Texture { // SAFETY: as above; the pass lives until the submission, waited for, completed. unsafe { decode.record(raw, command_buffer) }; } - }) + })?; + // An ASTC carrier's second twin's decode, for the next batch. + truth.queue_second_decode(std::slice::from_ref(&image_region)) } /// `getBytes:bytesPerRow:bytesPerImage:fromRegion:mipmapLevel:slice:`: read `region` of @@ -6250,9 +6305,12 @@ impl Texture { return Err(Error::NotImplemented(RuntimeGap::PvrtcBlockOrder)); } } - // A 2-bit PVRTC texture's carrier halves its regions' x (`pvrtc.rs`). + // A 2-bit PVRTC texture's carrier halves its regions' x (`pvrtc.rs`); an ASTC texture's + // carrier holds each block in 4 x 4 of its texels (`astc.rs`). let planned = match &self.0.storage { - Storage::Image(image) if holds_blocks(image.plan()) => { + Storage::Image(image) + if holds_blocks(image.plan()) || super::astc::decode_of(image.plan()).is_some() => + { image_region(image.plan(), planned) } _ => planned, diff --git a/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs b/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs index b817d80ad..b5efd1aac 100644 --- a/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs +++ b/crates/metal2vulkan-runtime/src/texture/decoded_twin.rs @@ -20,8 +20,8 @@ //! //! **Kept in step.** After every write into the BC image (`replace_region`, staged or submitted //! now; a blit from a buffer, `fillTexture` included; a copy from a texture), the written region -//! is decoded into the twin by `bind::block_decode_module` ([`DecodePass`]): its blocks copied -//! into a scratch buffer, decoded, and the texels copied into the twin, in bands of whole block +//! is decoded into the twin by the decode's kernel (`TwinDecode::module`; [`DecodePass`]): its +//! blocks copied into a scratch buffer, decoded, and the texels copied into the twin, in bands of whole block //! rows of at most [`BAND_BYTES`] of blocks and texels, which bound the scratch: the pass's own, //! or for a pass the device's next submission takes, the device's ([`PassScratch`]). A new //! texture's twin starts as its zero blocks decode (the zeros: BC1 opaque black, every other format @@ -30,7 +30,7 @@ //! //! **Host writes decode on the CPU** (off the caller's thread). A `replace_region` whose blocks go //! on the host or the staging queue queues the region's decode on the CPU -//! (`BlockDecode::decode_into`, the kernel's rules) for the device's decode thread, which copies +//! (`TwinDecode::decode_into`, the kernel's rules) for the device's decode thread, which copies //! its texels into the twin the same way ([`Image::decode_written`], `twin_decode.rs`, announced //! `cpu-block-decode`). A batch that may read the texture waits at its submission for that; one //! submitted before the call and not yet complete makes the call wait for its decode, so it reads @@ -43,6 +43,59 @@ //! (`decode_twin`) is the caller's command's, and covers only what it wrote, as Metal's write of //! those texels would. //! +//! **ASTC** (`astc.rs`): on a device without a texture's ASTC LDR format its blocks lie in a +//! carrier image and its twin holds Metal's decode in the texels `DevicePolicy::decoded_texels` names +//! (`TwinDecode::Astc`; an sRGB form's 8-bit codes under either, which its slots read raw and +//! decode through Metal's table), kept in step as a BC image's twin is (`bind::astc_decode_module` +//! on the GPU, `AstcDecode::decode_into` on the CPU): a pass's bands are of the texture's texels, +//! each band's blocks copied out of the carrier's texels over them. A new one's zero blocks read +//! magenta (an error block). +//! +//! **An ASTC texture's other colour space.** Metal views an ASTC texture as its `_sRGB` or LDR +//! form over the same blocks, whatever its usage, and the view reads what a texture of its own +//! format over those blocks reads (our probe on an M3 Max, macOS 27.0.1: reads and linear samples +//! bit for bit, footprints 4x4, 6x5 and 12x12). The two forms widen the endpoints apart +//! (`bind::AstcDecode`), so neither's texels follow from the other's: the first view of the +//! texture in its other colour space makes the carrier a second twin ([`Image::make_second_twin`]), +//! of that form's decode in the texels the policy names, in memory of its own, which the CPU +//! never writes. Its decodes are the GPU's, each recorded by a batch's submission +//! ([`SecondDecode`]): its whole decode as it is made, and a host write's, queued for the +//! device's next batch with work, which records them before its work, their uses joined to its +//! first part's, so the tracker orders them after earlier writes of the texture +//! ([`Device::take_second_decodes`]); a blit's write's, made as the blit is encoded where the +//! twin is there then, recorded by its batch after the blit's encoder ([`TwinWrite`]). A write +//! encoded before the twin was made has no decode: its batch leaves the texture's queued decodes, +//! the whole decode among them, to a later batch, which reads the carrier as the write left it. +//! Without a second twin a submission records nothing for such writes (counted: +//! `WorkCounts::second_twins`, `second_twin_checks`, `second_twin_decodes`). +//! +//! **PVRTC** (`pvrtc.rs`): on a device without a texture's PVRTC format its blocks lie in a +//! carrier too, and its twin holds their codes (`TwinDecode::Pvrtc`, `R8G8B8A8_UNORM`; an sRGB +//! form's slots read them raw and decode them through Metal's table), which serve the views of the +//! format's linear and sRGB forms alike. Each texel's colors come from the four blocks around it, +//! wrapping at the level's edges, so a write's decode is of whole levels (`twin_region`): on the +//! GPU (`bind::pvrtc_decode_module`), each band of a level's rows with all of its blocks, or a +//! host write's on the CPU (`PvrtcDecode::decode_rows`), a host write being of whole levels. A new +//! one's zero blocks read transparent black (an RGB format's opaque). +//! +//! **ETC2 and EAC** (`etc.rs`): on a device without the formats their blocks lie in a carrier of +//! the texture's shape, and the twin holds Metal's decode (`TwinDecode::Etc`): an 8-bit format's +//! codes (`R8G8B8A8_UNORM`; an sRGB form's slots read them raw and decode them through Metal's +//! table), which serve the views of its linear and sRGB forms alike, and an 11-bit format's texels +//! `DevicePolicy::decoded_texels` names (`bind::EtcTexels`). Each is kept in step as a BC image's +//! twin is (`bind::etc_decode_module` on the GPU, `EtcDecode::decode_into` on the CPU). A new +//! one's zero blocks read grey of codes 2 (`ETC2_RGB8`, and `EAC_RGBA8`'s colour, its alpha 0), +//! opaque black (`RGB8A1`), or an 11-bit value of 1 (signed -3), not zeros: the twin starts +//! cleared to them. +//! +//! **4:2:2** (`chroma_pairs.rs`): a `GBGR422` or `BGRG422` texture's texels lie in a carrier of +//! 2 bytes a texel, the texture's shape, and its twin holds Metal's texels (`TwinDecode::Chroma`, +//! `R8G8B8A8_UNORM` codes, exact), kept in step as an ETC2 texture's twin is +//! (`bind::chroma_decode_module` on the GPU, `ChromaDecode::decode_into` on the CPU). A texel's red +//! and blue read the pair beside it, so a write's decode is of whole rows (`twin_region`; a host +//! write of part of a row decodes its rows as the carrier then holds them, read back first). A new +//! one's zero pairs read opaque black: the twin starts cleared to it. +//! //! **Without a twin**, announced `compressed-texel-decode` as before: a texture over the caller's //! host pages or laid out apart from a heap's bytes (tiled, shadowed), a sparse texture, a //! texture over an IOSurface or the caller's image, one whose twin's format the device lacks; @@ -53,14 +106,18 @@ //! after each write. A `VkImage` handed out (`Texture::vk_image`) is the BC image: what the //! caller writes into it outside the runtime's calls leaves the twin as it was. +use super::super::astc; use super::super::blit::{BlitCommandEncoder, TRANSFER}; +use super::super::chroma_pairs; use super::super::copy_plan::ImageRegion; use super::super::degradation::Degradation; use super::super::device::{lock, DebugMessage, MessageKind, MessageSeverity}; use super::super::error::{internal, Error}; +use super::super::etc; use super::super::exit_guard::{self, Call}; use super::super::image_plan::ImagePlan; use super::super::owned_kernel::{OwnedModule, OwnedSets}; +use super::super::pvrtc; use super::super::resource::Identity; use super::super::resource::ResourceKey; use super::super::texture_descriptor::{TextureDescriptor, TextureLayout}; @@ -76,26 +133,206 @@ use super::{ }; use crate::device::functions::Vk; use ash::vk; -use metal2vulkan::bind::{BlockDecode, BlockDecodeModule, ImageViewDesc}; +use metal2vulkan::bind::{ + AstcDecode, AstcTexels, BlockDecode, BlockDecodeModule, ChromaDecode, EtcDecode, EtcTexels, + ImageViewDesc, PvrtcDecode, +}; +use metal2vulkan::device::DecodedTexelsPolicy; +use metal2vulkan::device::FormatUsage; +use metal2vulkan::error::{Capability, Feature, Unsupported}; use metal2vulkan::metal::format::FormatMapping; +use metal2vulkan::metal::PixelFormat; use metal2vulkan::vk::{ Format, FormatFeatureFlags2, ImageAspectFlags, ImageCreateFlags, ImageType, ImageUsageFlags, }; -use std::sync::{Arc, Weak}; +use std::sync::{Arc, Mutex, Weak}; + +/// What a decoded twin's format must take on the device: sampling, its linear filter and copies +/// into it. +const TWIN_FEATURES: FormatFeatureFlags2 = FormatFeatureFlags2::SAMPLED_IMAGE + .union(FormatFeatureFlags2::SAMPLED_IMAGE_FILTER_LINEAR) + .union(FormatFeatureFlags2::TRANSFER_DST); /// The most bytes of texels one band of a decode pass holds: its scratch's texels (and fewer /// blocks), within `maxStorageBufferRange`. pub(crate) const BAND_BYTES: u64 = 32 << 20; -/// A BC1 to BC5 image's decoded twin (the module docs). +/// How a decoded twin's blocks decode: a BC1 to BC5 format's (`BlockDecode`), an ASTC LDR +/// format's held in a carrier (`astc.rs`) into the texels the device's policy names, a PVRTC +/// format's held in a carrier (`pvrtc.rs`) into its codes (its linear form's decode, which its +/// sRGB form's is too), an ETC2 or EAC format's held in a carrier (`etc.rs`) into its codes or +/// an 11-bit format's texels the policy names (its unorm form's decode, which its sRGB form's is +/// too), or a 4:2:2 format's pairs held in a carrier (`chroma_pairs.rs`) into its codes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum TwinDecode { + Block(BlockDecode), + Astc(AstcDecode, AstcTexels), + Pvrtc(PvrtcDecode), + Etc(EtcDecode, EtcTexels), + Chroma(ChromaDecode), +} + +impl TwinDecode { + /// The texels across and down of a block. + pub(crate) fn block_extent(self) -> [u32; 2] { + match self { + TwinDecode::Block(_) => [4, 4], + TwinDecode::Astc(decode, _) => decode.block_extent(), + TwinDecode::Pvrtc(decode) => decode.block_extent(), + TwinDecode::Etc(decode, _) => decode.block_extent(), + TwinDecode::Chroma(decode) => decode.block_extent(), + } + } + + /// Whether a write's decode is of whole levels: a PVRTC texel's colors come from the blocks + /// around it, wrapping at the level's edges. + pub(crate) fn whole_levels(self) -> bool { + matches!(self, TwinDecode::Pvrtc(_)) + } + + /// Whether a write's decode is of whole rows: a 4:2:2 texel's red and blue read the pair + /// beside it. + pub(crate) fn whole_rows(self) -> bool { + matches!(self, TwinDecode::Chroma(_)) + } + + /// The bytes of a block. + pub(crate) fn block_bytes(self) -> u32 { + match self { + TwinDecode::Block(decode) => decode.block_bytes(), + TwinDecode::Astc(..) => AstcDecode::BLOCK_BYTES, + TwinDecode::Pvrtc(_) => PvrtcDecode::BLOCK_BYTES, + TwinDecode::Etc(decode, _) => decode.block_bytes(), + TwinDecode::Chroma(_) => ChromaDecode::BLOCK_BYTES, + } + } + + /// The bytes of a decoded texel. + pub(crate) fn texel_bytes(self) -> u32 { + match self { + TwinDecode::Block(decode) => decode.texel_bytes(), + TwinDecode::Astc(_, texels) => AstcDecode::texel_bytes(texels), + TwinDecode::Pvrtc(_) => PvrtcDecode::TEXEL_BYTES, + TwinDecode::Etc(decode, texels) => decode.texel_bytes(texels), + TwinDecode::Chroma(_) => ChromaDecode::TEXEL_BYTES, + } + } + + /// The Vulkan format of the decoded texels. + pub(crate) fn texel_format(self) -> Format { + match self { + TwinDecode::Block(decode) => decode.texel_format(), + TwinDecode::Astc(decode, texels) => decode.texel_format(texels), + TwinDecode::Pvrtc(decode) => decode.texel_format(), + TwinDecode::Etc(decode, texels) => decode.texel_format(texels), + TwinDecode::Chroma(decode) => decode.texel_format(), + } + } + + /// The Metal pixel format whose texels the decoded ones are. + fn texel_pixel_format(self) -> PixelFormat { + match self { + TwinDecode::Block(decode) => decode.texel_pixel_format(), + TwinDecode::Astc(decode, texels) => decode.texel_pixel_format(texels), + TwinDecode::Pvrtc(decode) => decode.texel_pixel_format(), + TwinDecode::Etc(decode, texels) => decode.texel_pixel_format(texels), + TwinDecode::Chroma(decode) => decode.texel_pixel_format(), + } + } + + /// The decode of a texture of `pf`, whose texels it decodes as the twin's: the same BC + /// decode, the same ASTC format (an sRGB form is another decode), the same PVRTC, ETC2 or + /// EAC blocks (an sRGB form's codes are its linear form's), or the same 4:2:2 pairs. + fn decodes(self, pf: PixelFormat) -> bool { + match self { + TwinDecode::Block(decode) => BlockDecode::of(pf) == Some(decode), + TwinDecode::Astc(decode, _) => AstcDecode::of(pf) == Some(decode), + TwinDecode::Pvrtc(decode) => { + PvrtcDecode::of(pf).map(PvrtcDecode::linear) == Some(decode) + } + TwinDecode::Etc(decode, _) => EtcDecode::of(pf) == Some(decode), + TwinDecode::Chroma(decode) => ChromaDecode::of(pf) == Some(decode), + } + } + + /// [`decode_into`](Self::decode_into) into a new buffer. + pub(crate) fn decode(self, blocks: &[u8], size: [u32; 3]) -> Vec { + let [width, height, depth] = size.map(|axis| axis as usize); + let mut texels = vec![0; width * height * depth * self.texel_bytes() as usize]; + self.decode_into(blocks, size, &mut texels); + texels + } + + /// The texels of a region `size` whose `blocks` lie as a copy of the region out of the + /// blocks' image lays them, into `texels`, laid out as a copy into the twin reads them (a + /// PVRTC region's images whole levels, [`whole_levels`](Self::whole_levels)). + pub(crate) fn decode_into(self, blocks: &[u8], size: [u32; 3], texels: &mut [u8]) { + match self { + TwinDecode::Block(decode) => decode.decode_into(blocks, size, texels), + TwinDecode::Astc(decode, form) => decode.decode_into(form, blocks, size, texels), + TwinDecode::Pvrtc(decode) => texels.copy_from_slice(&decode.decode(blocks, size)), + TwinDecode::Etc(decode, form) => decode.decode_into(form, blocks, size, texels), + TwinDecode::Chroma(decode) => decode.decode_into(blocks, size, texels), + } + } + + /// The texels of rows `first` to `first + rows` of one image `width` x `height` of a region + /// whose `blocks` (all of the image's) lie as for [`decode_into`](Self::decode_into), into + /// `texels`: a block decode's rows start at a block row (`first` a multiple of the block's + /// height); a PVRTC image's rows read all its blocks. + pub(crate) fn decode_rows( + self, + blocks: &[u8], + [width, height]: [u32; 2], + [first, rows]: [u32; 2], + texels: &mut [u8], + ) { + if let TwinDecode::Pvrtc(decode) = self { + decode.decode_rows(blocks, [width, height], [first, rows], texels); + return; + } + let [bw, bh] = self.block_extent(); + let row = (width.div_ceil(bw) * self.block_bytes()) as usize; + let at = (first / bh) as usize * row; + self.decode_into(&blocks[at..], [width, rows, 1], texels); + } + + /// The module of `device` whose dispatch decodes its blocks into the twin's texels on the + /// GPU ([`Image::decode_pass`]), each decode's own kernel on `BlockDecodeModule`'s bindings: + /// `bind::block_decode_module`'s, `bind::astc_decode_module`'s, `bind::etc_decode_module`'s + /// and `bind::chroma_decode_module`'s of its shape, `bind::pvrtc_decode_module`'s of + /// `PvrtcDecode::shape`. + pub(crate) fn module( + self, + device: &metal2vulkan::device::Device, + ) -> Result { + match self { + TwinDecode::Block(decode) => metal2vulkan::bind::block_decode_module(device, decode), + TwinDecode::Astc(decode, texels) => { + metal2vulkan::bind::astc_decode_module(device, decode, texels) + } + TwinDecode::Pvrtc(decode) => metal2vulkan::bind::pvrtc_decode_module(device, decode), + TwinDecode::Etc(decode, texels) => { + metal2vulkan::bind::etc_decode_module(device, decode, texels) + } + TwinDecode::Chroma(decode) => metal2vulkan::bind::chroma_decode_module(device, decode), + } + } +} + +/// A BC1 to BC5 image's, or an ASTC, PVRTC, ETC2, EAC or 4:2:2 carrier's, decoded twin (the +/// module docs). pub(super) struct Decoded { - /// The twin: `decode`'s texels, of the BC image's shape, levels and layers. + /// The twin: `decode`'s texels, of the texture's shape, levels and layers. pub(super) image: Image, - /// How the BC image's blocks decode. - pub(super) decode: BlockDecode, + /// How the blocks decode. + pub(super) decode: TwinDecode, /// It was made moved alone (`Start::Moved`): its texels start as the CPU's decode of the zero /// blocks, written as the texture is made ([`Texture::start_decoded_twin`]). started_on_the_cpu: bool, + /// The layout and descriptor of the texture it was made for, by which an ASTC carrier's + /// second twin is made ([`Image::make_second_twin`]). + made_for: (TextureLayout, TextureDescriptor), } impl Decoded { @@ -105,7 +342,30 @@ impl Decoded { fn view_format(&self, format: Format) -> Option { use BlockDecode as D; use Format as F; - match (self.decode, format) { + // An ASTC texture's binding views name its candidate's 8-bit format (its `_sRGB` form's + // `R8G8B8A8_SRGB`, or its raw view `R8G8B8A8_UNORM`, whose codes its twin holds): the + // twin's own view of it, or an LDR twin's exact values. + // A PVRTC texture's name the same formats, and the twin holds their codes; so does an + // ETC2 or EAC 8-bit format's, and an 11-bit one's name its compact texels' format. A + // 4:2:2 texture's name the codes' `R8G8B8A8_UNORM` alone (it has no sRGB form). + let named = matches!(format, F::R8G8B8A8_UNORM | F::R8G8B8A8_SRGB); + let decode = match self.decode { + TwinDecode::Block(decode) => decode, + TwinDecode::Astc(_, texels) => { + return named.then_some(match texels { + AstcTexels::Unorm8 => format, + _ => self.decode.texel_format(), + }); + } + TwinDecode::Pvrtc(_) => return named.then_some(format), + TwinDecode::Etc(etc, texels) if etc.eleven_bit() => { + let compact = etc.texel_format(EtcTexels::Compact); + return (format == compact).then_some(etc.texel_format(texels)); + } + TwinDecode::Etc(..) => return named.then_some(format), + TwinDecode::Chroma(_) => return (format == F::R8G8B8A8_UNORM).then_some(format), + }; + match (decode, format) { (D::Bc1, F::BC1_RGBA_SRGB_BLOCK) | (D::Bc2, F::BC2_SRGB_BLOCK) | (D::Bc3, F::BC3_SRGB_BLOCK) => Some(F::R8G8B8A8_SRGB), @@ -115,7 +375,7 @@ impl Decoded { | (D::Bc4Unorm, F::BC4_UNORM_BLOCK) | (D::Bc4Snorm, F::BC4_SNORM_BLOCK) | (D::Bc5Unorm, F::BC5_UNORM_BLOCK) - | (D::Bc5Snorm, F::BC5_SNORM_BLOCK) => Some(self.decode.texel_format()), + | (D::Bc5Snorm, F::BC5_SNORM_BLOCK) => Some(decode.texel_format()), _ => None, } } @@ -129,12 +389,13 @@ impl Decoded { fn bytes(&self) -> (u64, u64) { let plan = self.image.plan(); let decode = self.decode; + let [bw, bh] = decode.block_extent().map(u64::from); (0..plan.levels) .map(|level| { let [w, h, d] = plan.extent.map(|axis| u64::from((axis >> level).max(1))); let layers = u64::from(plan.layers); let texels = w * h * d * layers * u64::from(decode.texel_bytes()); - let blocks = w.div_ceil(4) * h.div_ceil(4) * d * layers; + let blocks = w.div_ceil(bw) * h.div_ceil(bh) * d * layers; (texels, blocks * u64::from(decode.block_bytes())) }) .fold((0, 0), |(t, b), (texels, blocks)| (t + texels, b + blocks)) @@ -149,21 +410,35 @@ fn placed(image: &Image) -> Option { } } -/// The plan of the decoded twin of a BC image of `plan` whose blocks decode by `decode`: the -/// image's type, shape, levels, layers and cube compatibility, of the decoded texels' format -/// (mutable for an sRGB view of BC1 to BC3's codes; `BlockDecode::texel_pixel_format`'s), sampled -/// and copied into. `routed`: the BC image's CPU copies go on the host or the staging queue, which -/// the twin starts on and takes the CPU's decodes through ([`Image::decode_written`]), copied both -/// ways as the staging queue's images are (`Device::stages`). -pub(crate) fn twin_plan(plan: &ImagePlan, decode: BlockDecode, routed: bool) -> ImagePlan { +/// The plan of the decoded twin of the blocks' image of `plan`, a texture of `layout`, whose +/// blocks decode by `decode`: the texture's type, shape (its extent, which an ASTC carrier's is +/// not), levels, layers and cube compatibility, of the decoded texels' format (mutable for an sRGB +/// view of 8-bit codes; `TwinDecode::texel_pixel_format`'s), sampled and copied into. `routed`: +/// the blocks' CPU copies go on the host or the staging queue, which the twin starts on and takes +/// the CPU's decodes through ([`Image::decode_written`]), copied both ways as the staging queue's +/// images are (`Device::stages`). +pub(crate) fn twin_plan( + plan: &ImagePlan, + layout: &TextureLayout, + decode: TwinDecode, + routed: bool, +) -> ImagePlan { let format = decode.texel_format(); + // A cube texture's twin is cube compatible, as its image would be (a carrier is not). let kept = ImageCreateFlags::CUBE_COMPATIBLE | ImageCreateFlags::CREATE_2D_ARRAY_COMPATIBLE; + let wanted = match decode { + TwinDecode::Block(_) => plan.flags & kept, + TwinDecode::Astc(..) + | TwinDecode::Pvrtc(_) + | TwinDecode::Etc(..) + | TwinDecode::Chroma(_) => super::super::image_plan::cube_flags(layout), + }; let (flags, view_formats) = match format { Format::R8G8B8A8_UNORM => ( - (plan.flags & kept) | ImageCreateFlags::MUTABLE_FORMAT, + wanted | ImageCreateFlags::MUTABLE_FORMAT, vec![Format::R8G8B8A8_UNORM, Format::R8G8B8A8_SRGB], ), - _ => (plan.flags & kept, Vec::new()), + _ => (wanted, Vec::new()), }; let copies = match routed { true => ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST, @@ -175,7 +450,7 @@ pub(crate) fn twin_plan(plan: &ImagePlan, decode: BlockDecode, routed: bool) -> flags, image_type: plan.image_type, format, - extent: plan.extent, + extent: layout.extent, levels: plan.levels, layers: plan.layers, samples: plan.samples, @@ -196,6 +471,76 @@ impl Device { (!measured && layout.samples == 1).then_some(decode) } + /// The texels of the decoded twin of an ASTC texture of `decode` on this device: an sRGB + /// form's 8-bit codes either way, which its slots read raw and decode through Metal's table, + /// exactly (`metal::texel_format::srgb_raw_on`); an LDR form's Metal's exact values where + /// `DevicePolicy::decoded_texels` asks for them and the device samples, filters and copies + /// into their format, else 8-bit codes. Refused where the device does not even take the + /// codes' format so (no conformant device). + fn astc_texels(&self, decode: AstcDecode) -> Result { + let facts = self + .shared() + .textures + .facts(self.compile_device().profile()); + let takes = |texels: AstcTexels| { + facts + .optimal(decode.texel_format(texels)) + .contains(TWIN_FEATURES) + }; + let wanted = match self.compile_device().policy().decoded_texels { + DecodedTexelsPolicy::Exact if !decode.srgb => AstcTexels::Float, + _ => AstcTexels::Unorm8, + }; + [wanted, AstcTexels::Unorm8] + .into_iter() + .find(|&texels| takes(texels)) + .ok_or_else(|| { + Error::Unsupported(Unsupported::needs( + Feature::Format, + Capability::Format { + format: decode.texel_format(AstcTexels::Unorm8), + usage: FormatUsage::SampledImageFilterLinear, + }, + )) + }) + } + + /// The texels of the decoded twin of an ETC2 or EAC texture of `decode` on this device: an + /// 8-bit format's codes either way; an 11-bit format's values exactly where + /// `DevicePolicy::decoded_texels` asks for them, else 16-bit normalized codes, each where the + /// device samples, filters and copies into their format, else the other. Refused where the + /// device takes neither so. + fn etc_texels(&self, decode: EtcDecode) -> Result { + if !decode.eleven_bit() { + return Ok(EtcTexels::Compact); + } + let facts = self + .shared() + .textures + .facts(self.compile_device().profile()); + let takes = |texels: EtcTexels| { + facts + .optimal(decode.texel_format(texels)) + .contains(TWIN_FEATURES) + }; + let order = match self.compile_device().policy().decoded_texels { + DecodedTexelsPolicy::Exact => [EtcTexels::Float, EtcTexels::Compact], + _ => [EtcTexels::Compact, EtcTexels::Float], + }; + order + .into_iter() + .find(|&texels| takes(texels)) + .ok_or_else(|| { + Error::Unsupported(Unsupported::needs( + Feature::Format, + Capability::Format { + format: decode.texel_format(order[0]), + usage: FormatUsage::SampledImageFilterLinear, + }, + )) + }) + } + /// `image`, a new texture's image of `layout` made with `descriptor`, its own for good, with /// its decoded twin where the texture takes one (the module docs), announced /// (`decoded-block-twin`); without one, `compressed-texel-decode` where the device's decode @@ -210,23 +555,37 @@ impl Device { descriptor: &TextureDescriptor, fresh: bool, ) -> Result { - let Some(decode) = self.twin_decode(layout) else { - self.degrade_block_decode(layout); - return Ok(image); + // An ASTC, PVRTC, ETC2, EAC or 4:2:2 carrier's texels are read through its twin alone + // (`astc.rs`, `pvrtc.rs`, `etc.rs`, `chroma_pairs.rs`). + let plan = image.plan(); + let carried = if let Some(decode) = astc::decode_of(plan) { + Some(TwinDecode::Astc(decode, self.astc_texels(decode)?)) + } else if let Some(decode) = etc::decode_of(plan) { + Some(TwinDecode::Etc(decode, self.etc_texels(decode)?)) + } else { + (pvrtc::decode_of(plan).map(TwinDecode::Pvrtc)) + .or_else(|| chroma_pairs::decode_of(plan).map(TwinDecode::Chroma)) + }; + let decode = match carried { + Some(decode) => decode, + None => match self.twin_decode(layout) { + Some(decode) => TwinDecode::Block(decode), + None => { + self.degrade_block_decode(layout); + return Ok(image); + } + }, }; // A twin starts, and takes the CPU's decodes, as the BC image's CPU copies go: on the // host or the staging queue where they do (then made as a `Shared` or `Managed` // texture's image is), else through submissions. let routed = image.host_copies || image.staging_copies; - let plan = twin_plan(image.plan(), decode, routed); + let plan = twin_plan(image.plan(), layout, decode, routed); let facts = self .shared() .textures .facts(self.compile_device().profile()); - let needs = FormatFeatureFlags2::SAMPLED_IMAGE - | FormatFeatureFlags2::SAMPLED_IMAGE_FILTER_LINEAR - | FormatFeatureFlags2::TRANSFER_DST; - if !facts.optimal(plan.format).contains(needs) { + if !facts.optimal(plan.format).contains(TWIN_FEATURES) { self.degrade_block_decode(layout); return Ok(image); } @@ -256,14 +615,12 @@ impl Device { image.host_copies = false; image.staging_copies = false; } - // A new BC1 texture's zero blocks are three-color blocks of black, alpha 1; every other - // format's decode to zero, which the twin's first move writes. - if fresh && decode == BlockDecode::Bc1 && !routed { + // A new texture's zero blocks: BC1's three-color blocks of black, alpha 1, an ASTC + // texture's error blocks of magenta, a 4:2:2 texture's opaque black; every other format's + // decode to zero, which the twin's first move writes. + if let Some(color) = zero_clear(decode).filter(|_| fresh && !routed) { let plan = twin.plan(); - let black = vk::ClearColorValue { - float32: [0.0, 0.0, 0.0, 1.0], - }; - let patterned = Patterned::new(Pattern::Color(black), plan.levels, plan.levels); + let patterned = Patterned::new(Pattern::Color(color), plan.levels, plan.levels); let first = FirstMove::new( twin.raw.get(), plan.format, @@ -276,8 +633,12 @@ impl Device { image: twin, decode, started_on_the_cpu: routed && fresh, + made_for: (*layout, *descriptor), }; - self.degrade_decoded_twin(layout, &decoded, placed(&image)); + match carried { + Some(_) => self.degrade_carried_twin(layout, &decoded, placed(&image)), + None => self.degrade_decoded_twin(layout, &decoded, placed(&image)), + } image.decoded = Some(Box::new(decoded)); Ok(image) } @@ -310,10 +671,62 @@ impl Device { } } +impl Device { + /// Announce, for an ASTC, PVRTC, ETC2 or EAC texture of `layout` made with `decoded`: + /// `carried-decoded-twin`, its cost (the twin's texels' bytes and memory beside its blocks' + /// carrier), and where an ASTC LDR texture's twin holds 8-bit codes or an 11-bit EAC + /// texture's 16-bit ones, `decoded-texel-precision` (a PVRTC texture's codes are exact, and so + /// are an ASTC sRGB texture's, an 8-bit ETC2 or EAC texture's and a 4:2:2 texture's). + fn degrade_carried_twin(&self, layout: &TextureLayout, decoded: &Decoded, image: Option) { + let [width, height, depth] = layout.extent; + let object = || { + format!( + "a {:?} {:?} texture of {width}x{height}x{depth}", + layout.pixel_format, layout.texture_type + ) + }; + self.degrade(Degradation::CarriedDecodedTwin, || { + let (texels, blocks) = decoded.bytes(); + let placed = + |bytes: Option| bytes.map_or_else(String::new, |n| format!(", {n} placed")); + let held = match decoded.decode { + TwinDecode::Chroma(_) => "Vulkan's 4:2:2 formats reconstruct chroma by the \ + implementation's rules" + .to_owned(), + _ => format!("the device has no {:?} format", layout.pixel_format), + }; + let why = format!( + "{held}: its blocks ({blocks} bytes) lie in a carrier image{}, which copies \ + move, and its samples read a decoded twin of {texels} bytes of {:?} texels{}, \ + decoded after each write into it", + placed(image), + decoded.decode.texel_format(), + placed(decoded.placed()), + ); + (object(), why) + }); + let why = match decoded.decode { + TwinDecode::Astc(decode, AstcTexels::Unorm8) if !decode.srgb => { + "its decoded twin holds each channel as the 8-bit code nearest Metal's 12-bit \ + value, at most 1/510 off it" + } + TwinDecode::Etc(decode, EtcTexels::Compact) if decode.eleven_bit() => { + "its decoded twin holds each channel as the 16-bit normalized code nearest \ + Metal's 11-bit value, at most half a 16-bit step off it" + } + _ => return, + }; + self.degrade(Degradation::DecodedTexelPrecision, || { + (object(), why.to_owned()) + }); + } +} + impl Texture { /// The `VkImageView` of `desc` (a sampled view; `call`'s) of the texture's decoded twin, where - /// its image (`image`) has one and the texture's format decodes as the twin's (the module - /// docs): made at its first bind, then kept with the twin. `None` elsewhere (an image with + /// its image (`image`) has one whose decode the texture's format takes (the module docs; an + /// ASTC carrier's second twin for a view in the texture's other colour space): made at its + /// first bind, then kept with the twin. `None` elsewhere (an image with /// one presents no stand-in: its detach is refused, `stand_in.rs`). pub(super) fn decoded_view( &self, @@ -321,11 +734,10 @@ impl Texture { image: &Image, desc: &ImageViewDesc, ) -> Result, Error> { - let Some(decoded) = image.decoded.as_deref() else { + let Some(decoded) = image.twin_of(self.0.record.pixel_format) else { return Ok(None); }; - let same = BlockDecode::of(self.0.record.pixel_format) == Some(decoded.decode); - let Some(format) = decoded.view_format(desc.format).filter(|_| same) else { + let Some(format) = decoded.view_format(desc.format) else { return Ok(None); }; let mut twin = *desc; @@ -346,18 +758,19 @@ impl Texture { if view_shadow::truth(image).decoded.is_none() { return; } - let decode = BlockDecode::of(record.pixel_format); - if image - .decoded - .as_ref() - .is_some_and(|d| Some(d.decode) == decode) - { + if image.twin_of(record.pixel_format).is_some() { return; } let device = self.device(); device.degrade_device_decode(record.pixel_format, record.texture_type, record.extent()); } + /// Whether the texture's texels are held in an image with a decoded twin + /// ([`decoding_image`](Self::decoding_image)). + pub(crate) fn has_decoded_twin(&self) -> bool { + self.decoding_image().is_some() + } + /// The image the texture's texels are held in where it has a decoded twin: its image, or a /// shadowed view's texture's (`view_shadow.rs`), whose twin a write through the view decodes /// into once its copy back is made. `None` for a texture without one. @@ -401,8 +814,9 @@ impl Texture { /// The texel every texel of a zero block decodes to, as `decode` writes it: `None` where they /// differ (no format so far), when the zero blocks are decoded instead. -fn zero_texel(decode: BlockDecode) -> Option> { - let texels = decode.decode(&vec![0; decode.block_bytes() as usize], [4, 4, 1]); +fn zero_texel(decode: TwinDecode) -> Option> { + let [bw, bh] = decode.block_extent(); + let texels = decode.decode(&vec![0; decode.block_bytes() as usize], [bw, bh, 1]); let size = decode.texel_bytes() as usize; let first = texels.get(..size)?; texels @@ -411,6 +825,43 @@ fn zero_texel(decode: BlockDecode) -> Option> { .then(|| first.to_vec()) } +/// The clear color of a twin whose zero blocks decode to texels other than zeros: BC1's opaque +/// black, an ASTC texture's magenta (an error block), an ETC2 texture's grey of codes 2, an EAC +/// 11-bit texture's value of 1 (signed -3) or its compact code; `None` where they decode to +/// zeros, which a new image's first move writes. The clear converts each value back to the code +/// it came from: a normalized code over its largest is within half a step of it. +fn zero_clear(decode: TwinDecode) -> Option { + let texel = zero_texel(decode)?; + if texel.iter().all(|&byte| byte == 0) { + return None; + } + let mut float32 = [0.0; 4]; + match decode.texel_format() { + Format::R8G8B8A8_UNORM => { + for (value, &code) in float32.iter_mut().zip(&texel) { + *value = f32::from(code) / 255.0; + } + } + Format::R32G32B32A32_SFLOAT | Format::R32G32_SFLOAT | Format::R32_SFLOAT => { + for (value, bytes) in float32.iter_mut().zip(texel.as_chunks::<4>().0) { + *value = f32::from_le_bytes(*bytes); + } + } + Format::R16_UNORM | Format::R16G16_UNORM => { + for (value, bytes) in float32.iter_mut().zip(texel.as_chunks::<2>().0) { + *value = f32::from(u16::from_le_bytes(*bytes)) / 65535.0; + } + } + Format::R16_SNORM | Format::R16G16_SNORM => { + for (value, bytes) in float32.iter_mut().zip(texel.as_chunks::<2>().0) { + *value = (f32::from(i16::from_le_bytes(*bytes)) / 32767.0).max(-1.0); + } + } + _ => return None, + } + Some(vk::ClearColorValue { float32 }) +} + /// The copies of `band`'s texels, laid out tight in rows of `row` bytes, in parts of whole block /// rows of at least `twin_decode::ROWS_PER_PART` texel rows, at most `twin_decode::THREADS`, each /// reading its rows at its offset: disjoint texels, which host copies may write at once. @@ -497,7 +948,10 @@ impl Image { /// copies stand when it runs, as Metal's unsynchronized CPU write leaves the ordering to the /// program. Always on the CPU: a decode staged for the GPU could run while a later write's CPU /// decode copies into the twin, read the old blocks before it and write their texels after it - /// (lavapipe under a lane's load, master `7d426aff`). Nothing for an image without a twin. + /// (lavapipe under a lane's load, master `7d426aff`). An ASTC carrier's second twin's decode + /// goes to the device's next batch ([`queue_second_decode`](Self::queue_second_decode)). + /// A 4:2:2 carrier's write of part of its rows decodes the whole rows as the image then holds + /// them ([`written_rows`](Self::written_rows)). Nothing for an image without a twin. pub(super) fn decode_written( self: &Arc, region: &ImageRegion, @@ -507,7 +961,9 @@ impl Image { return Ok(()); }; let host = decoded.image.takes_host_copies(); - self.queue_twin_decode(region, Some(packed))?; + let (region, packed) = self.written_rows(decoded, region, packed)?; + self.queue_twin_decode(®ion, Some(packed))?; + self.queue_second_decode(std::slice::from_ref(®ion))?; let device = &self.device; let object = || { let plan = self.plan(); @@ -532,6 +988,41 @@ impl Image { Ok(()) } + /// `region` and its blocks `packed`, a host call's write into the image, as its twin's decode + /// reads them: for a decode of whole rows ([`TwinDecode::whole_rows`], a 4:2:2 carrier's) of a + /// region short of its rows, the rows' region and their bytes as the image holds them after + /// the write, read back on the host or the staging queue as the write went (the caller waits + /// for that read); else themselves. + fn written_rows( + &self, + decoded: &Decoded, + region: &ImageRegion, + packed: Vec, + ) -> Result<(ImageRegion, Vec), Error> { + let rows = self.twin_region(decoded, region); + if !decoded.decode.whole_rows() || rows == *region { + return Ok((*region, packed)); + } + let decode = decoded.decode; + let [bw, bh] = decode.block_extent(); + let [width, height, depth] = rows.size.map(|axis| axis as usize); + let image = width.div_ceil(bw as usize) + * height.div_ceil(bh as usize) + * decode.block_bytes() as usize; + let mut bytes = vec![0; image * depth * rows.layers as usize]; + let copy = buffer_image_copy(&rows); + let read = match self.takes_host_copies() { + true => self.host_read(copy, &mut bytes)?, + false => self.staging_read(copy, &mut bytes)?, + }; + if !read { + return Err(internal( + "a 4:2:2 texture's rows that took no CPU copy its write took", + )); + } + Ok((rows, bytes)) + } + /// Queue the decode of `region` into the image's twin for the device's decode thread /// (`blocks`, the written blocks; `None`, a new texture's zero blocks): the scheduler holds /// each batch that may read the texture until it finished (every batch, where the texture is @@ -631,22 +1122,32 @@ impl Image { let decode = decoded.decode; let block = decode.block_bytes() as usize; let texel = decode.texel_bytes() as usize; + // The twin's region: a carrier's region in the texture's texels (a PVRTC one's whole + // levels, a 4:2:2 one's whole rows, whose blocks `decode_written` read). + let region = &self.twin_region(decoded, region); + let [bw, bh] = decode.block_extent(); let [width, height, depth] = region.size; - let (across, down) = (width.div_ceil(4) as usize, height.div_ceil(4) as usize); - // Block rows a band, each 4 texel rows of `width`. - let rows = (twin_decode::BAND_BYTES / (4 * width as usize * texel)).max(1); + let image_blocks = width.div_ceil(bw) as usize * height.div_ceil(bh) as usize * block; + // Texel rows a band, of `width` texels: whole block rows, but for a whole-level decode, + // each of whose bands reads all its image's blocks. + let fit = u32::try_from(twin_decode::BAND_BYTES / (width as usize * texel)) + .unwrap_or(u32::MAX) + .max(1); + let rows = match decode.whole_levels() { + true => fit, + false => (fit / bh).max(1) * bh, + }; let fill = blocks.is_none().then(|| zero_texel(decode)); for image in 0..depth * region.layers { - for first in (0..down).step_by(rows) { - let count = rows.min(down - first); - let y = first as u32 * 4; - let h = (count as u32 * 4).min(height - y); + for y in (0..height).step_by(rows as usize) { + let h = rows.min(height - y); let mut texels = vec![0; width as usize * h as usize * texel]; match (blocks, &fill) { (Some(blocks), _) => { - let at = (image as usize * down + first) * across * block; - let band = &blocks[at..at + count * across * block]; - twin_decode::decode_band(decode, band, [width, h], &mut texels); + let at = image as usize * image_blocks; + let image = &blocks[at..at + image_blocks]; + let size = [width, height]; + twin_decode::decode_band(decode, image, size, [y, h], &mut texels); } (None, Some(Some(texel))) => { for out in texels.chunks_exact_mut(texel.len()) { @@ -654,8 +1155,9 @@ impl Image { } } (None, _) => { - let zeros = vec![0; count * across * block]; - twin_decode::decode_band(decode, &zeros, [width, h], &mut texels); + let zeros = vec![0; image_blocks]; + let size = [width, height]; + twin_decode::decode_band(decode, &zeros, size, [y, h], &mut texels); } } let band = band_region(region, image, y, h); @@ -677,46 +1179,127 @@ impl Image { Ok(host) } - /// The pass that decodes `regions` (of the image's levels and layers) of the image into its - /// decoded twin (the module docs), its scratch (as `scratch` says) and sets made; `None` for an - /// image without one, or regions of no texel. + /// The twin's region of `region` of the image: a PVRTC carrier's whole levels of the + /// region's images, whose texels each write changes around it ([`TwinDecode::whole_levels`]); + /// a 4:2:2 carrier's whole rows of the region ([`TwinDecode::whole_rows`]); an ASTC carrier's + /// region in the texture's texels (`astc::texture_region`); any other image's itself. + fn twin_region(&self, decoded: &Decoded, region: &ImageRegion) -> ImageRegion { + let extent = decoded.image.plan().extent; + let level = |axis: usize| (extent[axis] >> region.level.min(31)).max(1); + if decoded.decode.whole_levels() { + return ImageRegion { + origin: [0, 0, region.origin[2]], + size: [level(0), level(1), region.size[2]], + ..*region + }; + } + if decoded.decode.whole_rows() { + return ImageRegion { + origin: [0, region.origin[1], region.origin[2]], + size: [level(0), region.size[1], region.size[2]], + ..*region + }; + } + astc::texture_region(self.plan(), extent, *region).unwrap_or(*region) + } + + /// The plan of the step of a decode pass that decodes `band` (of the twin's texels, one of + /// [`bands`]): the image's region its blocks are copied out of and their bytes, its shape and + /// its workgroups. A PVRTC band's blocks are its images' whole levels' (`pvrtc::image_region` + /// of them), its shape `PvrtcDecode::shape`; any other band's blocks lie over it (an ASTC + /// carrier's region over it, `astc::image_region`). + fn band_plan(&self, decode: TwinDecode, band: &ImageRegion) -> BandPlan { + let [w, h, _] = band.size; + let images = band.size[2] * band.layers; + let local = BlockDecodeModule::LOCAL_SIZE; + let groups = [w.div_ceil(local), h.div_ceil(local), images]; + if let TwinDecode::Pvrtc(pvrtc) = decode { + let height = (self.decoded_extent(1) >> band.level.min(31)).max(1); + let whole = ImageRegion { + origin: [0, 0, band.origin[2]], + size: [w, height, band.size[2]], + ..*band + }; + return BandPlan { + blocks: pvrtc::image_region(self.plan(), whole), + block_bytes: (pvrtc.level_bytes([w, height]) * images as usize) as u64, + shape: PvrtcDecode::shape([w, height], [band.origin[1], h], images), + groups, + }; + } + let [bw, bh] = decode.block_extent(); + let blocks = u64::from(w.div_ceil(bw)) * u64::from(h.div_ceil(bh)) * u64::from(images); + BandPlan { + blocks: astc::image_region(self.plan(), *band).unwrap_or(*band), + block_bytes: blocks * u64::from(decode.block_bytes()), + shape: BlockDecodeModule::shape([w, h, images]), + groups, + } + } + + /// The decoded twin's level-0 extent along `axis` (the texture's), 1 for an image without one. + fn decoded_extent(&self, axis: usize) -> u32 { + self.decoded + .as_deref() + .map_or(1, |decoded| decoded.image.plan().extent[axis]) + } + + /// The pass that decodes `regions` (of the image's levels and layers, in its texels: a + /// carrier's) of the image into its decoded twin (the module docs), its scratch (as `scratch` + /// says) and sets made; `None` for an image without one, or regions of no texel. Its steps are + /// bands of the twin's regions (a carrier's in the texture's texels, a PVRTC one's whole + /// levels, `twin_region`), each band's blocks copied out of the image's region over them (a + /// PVRTC band's, its images' whole levels; [`band_plan`](Self::band_plan)). pub(super) fn decode_pass( &self, regions: &[ImageRegion], scratch: PassScratch, ) -> Result, Error> { - let Some(decoded) = self.decoded.as_deref() else { - return Ok(None); - }; + match self.decoded.as_deref() { + Some(decoded) => self.decode_pass_into(decoded, regions, scratch), + None => Ok(None), + } + } + + /// [`decode_pass`](Self::decode_pass) into `decoded`, one of the image's twins. + fn decode_pass_into( + &self, + decoded: &Decoded, + regions: &[ImageRegion], + scratch: PassScratch, + ) -> Result, Error> { let decode = decoded.decode; let device = &self.device; let limits = &device.properties().description.limits; let align = limits.min_storage_buffer_offset_alignment.max(16); let most = u64::from(limits.max_storage_buffer_range).min(BAND_BYTES); let texel = u64::from(decode.texel_bytes()); - let block = u64::from(decode.block_bytes()); - let steps: Vec = regions - .iter() - .flat_map(|region| bands(region, texel, block, most)) + // A whole-level decode's regions of one level and its images are one region. + let mut twins: Vec = (regions.iter()) + .map(|region| self.twin_region(decoded, region)) + .collect(); + twins.dedup(); + let steps: Vec = (twins.iter()) + .flat_map(|region| bands(region, decode, most)) .collect(); if steps.is_empty() { return Ok(None); } - let images = |r: &ImageRegion| u64::from(r.size[2]) * u64::from(r.layers); - let blocks_of = |r: &ImageRegion| { - let [w, h, _] = r.size.map(u64::from); - w.div_ceil(4) * h.div_ceil(4) * images(r) * u64::from(decode.block_bytes()) - }; + // A step's texels in whole words: an `R11` format's compact texels are 2 bytes, two to + // a word, which the kernel writes whole (`bind::etc_decode_module`). let texels_of = |r: &ImageRegion| { let [w, h, _] = r.size.map(u64::from); - w * h * images(r) * texel + (w * h * u64::from(r.size[2]) * u64::from(r.layers) * texel).next_multiple_of(4) }; + let plans: Vec = steps + .iter() + .map(|step| self.band_plan(decode, step)) + .collect(); // Each step's blocks at the scratch's start and its texels at the alignment after them: // at most `most` bytes together (`bands`), so within `most` and the alignment. - let layouts: Vec<(u64, u64, u64)> = steps - .iter() - .map(|step| { - let blocks = blocks_of(step); + let layouts: Vec<(u64, u64, u64)> = (steps.iter().zip(&plans)) + .map(|(step, plan)| { + let blocks = plan.block_bytes; (blocks, blocks.div_ceil(align) * align, texels_of(step)) }) .collect(); @@ -751,21 +1334,15 @@ impl Image { } let contents = (shapes.contents()) .ok_or_else(|| internal("a Shared block decode shapes' buffer without contents"))?; - let mut groups = Vec::with_capacity(steps.len()); - for (at, step) in steps.iter().enumerate() { - let [w, h, _] = step.size; - let d = step.size[2] * step.layers; - let shape = BlockDecodeModule::shape([w, h, d]); + for (at, plan) in plans.iter().enumerate() { // SAFETY: the shapes' buffer holds `steps.len()` slots of `slot` bytes, each at least // a shape's, in host-coherent memory nothing else uses yet. unsafe { let to = contents.as_ptr().add(at * slot as usize); - std::ptr::copy_nonoverlapping(shape.as_ptr(), to, shape.len()); + std::ptr::copy_nonoverlapping(plan.shape.as_ptr(), to, plan.shape.len()); } - let local = BlockDecodeModule::LOCAL_SIZE; - groups.push([w.div_ceil(local), h.div_ceil(local), d]); } - let kernel = device.owned_kernel(OwnedModule::BlockDecode(decode))?; + let kernel = device.owned_kernel(OwnedModule::TwinDecode(decode))?; let ranges: Vec> = (layouts.iter()) .zip(0u64..) .map(|(&(blocks, texels_at, texels), at)| { @@ -779,20 +1356,20 @@ impl Image { let sets = OwnedSets::write(device, &kernel, &ranges)?; let steps = steps .iter() + .zip(&plans) .zip(&layouts) .zip(&sets.sets) - .zip(groups) - .map(|(((region, &(_, texels_at, _)), &set), groups)| Step { + .map(|(((region, plan), &(_, texels_at, _)), &set)| Step { blocks: vk::BufferImageCopy { buffer_offset: base, - ..buffer_image_copy(region) + ..buffer_image_copy(&plan.blocks) }, texels: vk::BufferImageCopy { buffer_offset: base + texels_at, ..buffer_image_copy(region) }, set, - groups, + groups: plan.groups, }) .collect(); device.shared().counts.block_decode_pass(); @@ -812,6 +1389,114 @@ impl Image { })) } + /// The image's decoded twin that decodes a texture of `pf` (its first, or an ASTC carrier's + /// second): `None` where neither does. + fn twin_of(&self, pf: PixelFormat) -> Option<&Decoded> { + (self.decoded.as_deref().into_iter()) + .chain(self.second.get().map(Box::as_ref)) + .find(|decoded| decoded.decode.decodes(pf)) + } + + /// Make the image's second decoded twin, an ASTC carrier's, for a view of the texture as `pf` + /// (its other colour space; the module docs), where it has none: + /// moved by the device's next submission, its texels the carrier's whole decode, which the + /// device's next batch with work records before that work ([`Device::take_second_decodes`]). + /// Refused (`Feature::TextureView`, not implemented) where the device takes no twin of the + /// decode's texels. + pub(super) fn make_second_twin(self: &Arc, pf: PixelFormat) -> Result<(), Error> { + if self.second.get().is_some() { + return Ok(()); + } + // A carrier without a twin (the device takes none of its texels) reads none either way. + let (Some(first), Some(decode)) = (self.decoded.as_deref(), AstcDecode::of(pf)) else { + return Ok(()); + }; + let device = &self.device; + let (layout, descriptor) = first.made_for; + let decode = TwinDecode::Astc(decode, device.astc_texels(decode)?); + let plan = twin_plan(self.plan(), &layout, decode, false); + let facts = (device.shared().textures).facts(device.compile_device().profile()); + if !facts.optimal(plan.format).contains(TWIN_FEATURES) { + return Err(Error::Unsupported(Unsupported::not_implemented( + Feature::TextureView, + ))); + } + // The kernel that keeps it in step, made now rather than by a submission. + device.owned_kernel(OwnedModule::TwinDecode(decode))?; + // Its uses are the image's, as the first twin's; it takes no CPU copy, so only the GPU + // writes it, in submission order. + let mut own = descriptor; + own.resource_options = ResourceOptions::private(); + let identity = Identity::new(HazardTrackingMode::Default, false); + let start = Start::Moved; + let twin = device.new_image_starting( + plan, + &layout, + &own, + identity, + start, + Device::runtime_owner, + )?; + let second = Decoded { + image: twin, + decode, + started_on_the_cpu: false, + made_for: (layout, own), + }; + let mut viewed = layout; + viewed.pixel_format = pf; + device.degrade_carried_twin(&viewed, &second, None); + // Made for another view meanwhile: that one stands, and this one goes unused. + if self.second.set(Box::new(second)).is_err() { + return Ok(()); + } + device.shared().counts.second_twin(); + self.register_first_move(); + self.queue_second_decode(&whole_regions(self.plan())) + } + + /// Queue the decode of `regions` (of the image's levels and layers, in its texels: a + /// carrier's) into its second decoded twin, where it has one, for the device's next batch with + /// work ([`Device::take_second_decodes`]): its pass made now, by the calling thread. After a + /// host call wrote the regions, or as the twin is made. + pub(super) fn queue_second_decode( + self: &Arc, + regions: &[ImageRegion], + ) -> Result<(), Error> { + let Some(SecondDecode { pass, uses, .. }) = self.second_decode(regions)? else { + return Ok(()); + }; + // Held weakly: an image gone takes its queued decodes with it. + let queued = QueuedDecode { + image: Arc::downgrade(self), + key: self.identity.key, + pass, + uses, + }; + lock(&self.device.shared().textures.second_decodes).push(queued); + Ok(()) + } + + /// The decode of `regions` (as for [`queue_second_decode`](Self::queue_second_decode)) into + /// the image's second decoded twin, for a batch to record: `None` for an image without one, + /// or regions of no texel. + fn second_decode( + self: &Arc, + regions: &[ImageRegion], + ) -> Result, Error> { + let Some(second) = self.second.get() else { + return Ok(None); + }; + let Some(pass) = self.decode_pass_into(second, regions, PassScratch::Own)? else { + return Ok(None); + }; + Ok(Some(SecondDecode { + pass, + uses: self.decode_uses(regions), + _image: Arc::clone(self), + })) + } + /// The uses of a command that decodes `regions` of the image into its twin: a write of each /// (the twin shares the image's resource identity), as a copy reads and writes. fn decode_uses(&self, regions: &[ImageRegion]) -> Vec> { @@ -838,18 +1523,24 @@ impl Image { } } -/// `region` (of texels of `texel` bytes, in blocks of `block` bytes of 4 x 4 texels) in steps -/// whose blocks and texels take at most `most` bytes together (before, its texels alone): whole, -/// else runs of its images (layers or depth slices), else each image in bands of whole block rows. -/// A block row past `most` (16384 texels of 16 bytes and their blocks are 1 MiB and 64 KiB) is a -/// step alone. -pub(crate) fn bands(region: &ImageRegion, texel: u64, block: u64, most: u64) -> Vec { +/// `region` (of the twin's texels, in `decode`'s blocks) in steps whose blocks and texels take at +/// most `most` bytes together (before, its texels alone): whole, else runs of its images (layers +/// or depth slices), else each image in bands of whole block rows (of a whole-level decode's +/// region, bands of rows beside all the image's blocks, [`TwinDecode::whole_levels`]). A block +/// row past `most` (16384 texels of 16 bytes and their blocks are 1 MiB and 64 KiB) is a step +/// alone. +pub(crate) fn bands(region: &ImageRegion, decode: TwinDecode, most: u64) -> Vec { + let (texel, block) = ( + u64::from(decode.texel_bytes()), + u64::from(decode.block_bytes()), + ); + let [bw, bh] = decode.block_extent(); let [w, h, d] = region.size; let count = u64::from(d) * u64::from(region.layers); - let across = u64::from(w).div_ceil(4); - // A row of blocks and its four rows of texels. - let row = across * block + 4 * u64::from(w) * texel; - let image = across * u64::from(h).div_ceil(4) * block + u64::from(w) * u64::from(h) * texel; + let across = u64::from(w).div_ceil(bw.into()); + // A row of blocks and its rows of texels. + let row = across * block + u64::from(bh) * u64::from(w) * texel; + let image = across * u64::from(h.div_ceil(bh)) * block + u64::from(w) * u64::from(h) * texel; if count == 0 || w == 0 || h == 0 { return Vec::new(); } @@ -879,7 +1570,16 @@ pub(crate) fn bands(region: &ImageRegion, texel: u64, block: u64, most: u64) -> .map(|i| images(i, per.min(total - i))) .collect(); } - let rows = u32::try_from((most / row).max(1) * 4).unwrap_or(u32::MAX); + // Rows a band: whole block rows, but for a whole-level decode, each of whose bands reads all + // its image's blocks. + let rows = match decode.whole_levels() { + true => { + let blocks = image - u64::from(w) * u64::from(h) * texel; + most.saturating_sub(blocks) / (u64::from(w) * texel) + } + false => (most / row).max(1) * u64::from(bh), + }; + let rows = u32::try_from(rows.max(1)).unwrap_or(u32::MAX); (0..total) .flat_map(|i| { let one = images(i, 1); @@ -893,8 +1593,17 @@ pub(crate) fn bands(region: &ImageRegion, texel: u64, block: u64, most: u64) -> .collect() } -/// One band of a decode pass: its blocks copied out of the BC image, its set, its workgroups and -/// its texels copied into the twin. +/// The plan of one band of a decode pass ([`Image::band_plan`]): the image's region its blocks +/// are copied out of and their bytes, its shape and its workgroups. +struct BandPlan { + blocks: ImageRegion, + block_bytes: u64, + shape: [u8; BlockDecodeModule::SHAPE_WORDS as usize * 4], + groups: [u32; 3], +} + +/// One band of a decode pass: its blocks copied out of the image, its set, its workgroups and its +/// texels copied into the twin. struct Step { blocks: vk::BufferImageCopy, texels: vk::BufferImageCopy, @@ -910,6 +1619,105 @@ struct Held { _sets: OwnedSets, } +/// A decode into an ASTC carrier's second decoded twin (the module docs) that a batch records +/// (`command_buffer/submit.rs`): its pass and its uses, and the image, held until the batch +/// completed. +pub(crate) struct SecondDecode { + pass: DecodePass, + uses: Vec>, + _image: Arc, +} + +impl SecondDecode { + /// The uses of its command (the image's, `Image::decode_uses`). + pub(crate) fn uses(&self) -> &[Use] { + &self.uses + } + + /// Record it ([`DecodePass::record`]). + /// + /// # Safety + /// + /// `raw` is recording, outside a render pass, on a queue family with compute; the decode lives + /// until it completes. + pub(crate) unsafe fn record(&self, device: &Vk, raw: vk::CommandBuffer) { + // SAFETY: the caller's contract; the decode holds the image and its twin, both in the + // `GENERAL` layout (the twin moved by a submission no later than the one that records + // this, `Image::make_second_twin`). + unsafe { self.pass.record(device, raw) } + } +} + +/// A blit encoder's write into an ASTC carrier's blocks (`BlitCommandEncoder::decode_twin`), +/// which its batch's submission decodes into the image's second decoded twin: by the decode made +/// as the command was encoded, where the image had a second twin then. Without one, the decodes +/// queued for the image wait past the batch ([`Device::take_second_decodes`]): a second twin made +/// since reads the carrier as the batch leaves it. +pub(crate) struct TwinWrite { + key: ResourceKey, + decode: Option, +} + +impl TwinWrite { + /// The image's resource key, where the write made no decode. + pub(crate) fn without_decode(&self) -> Option { + self.decode.is_none().then_some(self.key) + } + + /// Its decode, where it made one. + pub(crate) fn into_decode(self) -> Option { + self.decode + } +} + +/// A decode queued for an image's second decoded twin ([`Image::queue_second_decode`]): the +/// image, held weakly, its key, and the decode's pass and uses. +pub(crate) struct QueuedDecode { + image: Weak, + key: ResourceKey, + pass: DecodePass, + uses: Vec>, +} + +/// The decodes queued for second decoded twins ([`Image::queue_second_decode`]), which the +/// device's next batch with work records before that work ([`Device::take_second_decodes`]). +pub(crate) type SecondDecodes = Mutex>; + +impl Device { + /// The decodes queued for second decoded twins (the module docs), taken for the batch now + /// submitted to record before its work, in the order they were queued, but those of an image + /// for which `held` answers true (a write of the batch's made no decode), which stay queued + /// for a later batch, and those of an image gone, dropped. + pub(crate) fn take_second_decodes( + &self, + held: impl Fn(ResourceKey) -> bool, + ) -> Vec { + let mut queued = lock(&self.shared().textures.second_decodes); + if queued.is_empty() { + return Vec::new(); + } + let (kept, taken): (Vec, Vec) = + queued.drain(..).partition(|decode| held(decode.key)); + queued.extend(kept); + drop(queued); + taken + .into_iter() + .filter_map( + |QueuedDecode { + image, pass, uses, .. + }| { + let image = image.upgrade()?; + Some(SecondDecode { + pass, + uses, + _image: image, + }) + }, + ) + .collect() + } +} + /// The scratch buffer a decode pass's bands go through ([`Image::decode_pass`]). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum PassScratch { @@ -982,9 +1790,9 @@ impl DecodePass { } impl BlitCommandEncoder { - /// After the encoder's last command wrote `regions` (of the image's levels and layers) of - /// `texture`'s texels: their decode into its decoded twin (the module docs), one command of - /// the encoder. Nothing for a texture without one. + /// After the encoder's last command wrote `regions` (of the texture's levels and layers, in + /// its texels) of `texture`'s texels: their decode into its decoded twin (the module docs), + /// one command of the encoder. Nothing for a texture without one. pub(crate) fn decode_twin( &mut self, texture: &Texture, @@ -993,10 +1801,15 @@ impl BlitCommandEncoder { let Some(image) = texture.decoding_image() else { return Ok(()); }; - let Some(pass) = image.decode_pass(regions, PassScratch::Own)? else { + // A carrier's regions: the carrier's texels over the texture's. + let regions: Vec = regions + .iter() + .map(|region| pvrtc::image_region(image.plan(), *region)) + .collect(); + let Some(pass) = image.decode_pass(®ions, PassScratch::Own)? else { return Ok(()); }; - let uses = image.decode_uses(regions); + let uses = image.decode_uses(®ions); let stages = TRANSFER | vk::PipelineStageFlags2::COMPUTE_SHADER; self.command_in(stages, &uses, |device, raw| { // SAFETY: the encoder's command buffer is recording, outside a render pass; the @@ -1005,6 +1818,13 @@ impl BlitCommandEncoder { unsafe { pass.record(device, raw) } })?; self.core().retain(pass.held); + // An ASTC carrier's write, for its batch's submission to decode into the image's second + // twin, by the decode made now where it has one (the module docs). + if matches!(image.decoded.as_deref(), Some(d) if matches!(d.decode, TwinDecode::Astc(..))) { + let decode = image.second_decode(®ions)?; + let key = image.identity.key; + self.core().wrote_twin(TwinWrite { key, decode }); + } self.core().retain(image); Ok(()) } diff --git a/crates/metal2vulkan-runtime/src/texture/heap.rs b/crates/metal2vulkan-runtime/src/texture/heap.rs index b6e0f8233..d12b105fa 100644 --- a/crates/metal2vulkan-runtime/src/texture/heap.rs +++ b/crates/metal2vulkan-runtime/src/texture/heap.rs @@ -1151,6 +1151,11 @@ impl Device { let usage = descriptor.image_usage(); let (plan, twin) = plan_texture_images(&layout, usage, false, &facts) .map_err(|refusal| image_error(call, refusal))?; + // A heap texture's samples read what its bytes hold, which an ASTC carrier's decoded twin + // would decode as it is placed (`astc.rs`): refused, its size query too. + if crate::astc::decode_of(&plan).is_some() { + return Err(Error::NotImplemented(RuntimeGap::DecodedHeapTexture)); + } // An image whose copies would rewrite texels a CPU copy keeps is made uncompressed; the // texture still takes the compressed image's bytes of the heap, as Metal's does. let (plan, twin, compressed) = @@ -2099,6 +2104,7 @@ impl Device { resolves: KeptResolves::new(), twin: None, decoded: None, + second: std::sync::OnceLock::new(), form: Default::default(), kept_outside: AtomicBool::new(false), signed_depth: AtomicBool::new(false), @@ -2139,6 +2145,7 @@ impl Device { resolves: KeptResolves::new(), twin: None, decoded: None, + second: std::sync::OnceLock::new(), form: Default::default(), kept_outside: AtomicBool::new(false), signed_depth: AtomicBool::new(false), diff --git a/crates/metal2vulkan-runtime/src/texture/twin_decode.rs b/crates/metal2vulkan-runtime/src/texture/twin_decode.rs index 4a1b0b205..53f0f6e34 100644 --- a/crates/metal2vulkan-runtime/src/texture/twin_decode.rs +++ b/crates/metal2vulkan-runtime/src/texture/twin_decode.rs @@ -8,7 +8,8 @@ //! **The thread.** One per device, started with its first job ([`TwinDecodes::start`]), takes //! the jobs in the order they were queued, so a later write's texels land in a twin after an //! earlier one's. Each job decodes its region in bands of at most [`BAND_BYTES`] of texels, each -//! band's block rows split over up to [`THREADS`] threads ([`decode_band`]), and copies each band +//! band's rows split over up to [`THREADS`] threads ([`decode_band`]; a PVRTC image's bands read +//! all of its blocks, `TwinDecode::whole_levels`), and copies each band //! into the twin as the twin's copies go (on the host, or on the staging queue, waited for). A //! new texture's start, the zero blocks' decode, is a constant fill there. //! @@ -29,8 +30,8 @@ use super::super::copy_plan::ImageRegion; use super::super::device::lock; use super::super::error::{Error, MemoryKind}; use super::super::exit_guard; +use super::decoded_twin::TwinDecode; use super::Image; -use metal2vulkan::bind::BlockDecode; use std::collections::VecDeque; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Condvar, Mutex, PoisonError}; @@ -213,43 +214,42 @@ fn run(shared: &Shared) { } } -/// Decode `blocks`, the block rows of a band `width` x `height` texels of one image, into -/// `texels` (exactly its texels), split over up to [`THREADS`] threads of at least -/// [`ROWS_PER_THREAD`] block rows each; this thread takes its share. A thread the host does not -/// start leaves its share to the others. +/// Decode rows `first` to `first + rows` of one image `width` x `height` texels, whose blocks +/// are `blocks` (all of the image's), into `texels` (exactly the rows' texels), split over up to +/// [`THREADS`] threads of at least [`ROWS_PER_THREAD`] block rows each (`TwinDecode::decode_rows`: +/// a block decode's shares start at a block row, as `first` does); this thread takes its share. A +/// thread the host does not start leaves its share to the others. pub(super) fn decode_band( - decode: BlockDecode, + decode: TwinDecode, blocks: &[u8], - [width, height]: [u32; 2], + size: [u32; 2], + [first, rows]: [u32; 2], texels: &mut [u8], ) { - let down = height.div_ceil(4) as usize; - let across = width.div_ceil(4) as usize; - let block = decode.block_bytes() as usize; - let row = width as usize * decode.texel_bytes() as usize; + let bh = decode.block_extent()[1]; + let row = size[0] as usize * decode.texel_bytes() as usize; let host = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get); + let down = rows.div_ceil(bh) as usize; let threads = host.min(THREADS).min(down / ROWS_PER_THREAD).max(1); if threads == 1 { - decode.decode_into(blocks, [width, height, 1], texels); + decode.decode_rows(blocks, size, [first, rows], texels); return; } - // Each share: its block rows' blocks, its texel rows' bytes, and its height. - let per = down.div_ceil(threads); + // Each share: its first row, its texel rows' bytes, and its rows, whole block rows. + let per = (down.div_ceil(threads) as u32) * bh; let mut shares = Vec::with_capacity(threads); let mut rest = texels; - for first in (0..down).step_by(per) { - let rows = per.min(down - first); - let h = (rows * 4).min(height as usize - first * 4); - let (mine, after) = rest.split_at_mut(h * row); + for at in (0..rows).step_by(per as usize) { + let h = per.min(rows - at); + let (mine, after) = rest.split_at_mut(h as usize * row); rest = after; - let span = first * across * block..(first + rows) * across * block; - shares.push(Mutex::new(Some((&blocks[span], mine, h as u32)))); + shares.push(Mutex::new(Some((first + at, mine, h)))); } let next = AtomicUsize::new(0); let work = || { while let Some(share) = shares.get(next.fetch_add(1, Ordering::Relaxed)) { - if let Some((blocks, texels, h)) = lock(share).take() { - decode.decode_into(blocks, [width, h, 1], texels); + if let Some((y, texels, h)) = lock(share).take() { + decode.decode_rows(blocks, size, [y, h], texels); } } }; diff --git a/crates/metal2vulkan-runtime/src/texture/wrapped.rs b/crates/metal2vulkan-runtime/src/texture/wrapped.rs index df1fceccc..ce0ffd303 100644 --- a/crates/metal2vulkan-runtime/src/texture/wrapped.rs +++ b/crates/metal2vulkan-runtime/src/texture/wrapped.rs @@ -620,6 +620,7 @@ impl Device { resolves: KeptResolves::new(), twin: None, decoded: None, + second: std::sync::OnceLock::new(), form: Default::default(), kept_outside: AtomicBool::new(false), signed_depth: AtomicBool::new(false), diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 717ce8946..3a16fb7e8 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -96,6 +96,9 @@ pub(crate) struct Counters { uncached_host_images: AtomicU64, cpu_block_decodes: AtomicU64, block_decode_passes: AtomicU64, + second_twins: AtomicU64, + second_twin_checks: AtomicU64, + second_twin_decodes: AtomicU64, queue_drains: AtomicU64, stand_in_copies_made: AtomicU64, stand_in_copies_made_at_draws: AtomicU64, @@ -577,6 +580,24 @@ impl Counters { self.block_decode_passes.fetch_add(1, Ordering::Relaxed); } + /// An ASTC carrier's second decoded twin was made (`Image::make_second_twin`). + pub(crate) fn second_twin(&self) { + self.second_twins.fetch_add(1, Ordering::Relaxed); + } + + /// A submission checked `n` blit writes into ASTC carriers for second twins' decodes + /// (`command_buffer/submit.rs`). + pub(crate) fn second_twin_checks(&self, n: usize) { + self.second_twin_checks + .fetch_add(n as u64, Ordering::Relaxed); + } + + /// A submission recorded `n` decodes into second decoded twins. + pub(crate) fn second_twin_decodes(&self, n: usize) { + self.second_twin_decodes + .fetch_add(n as u64, Ordering::Relaxed); + } + /// The device's queues were drained before a failed wait's command buffers let go of what /// they used (`Device::drain_queues`). pub(crate) fn queue_drain(&self) { @@ -1367,6 +1388,17 @@ pub struct WorkCounts { /// a blit's or a copy's into a BC texture, a heap texture's start, a write through /// submissions. None for a twin that takes CPU copies, whose texels only the CPU decodes. pub block_decode_passes: u64, + /// ASTC textures' second decoded twins made (`texture/decoded_twin.rs`): one at a texture's + /// first view in its other colour space (an `_sRGB` texture's as its LDR form, or the other + /// way), which reads Metal's decode of the blocks in that form. + pub second_twins: u64, + /// Blit commands' writes into an ASTC texture's blocks that a submission checked for a + /// second twin's decode: each such write, whether or not the texture had one. + pub second_twin_checks: u64, + /// Decodes into ASTC textures' second decoded twins that submissions recorded: a new twin's + /// whole decode, a host write's, and a blit write's where the texture had one as the write was + /// encoded. None where no texture has a second twin. + pub second_twin_decodes: u64, /// Drains of the device's queues: one each time a wait for command buffers' work failed (a /// lost device), before those command buffers let go of what they used, so that the /// driver's own completion of the work, which can still read their pools, has run @@ -1764,6 +1796,9 @@ impl Device { uncached_host_images: counters.uncached_host_images.load(Ordering::Relaxed), cpu_block_decodes: counters.cpu_block_decodes.load(Ordering::Relaxed), block_decode_passes: counters.block_decode_passes.load(Ordering::Relaxed), + second_twins: counters.second_twins.load(Ordering::Relaxed), + second_twin_checks: counters.second_twin_checks.load(Ordering::Relaxed), + second_twin_decodes: counters.second_twin_decodes.load(Ordering::Relaxed), queue_drains: counters.queue_drains.load(Ordering::Relaxed), stand_in_copies_made: counters.stand_in_copies_made.load(Ordering::Relaxed), stand_in_copies_made_at_draws: counters diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index 92d55dbb4..201cc05bd 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -223,6 +223,8 @@ mod argument_buffers; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod argument_linear_samples; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod astc_textures; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod attachment_reads; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod attachmentless; @@ -347,6 +349,8 @@ mod dynamic_libraries; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod escaped_slots; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod etc_textures; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod events; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod executions; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/astc_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/astc_textures.rs new file mode 100644 index 000000000..8c2d41638 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/astc_textures.rs @@ -0,0 +1,708 @@ +//! ASTC LDR textures on the device the cfg selects, under the validation layer, against Metal's +//! decode (`metal2vulkan::bind::AstcDecode`, matched bit for bit against an Apple M3 Max by its +//! own tests). +//! +//! On a device without a format's ASTC block ([`decodes_astc`]) the texture holds its blocks in a +//! carrier and its reads go through a decoded twin, announced `carried-decoded-twin` once and, under +//! `DecodedTexelsPolicy::Compact`, `decoded-texel-precision` once ([`ASTC_TWINS`]). Every format's +//! texels read as Metal's after every kind of write ([`astc_texels_read_as_metal_s`], and +//! [`astc_texels_read_exactly_as_metal_s_under_exact`]): exactly under `DecodedTexelsPolicy::Exact`, +//! within 1/510 under the default, an sRGB form's exactly under either (its twin's 8-bit codes read +//! raw and decoded through Metal's table); a new texture's zero blocks as magenta; then blocks a CPU copy +//! wrote, a blit from a buffer, a fill of one block, and a copy from another ASTC texture, each +//! read by a command buffer after the write's, each decoded into the twin by a GPU decode pass (a +//! blit's always; a CPU copy's where it goes through a submission, else on the CPU, counted in +//! `WorkCounts`). The blocks each wrote come back unchanged from +//! `get_bytes` and from a blit into a buffer. A device with the ASTC block reads through its own +//! decode (not compared), announcing neither kind. +//! +//! On every device, the blocks of every level and slice of a mipmapped array and cube whose sides +//! are no multiple of the block, written by blits from a buffer at the level's texel size (Metal's +//! `sourceSize` at a level's edge, `bytesPerImage` the row's bytes times the block rows), come back +//! bit for bit from blits into a buffer and from `get_bytes` +//! ([`astc_blocks_round_trip_at_every_level_and_slice`]). On a device without ASTC a view of a +//! texture in its other colour space reads Metal's texels of the view's form through a second +//! decoded twin, kept in step with CPU copies and blits, a blit encoded before the view included +//! ([`astc_views_in_the_other_colour_space_read_as_metal_s`]); a heap's texture and a view of +//! another decode are refused, and creation with `ShaderWrite` and `RenderTarget` usage is not +//! ([`astc_textures_the_runtime_does_not_hold_are_refused`]). + +use super::degrade_notices::{counts, on_device, on_device_with}; +use super::{buffer_with, read_buffer, WAIT}; +use crate::air_library::AirLibrary; +use metal2vulkan::bind::{AstcDecode, AstcTexels}; +use metal2vulkan::device::{DecodedTexelsPolicy, FormatUsage}; +use metal2vulkan::metal::format::{vk_format, FormatEmulation}; +use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; +use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; +use metal2vulkan_devtools::{engine_dir, llvm_assemble}; +use metal2vulkan_runtime::{ + BlitCommandEncoder, BlitOption, Buffer, CommandBufferStatus, ComputePipelineState, Degradation, + Device, DeviceOptions, Error, HeapDescriptor, HeapType, Origin, PipelineOptions, Region, + ResourceOptions, RuntimeGap, Size, Texture, TextureDescriptor, +}; + +/// The kinds an ASTC texture announces on a device without its ASTC block: the decoded twin, and +/// an LDR form's 8-bit codes under `DecodedTexelsPolicy::Compact`. +pub(super) const ASTC_TWINS: [Degradation; 2] = [ + Degradation::CarriedDecodedTwin, + Degradation::DecodedTexelPrecision, +]; + +/// Every ASTC LDR format, linear and sRGB. +const FORMATS: [PixelFormat; 28] = [ + PixelFormat::ASTC4x4LDR, + PixelFormat::ASTC5x4LDR, + PixelFormat::ASTC5x5LDR, + PixelFormat::ASTC6x5LDR, + PixelFormat::ASTC6x6LDR, + PixelFormat::ASTC8x5LDR, + PixelFormat::ASTC8x6LDR, + PixelFormat::ASTC8x8LDR, + PixelFormat::ASTC10x5LDR, + PixelFormat::ASTC10x6LDR, + PixelFormat::ASTC10x8LDR, + PixelFormat::ASTC10x10LDR, + PixelFormat::ASTC12x10LDR, + PixelFormat::ASTC12x12LDR, + PixelFormat::ASTC4x4SRGB, + PixelFormat::ASTC5x4SRGB, + PixelFormat::ASTC5x5SRGB, + PixelFormat::ASTC6x5SRGB, + PixelFormat::ASTC6x6SRGB, + PixelFormat::ASTC8x5SRGB, + PixelFormat::ASTC8x6SRGB, + PixelFormat::ASTC8x8SRGB, + PixelFormat::ASTC10x5SRGB, + PixelFormat::ASTC10x6SRGB, + PixelFormat::ASTC10x8SRGB, + PixelFormat::ASTC10x10SRGB, + PixelFormat::ASTC12x10SRGB, + PixelFormat::ASTC12x12SRGB, +]; + +/// The side, in texels, of every texture the lane reads. +const SIDE: u32 = 16; + +/// The most an 8-bit code is off Metal's value (`decoded-texel-precision`), with room for `f32`. +const UNORM8_BOUND: f32 = 1.0 / 510.0 + 1e-6; + +/// An LDR void-extent block of red, green, blue and alpha `0x4000`, `0x8000`, `0xc000` and +/// `0xffff`: every texel that color. +const VOID_EXTENT: [u8; 16] = [ + 0xfc, 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x40, 0x00, 0x80, 0x00, 0xc0, 0xff, 0xff, +]; + +/// Whether `device` holds a texture of `pf` in its ASTC block, decoding it its own way, rather +/// than in a carrier with a decoded twin. +pub(super) fn decodes_astc(device: &Device, pf: PixelFormat) -> bool { + let usage = [FormatUsage::SampledImage].into(); + let mapping = vk_format(pf, &usage, device.compile_device().profile()).unwrap(); + mapping.emulation != FormatEmulation::Decoded +} + +/// `count` 16-byte blocks of a seeded xorshift: random bits, of which most are error blocks and +/// the rest decode through every mode, every fourth an LDR void-extent block of a random color. +fn seeded_blocks(seed: u64, count: usize) -> Vec { + let mut state = seed | 1; + let mut next = move || { + state ^= state >> 12; + state ^= state << 25; + state ^= state >> 27; + state.wrapping_mul(0x2545_f491_4f6c_dd1d) + }; + let mut blocks = Vec::with_capacity(16 * count); + for index in 0..count { + let mut block = [0; 16]; + block[..8].copy_from_slice(&next().to_le_bytes()); + block[8..].copy_from_slice(&next().to_le_bytes()); + if index % 4 == 3 { + block[..8].copy_from_slice(&VOID_EXTENT[..8]); + } + blocks.extend_from_slice(&block); + } + blocks +} + +/// The format scout's `scout_read_f` on `device`. +pub(super) fn reader(device: &Device) -> ComputePipelineState { + let bitcode = llvm_assemble(&engine_dir().join("format_scout.ll")).unwrap(); + let library = device.new_library_with_air(&bitcode).unwrap(); + let function = library.new_function_with_name("scout_read_f").unwrap(); + device + .new_compute_pipeline_state( + &ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())), + &PipelineOptions::default(), + ) + .unwrap() +} + +/// `bytes` as `float4` texels. +fn texels_of(bytes: &[u8]) -> Vec<[f32; 4]> { + bytes + .as_chunks::<16>() + .0 + .iter() + .map(|t| { + std::array::from_fn(|c| f32::from_le_bytes(t[4 * c..4 * c + 4].try_into().unwrap())) + }) + .collect() +} + +/// The `float4` texels of `texture` (`SIDE` x `SIDE`) as `state` ([`reader`]) reads them, in one +/// command buffer, waited for. +pub(super) fn read_whole( + device: &Device, + state: &ComputePipelineState, + texture: &Texture, +) -> Vec<[f32; 4]> { + let texels = u64::from(SIDE * SIDE); + let out = buffer_with(device, &vec![0; 16 * texels as usize]).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_texture(Some(texture), 0).unwrap(); + encoder.set_buffer(Some(&out), 0, 0).unwrap(); + let side = u64::from(SIDE); + encoder + .dispatch_threads(Size::new(side, side, 1), Size::new(side, side, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + texels_of(&read_buffer(&out, 0, 16 * texels).unwrap()) +} + +/// One command buffer of blits `encode` encodes, committed and waited for. +pub(super) fn blit(device: &Device, encode: impl FnOnce(&mut BlitCommandEncoder)) { + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + encode(&mut encoder); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); +} + +/// A texture of `pf`, `Shared`, of `descriptor`'s shape, made with `usage`. +fn made(device: &Device, mut descriptor: TextureDescriptor, usage: TextureUsage) -> Texture { + descriptor.usage = usage; + descriptor.resource_options = ResourceOptions::shared(); + device.new_texture(&descriptor).unwrap() +} + +/// A `SIDE` x `SIDE` texture of `pf`, `Shared`, made with `usage`. +pub(super) fn texture(device: &Device, pf: PixelFormat, usage: TextureUsage) -> Texture { + let descriptor = TextureDescriptor::texture_2d(pf, SIDE.into(), SIDE.into(), false); + made(device, descriptor, usage) +} + +/// The blocks across and down a level of `width` x `height` texels of `decode`'s. +fn blocks_of(decode: AstcDecode, width: u64, height: u64) -> [u64; 2] { + let [bw, bh] = decode.block_extent().map(u64::from); + [width.div_ceil(bw), height.div_ceil(bh)] +} + +/// The bytes of a row of `decode`'s blocks across a `SIDE`-texel level. +fn row_bytes(decode: AstcDecode) -> u64 { + blocks_of(decode, SIDE.into(), SIDE.into())[0] * u64::from(AstcDecode::BLOCK_BYTES) +} + +/// The blocks of a `SIDE` x `SIDE` level of `decode`. +fn block_count(decode: AstcDecode) -> usize { + let [across, down] = blocks_of(decode, SIDE.into(), SIDE.into()); + (across * down) as usize +} + +/// Metal's texels of `blocks`, a `SIDE` x `SIDE` level of `decode`. +fn metal_texels(decode: AstcDecode, blocks: &[u8]) -> Vec<[f32; 4]> { + texels_of(&decode.decode(AstcTexels::Float, blocks, [SIDE, SIDE, 1])) +} + +/// A blit of `blocks` from a buffer into `level` and `slice` of `texture`, a level of `size` +/// texels, `row` bytes a row of blocks and `image` an image of them. +pub(super) fn upload( + device: &Device, + texture: &Texture, + (level, slice): (u64, u64), + size: Size, + (row, image): (u64, u64), + blocks: &[u8], +) { + let source = buffer_with(device, blocks).unwrap(); + blit(device, |encoder| { + encoder + .copy_from_buffer_to_texture( + &source, + 0, + row, + image, + size, + texture, + slice, + level, + Origin::new(0, 0, 0), + BlitOption::None, + ) + .unwrap(); + }); +} + +/// The blocks of `level` and `slice` of `texture`, a level of `size` texels, blitted into a +/// buffer `row` bytes a row of blocks and `image` an image of them: `length` bytes. +pub(super) fn download( + device: &Device, + texture: &Texture, + (level, slice): (u64, u64), + size: Size, + (row, image): (u64, u64), + length: u64, +) -> Vec { + let out: Buffer = buffer_with(device, &vec![0; length as usize]).unwrap(); + blit(device, |encoder| { + encoder + .copy_from_texture_to_buffer( + texture, + slice, + level, + Origin::new(0, 0, 0), + size, + &out, + 0, + row, + image, + BlitOption::None, + ) + .unwrap(); + }); + read_buffer(&out, 0, length).unwrap() +} + +/// Every ASTC LDR format's texels read as Metal's on a device without its block, under `policy` +/// (the module docs): a new texture's, then after a CPU copy, a blit from a buffer, a fill and a +/// copy from another texture, the blocks of each coming back unchanged. +fn astc_texels_under(policy: DecodedTexelsPolicy) { + let adjust = |options: &mut DeviceOptions| options.policy.decoded_texels = policy; + on_device_with(adjust, |device, messages| { + let name = device.name().to_owned(); + let state = reader(device); + let mut wrong = Vec::new(); + let mut undecoded = Vec::new(); + let mut twinned = false; + // The GPU decode passes and CPU decodes so far. + let decodes = |device: &Device| { + let counts = device.work_counts(); + (counts.block_decode_passes, counts.cpu_block_decodes) + }; + for (f, pf) in FORMATS.into_iter().enumerate() { + let decode = AstcDecode::of(pf).unwrap(); + let native = decodes_astc(device, pf); + twinned |= !native; + let row = row_bytes(decode); + let side = Size::new(SIDE.into(), SIDE.into(), 1); + let whole = Region::new_2d(0, 0, SIDE.into(), SIDE.into()); + let mut check = |what: &str, texture: &Texture, blocks: &[u8]| { + let mut back = vec![0; blocks.len()]; + texture.get_bytes(&mut back, row, 0, whole, 0, 0).unwrap(); + if back != blocks { + wrong.push(format!("{pf:?} {what}: get_bytes changed the blocks")); + } + let length = blocks.len() as u64; + if download(device, texture, (0, 0), side, (row, 0), length) != blocks { + wrong.push(format!( + "{pf:?} {what}: a blit into a buffer changed the blocks" + )); + } + if native { + return; + } + let got = read_whole(device, &state, texture); + let want = metal_texels(decode, blocks); + let mut most = 0.0f32; + for (t, (got, want)) in got.iter().zip(&want).enumerate() { + for c in 0..4 { + let off = (got[c] - want[c]).abs(); + most = most.max(off); + let fits = reads_as(policy, decode, got[c], want[c]); + if !fits && wrong.len() < 24 { + wrong.push(format!( + "{pf:?} {what} texel {t} channel {c}: {} against Metal's {}", + got[c], want[c] + )); + } + } + } + eprintln!("ASTCREAD {name} {policy:?} {pf:?} {what}: at most {most} off Metal's"); + }; + let texture = texture(device, pf, TextureUsage::SHADER_READ); + // A new texture's zero blocks are error blocks: magenta. + let count = block_count(decode); + check("fresh", &texture, &vec![0; count * 16]); + let seed = 0xa57c_0000 + 0x10 * f as u64; + let written = seeded_blocks(seed, count); + let before = decodes(device); + texture + .replace_region(whole, 0, 0, &written, row, 0) + .unwrap(); + check("CPU copy", &texture, &written); + // A CPU copy's decode: a GPU pass where it goes through a submission, else the CPU's. + let after = decodes(device); + if !native && after == before { + undecoded.push(format!("{pf:?} CPU copy: neither a pass nor a CPU decode")); + } + let blitted = seeded_blocks(seed + 1, count); + let before = decodes(device); + upload(device, &texture, (0, 0), side, (row, 0), &blitted); + check("blit", &texture, &blitted); + let [across, down] = blocks_of(decode, SIDE.into(), SIDE.into()); + blit(device, |encoder| { + let blocks = Region::new_2d(0, 0, across, down); + encoder + .fill_texture(&texture, 0, 0, blocks, &VOID_EXTENT) + .unwrap(); + }); + check("fill", &texture, &VOID_EXTENT.repeat(count)); + let copy = self::texture(device, pf, TextureUsage::SHADER_READ); + let source = seeded_blocks(seed + 2, count); + texture + .replace_region(whole, 0, 0, &source, row, 0) + .unwrap(); + let blits = decodes(device); + blit(device, |encoder| { + let at = Origin::new(0, 0, 0); + encoder + .copy_from_texture_to_texture(&texture, 0, 0, at, side, ©, 0, 0, at) + .unwrap(); + }); + check("texture copy", ©, &source); + // Every blit's decode is a GPU pass: the upload's and the fill's, then the copy's. + let after = decodes(device); + if !native && (blits.0 < before.0 + 2 || after.0 == blits.0) { + undecoded.push(format!( + "{pf:?} blits: GPU decode passes {before:?} -> {blits:?} -> {after:?}" + )); + } + } + assert!(wrong.is_empty(), "on {name}:\n{}", wrong.join("\n")); + assert!(undecoded.is_empty(), "on {name}:\n{}", undecoded.join("\n")); + let counts = counts(&messages.take_notices()); + let announced = |kind| counts.get(&kind).copied().unwrap_or(0); + let precision = twinned && policy == DecodedTexelsPolicy::Compact; + assert_eq!( + (announced(ASTC_TWINS[0]), announced(ASTC_TWINS[1])), + (usize::from(twinned), usize::from(precision)), + "on {name}" + ); + }); +} + +/// Whether `got` reads as Metal's `want` for a channel of a texel of `decode` under `policy` (the +/// module docs): bit for bit under `DecodedTexelsPolicy::Exact`, and an sRGB form's under either +/// (its twin's codes, decoded through Metal's table); an LDR form's within 1/510 under the +/// default. +fn reads_as(policy: DecodedTexelsPolicy, decode: AstcDecode, got: f32, want: f32) -> bool { + match (policy, decode.srgb) { + (DecodedTexelsPolicy::Exact, _) | (_, true) => got.to_bits() == want.to_bits(), + _ => (got - want).abs() <= UNORM8_BOUND, + } +} + +/// [`astc_texels_under`] the default, `DecodedTexelsPolicy::Compact`. +#[test] +fn astc_texels_read_as_metal_s() { + astc_texels_under(DecodedTexelsPolicy::Compact); +} + +/// [`astc_texels_under`] `DecodedTexelsPolicy::Exact`, which `DevicePolicy::exact_answers` selects. +#[test] +fn astc_texels_read_exactly_as_metal_s_under_exact() { + astc_texels_under(DecodedTexelsPolicy::Exact); +} + +/// The other colour space's form of an ASTC LDR format: its sRGB form's LDR one, and the other +/// way. +fn other_space(pf: PixelFormat) -> PixelFormat { + FORMATS + .into_iter() + .find(|&other| { + let (a, b) = (AstcDecode::of(pf).unwrap(), AstcDecode::of(other).unwrap()); + a.srgb != b.srgb && a.block_extent() == b.block_extent() + }) + .unwrap() +} + +/// On a device without ASTC, a view of a texture in its other colour space (an sRGB texture as its +/// LDR form, an LDR one as its sRGB form) reads Metal's texels of the view's form, as a texture of +/// the view's format over the same blocks reads them (our probe on an M3 Max: bit for bit), and +/// the texture its own, through its second decoded twin (the module docs): after a CPU copy made +/// before the view (the twin's whole decode), a blit encoded before another texture's view was +/// made and committed after it, a blit, a CPU copy and a copy from another texture after the +/// view. A blit into a texture with no such view counts a check and records no decode +/// (`WorkCounts::second_twin_checks`, `second_twin_decodes`); one after the view records one. +#[test] +fn astc_views_in_the_other_colour_space_read_as_metal_s() { + on_device(|device, _messages| { + let name = device.name().to_owned(); + let state = reader(device); + let policy = DecodedTexelsPolicy::Compact; + let mut wrong = Vec::new(); + let formats = [ + PixelFormat::ASTC4x4SRGB, + PixelFormat::ASTC6x5LDR, + PixelFormat::ASTC12x12SRGB, + PixelFormat::ASTC8x8LDR, + ]; + for (f, pf) in formats.into_iter().enumerate() { + if decodes_astc(device, pf) { + continue; + } + let other = other_space(pf); + let (own, theirs) = (AstcDecode::of(pf).unwrap(), AstcDecode::of(other).unwrap()); + let row = row_bytes(own); + let count = block_count(own); + let side = Size::new(SIDE.into(), SIDE.into(), 1); + let whole = Region::new_2d(0, 0, SIDE.into(), SIDE.into()); + let check = |wrong: &mut Vec, + what: &str, + texture: &Texture, + decode: AstcDecode, + blocks: &[u8]| { + let got = read_whole(device, &state, texture); + let want = metal_texels(decode, blocks); + for (t, (got, want)) in got.iter().zip(&want).enumerate() { + for c in 0..4 { + let fits = reads_as(policy, decode, got[c], want[c]); + if !fits && wrong.len() < 24 { + wrong.push(format!( + "{pf:?} as {:?} {what} texel {t} channel {c}: {} against Metal's {}", + decode, got[c], want[c] + )); + } + } + } + }; + let seed = 0xa57c_4000 + 0x10 * f as u64; + let texture = texture(device, pf, TextureUsage::SHADER_READ); + // No view yet: a blit's write is checked and decodes into no second twin. + let before = device.work_counts(); + upload( + device, + &texture, + (0, 0), + side, + (row, 0), + &seeded_blocks(seed, count), + ); + let after = device.work_counts(); + if after.second_twin_checks <= before.second_twin_checks + || after.second_twin_decodes != before.second_twin_decodes + { + wrong.push(format!( + "{pf:?} a blit without a view: checks {} -> {}, decodes {} -> {}", + before.second_twin_checks, + after.second_twin_checks, + before.second_twin_decodes, + after.second_twin_decodes + )); + } + // A CPU copy, then the view: its second twin's whole decode. + let copied = seeded_blocks(seed + 1, count); + texture + .replace_region(whole, 0, 0, &copied, row, 0) + .unwrap(); + let view = texture.new_texture_view(other).unwrap(); + check( + &mut wrong, + "CPU copy before the view", + &texture, + own, + &copied, + ); + check( + &mut wrong, + "CPU copy before the view", + &view, + theirs, + &copied, + ); + // A blit after the view decodes into the second twin. + let blitted = seeded_blocks(seed + 2, count); + let before = device.work_counts(); + upload(device, &texture, (0, 0), side, (row, 0), &blitted); + let after = device.work_counts(); + if after.second_twin_decodes <= before.second_twin_decodes { + wrong.push(format!( + "{pf:?} a blit after the view decoded no second twin" + )); + } + check(&mut wrong, "blit", &view, theirs, &blitted); + check(&mut wrong, "blit", &texture, own, &blitted); + // A CPU copy after the view. + let copied = seeded_blocks(seed + 3, count); + texture + .replace_region(whole, 0, 0, &copied, row, 0) + .unwrap(); + check(&mut wrong, "CPU copy", &view, theirs, &copied); + // A copy from another texture. + let source = self::texture(device, pf, TextureUsage::SHADER_READ); + let blocks = seeded_blocks(seed + 4, count); + source.replace_region(whole, 0, 0, &blocks, row, 0).unwrap(); + blit(device, |encoder| { + let at = Origin::new(0, 0, 0); + encoder + .copy_from_texture_to_texture(&source, 0, 0, at, side, &texture, 0, 0, at) + .unwrap(); + }); + check(&mut wrong, "texture copy", &view, theirs, &blocks); + // A blit encoded before a texture's view was made, committed after it: the view's + // twin reads the blocks the blit wrote. + let later = self::texture(device, pf, TextureUsage::SHADER_READ); + let blocks = seeded_blocks(seed + 5, count); + let staged = buffer_with(device, &blocks).unwrap(); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + let at = Origin::new(0, 0, 0); + encoder + .copy_from_buffer_to_texture( + &staged, + 0, + row, + 0, + side, + &later, + 0, + 0, + at, + BlitOption::None, + ) + .unwrap(); + encoder.end_encoding().unwrap(); + let later_view = later.new_texture_view(other).unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + check( + &mut wrong, + "blit encoded before the view", + &later_view, + theirs, + &blocks, + ); + check( + &mut wrong, + "blit encoded before the view", + &later, + own, + &blocks, + ); + } + assert!(wrong.is_empty(), "on {name}:\n{}", wrong.join("\n")); + }); +} + +/// Every level and slice of a mipmapped 2D array (two slices) and cube of sides no multiple of the +/// block, of a square, an oblong and an sRGB footprint: blocks blitted in from a buffer at the +/// level's texel size come back bit for bit from blits into a buffer and from `get_bytes` (the +/// module docs). +#[test] +fn astc_blocks_round_trip_at_every_level_and_slice() { + on_device(|device, _messages| { + let name = device.name().to_owned(); + let mut wrong = Vec::new(); + let formats = [ + PixelFormat::ASTC8x8LDR, + PixelFormat::ASTC6x5LDR, + PixelFormat::ASTC12x10SRGB, + ]; + for (f, pf) in formats.into_iter().enumerate() { + let decode = AstcDecode::of(pf).unwrap(); + let mut array = TextureDescriptor::texture_2d(pf, 37, 23, true); + array.texture_type = TextureType::Type2DArray; + array.array_length = 2; + let cube = TextureDescriptor::texture_cube(pf, 29, true); + for (shape, descriptor) in [("array", array), ("cube", cube)] { + let texture = made(device, descriptor, TextureUsage::SHADER_READ); + let slices = match descriptor.texture_type { + TextureType::Cube => 6, + _ => descriptor.array_length, + }; + for level in 0..descriptor.mipmap_level_count { + let width = (descriptor.width >> level).max(1); + let height = (descriptor.height >> level).max(1); + let [across, down] = blocks_of(decode, width, height); + let row = across * u64::from(AstcDecode::BLOCK_BYTES); + let image = row * down; + let size = Size::new(width, height, 1); + for slice in 0..slices { + let seed = 0xa57c_2000 ^ ((f as u64) << 16) ^ (level << 8) ^ slice; + let blocks = seeded_blocks(seed, (across * down) as usize); + let at = (level, slice); + upload(device, &texture, at, size, (row, image), &blocks); + let what = format!("{pf:?} {shape} level {level} slice {slice}"); + if download(device, &texture, at, size, (row, image), image) != blocks { + wrong.push(format!("{what}: a blit into a buffer changed the blocks")); + } + let mut back = vec![0; blocks.len()]; + let region = Region::new_2d(0, 0, width, height); + texture + .get_bytes(&mut back, row, image, region, level, slice) + .unwrap(); + if back != blocks { + wrong.push(format!("{what}: get_bytes changed the blocks")); + } + } + } + } + } + assert!(wrong.is_empty(), "on {name}:\n{}", wrong.join("\n")); + }); +} + +/// On a device without ASTC: a texture of `ShaderWrite` and `RenderTarget` usage is made (as +/// Metal makes it); a placement heap's texture (whose size the device answers) and a view of the +/// texture's HDR form are refused, typed. Nothing on a device with the format's block. +#[test] +fn astc_textures_the_runtime_does_not_hold_are_refused() { + on_device(|device, messages| { + let pf = PixelFormat::ASTC8x8LDR; + if decodes_astc(device, pf) { + return; + } + let usage = + TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE | TextureUsage::RENDER_TARGET; + let written = texture(device, pf, usage); + let mut descriptor = TextureDescriptor::texture_2d(pf, SIDE.into(), SIDE.into(), false); + descriptor.resource_options = ResourceOptions::shared(); + // Its heap size query is refused alike. + let answer = device.heap_texture_size_and_align(&descriptor).map(drop); + assert!( + matches!( + answer, + Err(Error::NotImplemented(RuntimeGap::DecodedHeapTexture)) + ), + "{answer:?}" + ); + let heap_descriptor = + HeapDescriptor::new(HeapType::Placement, 1 << 16, ResourceOptions::shared()); + let heap = device.new_heap(&heap_descriptor).unwrap(); + let placed = heap.new_texture_at_offset(&descriptor, 0).map(drop); + assert!( + matches!( + placed, + Err(Error::NotImplemented(RuntimeGap::DecodedHeapTexture)) + ), + "{placed:?}" + ); + // A view as its HDR form reads another decode; one as its sRGB form is made + // ([`astc_views_in_the_other_colour_space_read_as_metal_s`]). + let view = written.new_texture_view(PixelFormat::ASTC8x8HDR).map(drop); + assert!(matches!(view, Err(Error::Unsupported(_))), "{view:?}"); + written.new_texture_view(PixelFormat::ASTC8x8SRGB).unwrap(); + let counts = counts(&messages.take_notices()); + assert_eq!(counts.get(&ASTC_TWINS[0]).copied(), Some(1)); + }); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/chroma_pairs.rs b/crates/metal2vulkan-validation/src/runtime_lane/chroma_pairs.rs index deed43f63..7836561f4 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/chroma_pairs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/chroma_pairs.rs @@ -12,25 +12,33 @@ //! - A copy into such a texture from a texture of another format is refused typed //! (`Unsupported`, `Feature::Format`): plain Metal writes `0xff` over part of each row. //! - A kernel that only writes the texture completes and leaves it as it was, as plain Metal's -//! `write()` does (its validation stops the binding). A kernel that reads it is refused typed -//! (`Bind(Unsupported)`, `Feature::Format`): Metal decodes the pairs. +//! `write()` does (its validation stops the binding). +//! - A kernel reads and samples Metal's texels (`metal2vulkan::bind::ChromaDecode`, matched +//! against an Apple M3 Max's reads by its own tests) through the texture's decoded twin, +//! announced `carried-decoded-twin` once and `decoded-texel-precision` never: a new texture's +//! opaque black, then after a CPU copy of the whole texture and of part of two rows, a blit +//! from a buffer of the whole texture and of part of a row, and a copy from another texture, +//! each decoded into the twin in whole rows (a blit's by a GPU decode pass, a CPU copy's by one +//! or on the CPU, counted in `WorkCounts`; [`four_two_two_texels_read_as_metal_s`]). //! - A render pipeline state of the format, which Metal's own validation aborts plain too, and a //! render pass into the texture, whose clear plain Metal stores in the format's encoding (not //! built), are refused typed (`Unsupported`, `Feature::Format`). -use super::degrade_notices::on_device; +use super::astc_textures::{read_whole, reader}; +use super::degrade_notices::{counts, on_device}; use super::{buffer_with, read_buffer, WAIT}; use crate::air_library::AirLibrary; -use metal2vulkan::error::{BindError, Feature, Unsupported}; +use metal2vulkan::bind::ChromaDecode; +use metal2vulkan::error::Feature; use metal2vulkan::metal::{PixelFormat, TextureUsage}; use metal2vulkan::pipeline::{ ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource, }; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ - BlitOption, Buffer, CommandBufferStatus, ComputePipelineState, Device, Error, LoadAction, - Origin, PipelineOptions, Region, RenderPassDescriptor, ResourceOptions, Size, StoreAction, - Texture, TextureDescriptor, + BlitOption, Buffer, CommandBufferStatus, ComputePipelineState, Degradation, Device, Error, + LoadAction, Origin, PipelineOptions, Region, RenderPassDescriptor, ResourceOptions, Size, + StoreAction, Texture, TextureDescriptor, }; /// The two 4:2:2 formats. @@ -400,7 +408,8 @@ fn state(device: &Device, stem: &str, entry: &str) -> ComputePipelineState { /// `(0.25, 0.5, 0.75, 1)` at each thread's position, over a filled 4:2:2 texture of `ShaderRead /// | ShaderWrite` usage completes and leaves its bytes as they were; over an `RGBA8Unorm` one, /// the control, it writes them (its tie within one unit of Metal's). `sampling`'s -/// `sample_pixel`, which reads its texture, is refused typed at the dispatch. +/// `sample_pixel`, whose linear sample at texel (0, 0)'s centre reads that texel, reads Metal's +/// texel there (within one ulp: the device's filter converts the twin's codes). #[test] fn a_four_two_two_texture_written_by_a_kernel_keeps_its_texels() { on_device(|device, _| { @@ -435,20 +444,20 @@ fn a_four_two_two_texture_written_by_a_kernel_keeps_its_texels() { let out = buffer_with(device, &[0; 1024]).unwrap(); encoder.set_buffer(Some(&out), 0, 0).unwrap(); let one = Size::new(1, 1, 1); - let dispatched = encoder.dispatch_threads(one, one); + encoder.dispatch_threads(one, one).unwrap(); encoder.end_encoding().unwrap(); command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); - assert!( - matches!( - &dispatched, - Err(Error::Bind(BindError::Unsupported(Unsupported { - feature: Feature::Format, - .. - }))) - ), - "{pf:?}: read: {dispatched:?}" - ); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + let got = &metal_texels(pf, &pattern)[0]; + let read = read_buffer(&out, 0, 16).unwrap(); + for (c, want) in got.iter().enumerate() { + let value = f32::from_le_bytes(read[4 * c..4 * c + 4].try_into().unwrap()); + assert!( + (value - want).abs() <= f32::EPSILON, + "{pf:?}: sampled channel {c}: {value} against Metal's {want}" + ); + } } let control = texture(device, PixelFormat::RGBA8Unorm, usage, false); dispatch(&control); @@ -487,6 +496,133 @@ fn a_four_two_two_texture_written_by_a_kernel_keeps_its_texels() { }); } +/// Metal's `float` texels of a [`SIDE`]-square 4:2:2 texture of `pf` holding `bytes` +/// (`ChromaDecode`): each code over 255. +fn metal_texels(pf: PixelFormat, bytes: &[u8]) -> Vec<[f32; 4]> { + let decode = ChromaDecode::of(pf).unwrap(); + let codes = decode.decode(bytes, [SIDE as u32, SIDE as u32, 1]); + (codes.as_chunks::<4>().0.iter()) + .map(|texel| texel.map(|code| f32::from(code) / 255.0)) + .collect() +} + +/// Each format's texels read exactly as Metal's after every kind of write (the module docs): a +/// `Shared` texture's after a CPU copy of the whole texture and of 4 x 2 texels off the pairs' +/// rows, whose red and blue change beside the region too, then after a blit of the whole texture +/// and of 6 x 1 texels; a `Private` texture's after a copy from the `Shared` one. Each read is a +/// command buffer after the write. The CPU copies' decodes are a GPU pass or the CPU's, the +/// blits' GPU passes; the twin announces `carried-decoded-twin` once. +#[test] +fn four_two_two_texels_read_as_metal_s() { + on_device(|device, messages| { + let name = device.name().to_owned(); + let state = reader(device); + let usage = TextureUsage::SHADER_READ; + let decodes = |device: &Device| { + let counts = device.work_counts(); + (counts.block_decode_passes, counts.cpu_block_decodes) + }; + let mut wrong = Vec::new(); + let check = + |wrong: &mut Vec, what: &str, pf: PixelFormat, t: &Texture, bytes: &[u8]| { + assert_eq!(bytes_of(device, t), bytes, "{pf:?} {what}: its bytes"); + let got = read_whole(device, &state, t); + let want = metal_texels(pf, bytes); + for (at, (got, want)) in got.iter().zip(&want).enumerate() { + for c in 0..4 { + if got[c].to_bits() != want[c].to_bits() && wrong.len() < 24 { + wrong.push(format!( + "{pf:?} {what}, texel {at} channel {c}: {} against Metal's {}", + got[c], want[c] + )); + } + } + } + }; + let whole = Region::new_2d(0, 0, SIDE, SIDE); + for (f, pf) in PAIRS.into_iter().enumerate() { + let t = texture(device, pf, usage, true); + check(&mut wrong, "fresh", pf, &t, &vec![0; (ROW * SIDE) as usize]); + let written = seq(ROW * SIDE, 0x31 + 0x40 * f as u8); + let before = decodes(device); + t.replace_region(whole, 0, 0, &written, ROW, 0).unwrap(); + check(&mut wrong, "CPU copy", pf, &t, &written); + // A part of two rows off the pairs: 4 texels from x 6 on rows 3 and 4. + let patch = seq(16, 0xa0); + let region = Region::new_2d(6, 3, 4, 2); + t.replace_region(region, 0, 0, &patch, 8, 0).unwrap(); + let mut expected = written.clone(); + for row in 0..2 { + let at = ((3 + row) * ROW + 2 * 6) as usize; + expected[at..at + 8].copy_from_slice(&patch[8 * row as usize..][..8]); + } + check( + &mut wrong, + "CPU copy of part of two rows", + pf, + &t, + &expected, + ); + if decodes(device) == before { + wrong.push(format!( + "{pf:?} CPU copies: neither a pass nor a CPU decode" + )); + } + let blitted = seq(ROW * SIDE, 0x17 + 0x40 * f as u8); + let before = decodes(device); + fill(device, &t, &blitted); + check(&mut wrong, "blit", pf, &t, &blitted); + // 6 texels from x 2 on row 7. + let row = seq(12, 0xc8); + let source = buffer_with(device, &row).unwrap(); + blit(device, |e| { + e.copy_from_buffer_to_texture( + &source, + 0, + 12, + 12, + Size::new(6, 1, 1), + &t, + 0, + 0, + Origin::new(2, 7, 0), + BlitOption::None, + ) + }) + .unwrap(); + let mut expected = blitted.clone(); + let at = (7 * ROW + 2 * 2) as usize; + expected[at..at + 12].copy_from_slice(&row); + check(&mut wrong, "blit of part of a row", pf, &t, &expected); + let private = texture(device, pf, usage, false); + blit(device, |e| { + let at = Origin::new(0, 0, 0); + let side = Size::new(SIDE, SIDE, 1); + e.copy_from_texture_to_texture(&t, 0, 0, at, side, &private, 0, 0, at) + }) + .unwrap(); + check(&mut wrong, "texture copy", pf, &private, &expected); + let after = decodes(device); + if after.0 < before.0 + 3 { + wrong.push(format!( + "{pf:?} blits: GPU decode passes {before:?} -> {after:?}" + )); + } + } + assert!(wrong.is_empty(), "on {name}:\n{}", wrong.join("\n")); + let counts = counts(&messages.take_notices()); + let announced = |kind| counts.get(&kind).copied().unwrap_or(0); + assert_eq!( + ( + announced(Degradation::CarriedDecodedTwin), + announced(Degradation::DecodedTexelPrecision) + ), + (1, 0), + "on {name}" + ); + }); +} + /// Probe 8's `pipeline_*` (Metal's validation aborts a render pipeline of the format, plain /// too) and `pass_*` (a pass into the texture, whose clear plain Metal stores in the format's /// encoding, probe 11's `pass_clear_*`; its validation stops it, "not color renderable"): both diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index ae7c8da7d..aa6964fe4 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -78,8 +78,8 @@ //! sampler states of an anisotropy past the device's largest here ([`CAPPED_ANISOTROPY`]), //! anisotropic sampler states without a mip filter through Metal's own sampler //! ([`NOT_MIPMAPPED_ANISOTROPY`]), draws that read an attachment's bytes in place in -//! `attachment_reads` ([`IN_PLACE`]), PVRTC -//! textures held for copies that a kernel's texture handles reach in `pvrtc_textures` +//! `attachment_reads` ([`IN_PLACE`]), textures +//! held for copies alone that a kernel's texture handles reach in `pvrtc_textures` //! ([`UNREADABLE`]), the device's texture table and heap sets in `resource_ids` (an unviewable //! texture, [`UNVIEWABLE`]; a shadowed one, [`UNNAMED_SHADOWS`]; an ID past a pipeline's arrays, //! [`PAST_CAPACITY`]; each command buffer's own copy on a device withholding @@ -100,7 +100,8 @@ //! ([`UNMODELLED_SIZES`]) and those whose images take more of a heap than Metal's answer there //! ([`PAST_METAL_SIZES`]), BC1 to BC5 textures on a driver not measured to decode them as Metal //! does in `compressed_decode` ([`BLOCK_DECODES`]) and writes into their decoded twins behind -//! work in flight there ([`BEHIND_WRITES`]), passes rendering a linear image apart in +//! work in flight there ([`BEHIND_WRITES`]), ASTC textures on a device without their format in +//! `astc_textures` ([`ASTC_TWINS`]; PVRTC ones take the first in `pvrtc_textures`), passes rendering a linear image apart in //! `linear_attachments` ([`LINEAR_COPIES`]) and those rendering one through copies as they clear //! it and no command of them may read it, there too ([`CHOSEN_COPIES`]), passes rendering a texture //! over a buffer they do not store through the image its texture keeps in `kept_buffer_bytes` @@ -136,6 +137,7 @@ use super::absent_reads::ABSENT_READS; use super::amplified_draws::AMPLIFICATION; +use super::astc_textures::{decodes_astc, ASTC_TWINS}; use super::attachment_reads::IN_PLACE; use super::barycentric_weights::SYNTHESIZED_GEOMETRY; use super::binary_archives::ARCHIVES; @@ -205,7 +207,7 @@ use crate::candidate::engine::compute_shape; use crate::candidate::engine::resources::pixel_format; use crate::candidate::engine::variants::compile_compute_for_shape; use crate::gpu::TEST_DEVICE; -use metal2vulkan::bind::SamplerDescriptor; +use metal2vulkan::bind::{AstcDecode, SamplerDescriptor}; use metal2vulkan::cache::VariantKey; use metal2vulkan::device::VkExtension; use metal2vulkan::device::{DriverFact, DriverWorkaround, OpBits, VkFeature, VkProperty}; @@ -525,6 +527,7 @@ fn every_kind_has_a_site_a_lane_test_takes() { &NIL_OFFSETS, &BLOCK_DECODES, &BEHIND_WRITES, + &ASTC_TWINS, &SHARED_PRESENT_QUEUES, &PAST_METAL_SIZES, &LINEAR_COPIES, @@ -1998,6 +2001,31 @@ pub(super) fn draws_depth_copies(device: &Device) -> bool { !copies && !exact } +/// Whether `device` holds a texture of `pf` of its own in a carrier with a decoded twin +/// (`carried-decoded-twin`), and whether the twin's codes announce `decoded-texel-precision`: an +/// ASTC format the device has no block for (`astc_textures::decodes_astc`), a PVRTC, ETC2 or +/// EAC format it has no format for, or a 4:2:2 format (every device); the notice for an ASTC LDR +/// format's 8-bit codes and an EAC 11-bit format's 16-bit ones under +/// `DecodedTexelsPolicy::Compact`, and for no other twin, whose codes are exact (an ASTC sRGB +/// format's, a PVRTC format's, an 8-bit ETC2 or EAC format's, a 4:2:2 format's). +pub(super) fn twins_carried(device: &Device, pf: PixelFormat) -> [bool; 2] { + let astc = AstcDecode::of(pf).filter(|_| !decodes_astc(device, pf)); + let usage = [metal2vulkan::device::FormatUsage::SampledImage].into(); + let profile = device.compile_device().profile(); + let decoded = metal2vulkan::metal::format::vk_format(pf, &usage, profile) + .is_ok_and(|m| m.emulation == metal2vulkan::metal::format::FormatEmulation::Decoded); + let pvrtc = metal2vulkan::bind::PvrtcDecode::of(pf).is_some() && decoded; + let etc = metal2vulkan::bind::EtcDecode::of(pf).filter(|_| decoded); + let chroma = metal2vulkan::bind::ChromaDecode::of(pf).is_some() && decoded; + let eleven = etc.is_some_and(metal2vulkan::bind::EtcDecode::eleven_bit); + let compact = device.compile_device().policy().decoded_texels == DecodedTexelsPolicy::Compact; + let ldr = astc.is_some_and(|decode| !decode.srgb); + [ + astc.is_some() || pvrtc || etc.is_some() || chroma, + (ldr || eleven) && compact, + ] +} + /// Whether `device` gives a single-sample texture of `pf` a decoded twin (`decoded-block-twin`): a /// BC1 to BC5 format whose decode its driver is not measured to make as Metal's (BC1 to BC3 /// `DriverFact::ColorBlockDecodeIsMetals`, BC4 and BC5 `DriverFact::ChannelBlockDecodeIsMetals`). diff --git a/crates/metal2vulkan-validation/src/runtime_lane/etc_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/etc_textures.rs new file mode 100644 index 000000000..3b51a6be5 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/etc_textures.rs @@ -0,0 +1,272 @@ +//! ETC2 and EAC textures on the device the cfg selects, under the validation layer, against +//! Metal's decode (`metal2vulkan::bind::EtcDecode`, matched against an Apple M3 Max's reads of +//! random blocks by its own tests). +//! +//! On a device without the formats ([`holds_etc`] false: desktop GPUs and lavapipe) the texture +//! holds its blocks in a carrier and its reads go through a decoded twin, announced +//! `carried-decoded-twin` once and, for an 11-bit format under `DecodedTexelsPolicy::Compact`, +//! `decoded-texel-precision` once. Every format's texels read as Metal's after every kind of +//! write ([`etc_texels_read_as_metal_s`], [`etc_texels_read_exactly_as_metal_s_under_exact`]): an +//! 8-bit format's exactly under either policy (an sRGB form's colour through Metal's table, read +//! from the twin's codes), an 11-bit format's exactly under `DecodedTexelsPolicy::Exact` and within +//! half a 16-bit step under the default; a new texture's zero blocks, then blocks a CPU copy wrote, +//! a blit from a buffer, a fill of one block and a copy from another texture, each read by a +//! command buffer after the write's, each decoded into the twin (a blit's by a GPU decode pass, a +//! CPU copy's by one or on the CPU, counted in `WorkCounts`), and an 8-bit format's view as its +//! other colour space, which reads the same codes. The blocks each wrote come back unchanged from +//! `get_bytes` and from a blit into a buffer, on every device. A view of an 11-bit format as its +//! other signedness is refused there (`Feature::TextureView`). A device with the formats reads +//! through its own decode (not compared), announcing neither kind. + +use super::astc_textures::{blit, download, read_whole, reader, texture, upload}; +use super::degrade_notices::{counts, on_device_with}; +use metal2vulkan::bind::{EtcDecode, EtcTexels, PvrtcDecode}; +use metal2vulkan::device::{DecodedTexelsPolicy, FormatUsage}; +use metal2vulkan::metal::format::{srgb_raw_twin, vk_format, FormatEmulation}; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use metal2vulkan_runtime::{ + Degradation, Device, DeviceOptions, Error, Origin, Region, Size, Texture, +}; + +/// The ten ETC2 and EAC formats. +const FORMATS: [PixelFormat; 10] = [ + PixelFormat::ETC2RGB8, + PixelFormat::ETC2RGB8SRGB, + PixelFormat::ETC2RGB8A1, + PixelFormat::ETC2RGB8A1SRGB, + PixelFormat::EACRGBA8, + PixelFormat::EACRGBA8SRGB, + PixelFormat::EACR11Unorm, + PixelFormat::EACR11Snorm, + PixelFormat::EACRG11Unorm, + PixelFormat::EACRG11Snorm, +]; + +/// The side, in texels, of every texture the lane reads (`astc_textures`'s): 4 x 4 blocks. +const SIDE: u32 = 16; + +/// Whether `device` holds a texture of `pf` in its own format, decoding it its own way, rather +/// than in a carrier with a decoded twin. +fn holds_etc(device: &Device, pf: PixelFormat) -> bool { + let usage = [FormatUsage::SampledImage].into(); + let mapping = vk_format(pf, &usage, device.compile_device().profile()).unwrap(); + mapping.emulation != FormatEmulation::Decoded +} + +/// `count` blocks of `bytes` each of a seeded xorshift: random bits, which decode through every +/// mode. +fn seeded_blocks(seed: u64, count: usize, bytes: usize) -> Vec { + let mut state = seed | 1; + let mut out = Vec::with_capacity(count * bytes + 8); + while out.len() < count * bytes { + state ^= state >> 12; + state ^= state << 25; + state ^= state >> 27; + out.extend_from_slice(&state.wrapping_mul(0x2545_f491_4f6c_dd1d).to_le_bytes()); + } + out.truncate(count * bytes); + out +} + +/// The `float` Metal reads of channel `c` of a `SIDE` x `SIDE` level of `pf`'s `blocks`, each +/// texel's four: an 8-bit code over 255, an sRGB form's colour through Metal's twelve-bit table +/// (the table PVRTC's and BC's sRGB forms read through), an 11-bit value over 2047 (signed 1023), +/// and an `R11` or `RG11` format's missing channels 0, alpha 1. +fn metal_texels(pf: PixelFormat, blocks: &[u8]) -> Vec<[f32; 4]> { + let decode = EtcDecode::of(pf).unwrap(); + let size = [SIDE, SIDE, 1]; + let texels = decode.decode(EtcTexels::Float, blocks, size); + if decode.eleven_bit() { + let channels = decode.texel_bytes(EtcTexels::Float) as usize / 4; + return (texels.chunks_exact(4 * channels)) + .map(|texel| { + let value = + |k: usize| f32::from_le_bytes(texel[4 * k..4 * k + 4].try_into().unwrap()); + let green = if channels == 2 { value(1) } else { 0.0 }; + [value(0), green, 0.0, 1.0] + }) + .collect(); + } + let table = match srgb_raw_twin(pf).is_some() { + true => PvrtcDecode::of(PixelFormat::PVRTCRGBA4BPPSRGB).unwrap(), + false => PvrtcDecode::of(PixelFormat::PVRTCRGBA4BPP).unwrap(), + }; + (texels.as_chunks::<4>().0.iter()) + .map(|codes| std::array::from_fn(|c| table.metal_value(c, codes[c]))) + .collect() +} + +/// The most a compact 11-bit texel is off Metal's value: half a 16-bit step, with room for `f32`. +fn compact_bound(pf: PixelFormat) -> f32 { + match pf { + PixelFormat::EACR11Snorm | PixelFormat::EACRG11Snorm => 0.5 / 32767.0 + 1e-6, + _ => 0.5 / 65535.0 + 1e-6, + } +} + +/// The other colour space's form of an 8-bit ETC2 or EAC format, or an 11-bit format's other +/// signedness. +fn other_form(pf: PixelFormat) -> PixelFormat { + use PixelFormat as P; + match pf { + P::ETC2RGB8 => P::ETC2RGB8SRGB, + P::ETC2RGB8SRGB => P::ETC2RGB8, + P::ETC2RGB8A1 => P::ETC2RGB8A1SRGB, + P::ETC2RGB8A1SRGB => P::ETC2RGB8A1, + P::EACRGBA8 => P::EACRGBA8SRGB, + P::EACRGBA8SRGB => P::EACRGBA8, + P::EACR11Unorm => P::EACR11Snorm, + P::EACR11Snorm => P::EACR11Unorm, + P::EACRG11Unorm => P::EACRG11Snorm, + _ => P::EACRG11Unorm, + } +} + +/// Every ETC2 and EAC format's texels read as Metal's on a device without the formats, under +/// `policy` (the module docs): a new texture's, then after a CPU copy, a blit from a buffer, a +/// fill and a copy from another texture, the blocks of each coming back unchanged. +fn etc_texels_under(policy: DecodedTexelsPolicy) { + let adjust = |options: &mut DeviceOptions| options.policy.decoded_texels = policy; + on_device_with(adjust, |device, messages| { + let name = device.name().to_owned(); + let state = reader(device); + let mut wrong = Vec::new(); + let mut undecoded = Vec::new(); + let (mut twinned, mut eleven) = (false, false); + // The GPU decode passes and CPU decodes so far. + let decodes = |device: &Device| { + let counts = device.work_counts(); + (counts.block_decode_passes, counts.cpu_block_decodes) + }; + for (f, pf) in FORMATS.into_iter().enumerate() { + let decode = EtcDecode::of(pf).unwrap(); + let native = holds_etc(device, pf); + twinned |= !native; + eleven |= !native && decode.eleven_bit(); + let bytes = decode.block_bytes() as usize; + let row = u64::from(SIDE / 4) * bytes as u64; + let count = (SIDE / 4 * SIDE / 4) as usize; + let side = Size::new(SIDE.into(), SIDE.into(), 1); + let whole = Region::new_2d(0, 0, SIDE.into(), SIDE.into()); + let check = |wrong: &mut Vec, + what: &str, + texture: &Texture, + read_as: PixelFormat, + blocks: &[u8]| { + let mut back = vec![0; blocks.len()]; + texture.get_bytes(&mut back, row, 0, whole, 0, 0).unwrap(); + if back != blocks { + wrong.push(format!("{pf:?} {what}: get_bytes changed the blocks")); + } + let length = blocks.len() as u64; + if download(device, texture, (0, 0), side, (row, 0), length) != blocks { + wrong.push(format!( + "{pf:?} {what}: a blit into a buffer changed the blocks" + )); + } + if native { + return; + } + let got = read_whole(device, &state, texture); + let want = metal_texels(read_as, blocks); + let exact = !decode.eleven_bit() || policy == DecodedTexelsPolicy::Exact; + for (t, (got, want)) in got.iter().zip(&want).enumerate() { + for c in 0..4 { + let fits = match exact { + true => got[c].to_bits() == want[c].to_bits(), + false => (got[c] - want[c]).abs() <= compact_bound(pf), + }; + if !fits && wrong.len() < 24 { + wrong.push(format!( + "{pf:?} {what} read as {read_as:?}, texel {t} channel {c}: {} \ + against Metal's {}", + got[c], want[c] + )); + } + } + } + }; + let texture = texture(device, pf, TextureUsage::SHADER_READ); + check(&mut wrong, "fresh", &texture, pf, &vec![0; count * bytes]); + let seed = 0xe7c2_0000 + 0x10 * f as u64; + let written = seeded_blocks(seed, count, bytes); + let before = decodes(device); + texture + .replace_region(whole, 0, 0, &written, row, 0) + .unwrap(); + check(&mut wrong, "CPU copy", &texture, pf, &written); + // A CPU copy's decode: a GPU pass where it goes through a submission, else the CPU's. + let after = decodes(device); + if !native && after == before { + undecoded.push(format!("{pf:?} CPU copy: neither a pass nor a CPU decode")); + } + let blitted = seeded_blocks(seed + 1, count, bytes); + let before = decodes(device); + upload(device, &texture, (0, 0), side, (row, 0), &blitted); + check(&mut wrong, "blit", &texture, pf, &blitted); + // An 8-bit format's view in its other colour space reads the same codes; an 11-bit + // one's as its other signedness is refused where the texture has a twin. + let other = other_form(pf); + match texture.new_texture_view(other) { + // A device with the formats views them as it does. + _ if native && decode.eleven_bit() => {} + Ok(view) if !decode.eleven_bit() => { + check(&mut wrong, "blit", &view, other, &blitted) + } + Err(Error::Unsupported(_)) if decode.eleven_bit() => {} + made => wrong.push(format!("{pf:?} viewed as {other:?}: {made:?}")), + } + let one = seeded_blocks(seed + 2, 1, bytes); + blit(device, |encoder| { + let blocks = Region::new_2d(0, 0, u64::from(SIDE / 4), u64::from(SIDE / 4)); + encoder.fill_texture(&texture, 0, 0, blocks, &one).unwrap(); + }); + check(&mut wrong, "fill", &texture, pf, &one.repeat(count)); + let copy = self::texture(device, pf, TextureUsage::SHADER_READ); + let source = seeded_blocks(seed + 3, count, bytes); + texture + .replace_region(whole, 0, 0, &source, row, 0) + .unwrap(); + let blits = decodes(device); + blit(device, |encoder| { + let at = Origin::new(0, 0, 0); + encoder + .copy_from_texture_to_texture(&texture, 0, 0, at, side, ©, 0, 0, at) + .unwrap(); + }); + check(&mut wrong, "texture copy", ©, pf, &source); + // Every blit's decode is a GPU pass: the upload's and the fill's, then the copy's. + let after = decodes(device); + if !native && (blits.0 < before.0 + 2 || after.0 == blits.0) { + undecoded.push(format!( + "{pf:?} blits: GPU decode passes {before:?} -> {blits:?} -> {after:?}" + )); + } + } + assert!(wrong.is_empty(), "on {name}:\n{}", wrong.join("\n")); + assert!(undecoded.is_empty(), "on {name}:\n{}", undecoded.join("\n")); + let counts = counts(&messages.take_notices()); + let announced = |kind| counts.get(&kind).copied().unwrap_or(0); + let precision = eleven && policy == DecodedTexelsPolicy::Compact; + assert_eq!( + ( + announced(Degradation::CarriedDecodedTwin), + announced(Degradation::DecodedTexelPrecision) + ), + (usize::from(twinned), usize::from(precision)), + "on {name}" + ); + }); +} + +/// [`etc_texels_under`] the default, `DecodedTexelsPolicy::Compact`. +#[test] +fn etc_texels_read_as_metal_s() { + etc_texels_under(DecodedTexelsPolicy::Compact); +} + +/// [`etc_texels_under`] `DecodedTexelsPolicy::Exact`, which `DevicePolicy::exact_answers` selects. +#[test] +fn etc_texels_read_exactly_as_metal_s_under_exact() { + etc_texels_under(DecodedTexelsPolicy::Exact); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/format_copies.rs b/crates/metal2vulkan-validation/src/runtime_lane/format_copies.rs index efc2b1b81..1050e1caa 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/format_copies.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/format_copies.rs @@ -9,6 +9,10 @@ //! - A buffer copy through the stencil view reads or writes the stencil, a byte a texel, with any //! blit option; the depth stays. A `Depth32FloatStencil8` texture copies into another, both //! aspects. +//! - Between a compressed format and an uncompressed one whose texel is its block's bytes, Metal +//! copies each block into one texel and back, the copy's origins and size in the destination's +//! texels (our probe on an Apple M3 Max under macOS 27.0.1; +//! [`compressed_blocks_copy_into_texels_of_their_bytes_and_back`]). //! - Formats of different units, and a combined format with another, are Metal's to refuse //! (`Invalid`, `CopyProblem::Format`). //! - A region copied onto itself keeps its texels; a copy between other overlapping regions of @@ -534,3 +538,131 @@ fn a_copy_onto_its_own_texels_keeps_them_and_another_overlap_moves_as_memmove() } assert_eq!(messages.take(), Vec::new(), "the validation layer reported"); } + +/// A unit's bytes: `tag`, its index `i`, then bytes that count up, `n` in all. +fn unit_bytes(i: usize, tag: u8, n: usize) -> Vec { + let mut bytes = vec![tag, i as u8]; + bytes.extend((2..n).map(|k| (k as u8) ^ tag)); + bytes +} + +/// Our probe on an Apple M3 Max under macOS 27.0.1: between a compressed format and an +/// uncompressed one whose texel is its block's bytes, each block copies into one texel and back, +/// the copy's origins and size in the destination's texels. Out of a texture of 8 x 8 blocks an +/// origin of (4, 4) and a size of 2 x 2 into an 8 x 8 texture at (1, 2) copy the blocks from +/// (4, 4) into texels (1, 2) to (2, 3); out of that texture an origin of (1, 2) and a size of +/// 2 x 2 into the compressed one at a block's texel extent (its second block across and down) +/// copy texel (0, 0) alone into that block. Every other byte stays. BC1 and BC7, and ETC2 and +/// ASTC 6x5, which a device without them holds in a carrier. +#[test] +fn compressed_blocks_copy_into_texels_of_their_bytes_and_back() { + use PixelFormat as P; + let messages = Messages::default(); + let cache = ScratchCache::new().unwrap(); + { + let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + let name = device.name().to_owned(); + let lane = Lane { + queue: device.new_command_queue().unwrap(), + device, + }; + let made = |pf: PixelFormat, width: u64, height: u64| { + let mut d = TextureDescriptor::texture_2d(pf, width, height, false); + d.usage = TextureUsage::SHADER_READ; + d.resource_options = ResourceOptions::new( + StorageMode::Private, + CpuCacheMode::DefaultCache, + HazardTrackingMode::Default, + ); + lane.device.new_texture(&d).unwrap() + }; + let cases: [(P, [u64; 2], P, usize); 4] = [ + (P::BC1RGBA, [4, 4], P::RG32Uint, 8), + (P::BC7RGBAUnorm, [4, 4], P::RGBA32Uint, 16), + (P::ETC2RGB8, [4, 4], P::RG32Uint, 8), + (P::ASTC6x5LDR, [6, 5], P::RGBA32Uint, 16), + ]; + for (c, [bw, bh], u, n) in cases { + let compressed = made(c, 8 * bw, 8 * bh); + let texels = made(u, 8, 8); + let blocks: Vec = (0..64).flat_map(|i| unit_bytes(i, 0x10, n)).collect(); + let words: Vec = (0..64).flat_map(|i| unit_bytes(i, 0x80, n)).collect(); + let row = 8 * n as u64; + let got = lane.run(|blit| { + for (texture, bytes, size) in [ + (&compressed, &blocks, Size::new(8 * bw, 8 * bh, 1)), + (&texels, &words, Size::new(8, 8, 1)), + ] { + blit.copy_from_buffer_to_texture( + &lane.buffer(bytes), + 0, + row, + 8 * row, + size, + texture, + 0, + 0, + Origin::new(0, 0, 0), + BlitOption::None, + )?; + } + blit.copy_from_texture_to_texture( + &compressed, + 0, + 0, + Origin::new(4, 4, 0), + Size::new(2, 2, 1), + &texels, + 0, + 0, + Origin::new(1, 2, 0), + )?; + blit.copy_from_texture_to_texture( + &texels, + 0, + 0, + Origin::new(1, 2, 0), + Size::new(2, 2, 1), + &compressed, + 0, + 0, + Origin::new(bw, bh, 0), + )?; + let mut out = Vec::new(); + for (texture, size) in [ + (&compressed, Size::new(8 * bw, 8 * bh, 1)), + (&texels, Size::new(8, 8, 1)), + ] { + let buffer = lane.buffer(&vec![0xee; 64 * n]); + blit.copy_from_texture_to_buffer( + texture, + 0, + 0, + Origin::new(0, 0, 0), + size, + &buffer, + 0, + row, + 8 * row, + BlitOption::None, + )?; + out.push((buffer, 64 * n)); + } + Ok(out) + }); + let at = |x: usize, y: usize| (8 * y + x) * n..(8 * y + x + 1) * n; + let mut want_blocks = blocks.clone(); + want_blocks[at(1, 1)].copy_from_slice(&words[at(0, 0)]); + let mut want_words = words.clone(); + for (x, y) in [(1, 2), (2, 2), (1, 3), (2, 3)] { + want_words[at(x, y)].copy_from_slice(&blocks[at(x + 3, y + 2)]); + } + assert_eq!( + got, + Ok(vec![want_blocks, want_words]), + "{c:?} with {u:?} on {name}" + ); + } + } + assert_eq!(messages.take(), Vec::new(), "the validation layer reported"); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/heap_layouts.rs b/crates/metal2vulkan-validation/src/runtime_lane/heap_layouts.rs index 5ba39eb29..f66f7c822 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/heap_layouts.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/heap_layouts.rs @@ -903,11 +903,15 @@ fn block_rows_lie_as_their_level_lays_them_out( return; }; let descriptor = row.descriptor(); - // A format the device has no image of is refused before any layout (lavapipe's ETC2 and - // EAC). + // A format the device has no image of is refused before any layout, and an ASTC texture + // on a device without ASTC (`RuntimeGap::DecodedHeapTexture`); an ETC2 or EAC texture on a + // device without them lies in a carrier of the same blocks (`etc.rs`). let answer = match device.heap_texture_size_and_align(&descriptor) { Ok(answer) => answer, - Err(error @ Error::Unsupported(_)) => { + Err( + error @ (Error::Unsupported(_) + | Error::NotImplemented(RuntimeGap::DecodedHeapTexture)), + ) => { eprintln!("HEAPLAYOUT {what}: refused {error:?}"); continue; } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/pvrtc_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/pvrtc_textures.rs index 515496c45..869dbe36a 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/pvrtc_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/pvrtc_textures.rs @@ -26,27 +26,37 @@ //! CFR-probe7-m4). //! - The runtime's gap, `NotImplemented(PvrtcBlockOrder)`: `replaceRegion` and `getBytes` of a //! region other than a whole level, which plain Metal places by no rule the runtime has found, -//! and of a whole level at another `bytesPerRow`, unmeasured. A kernel that reads the texture -//! is refused where the device has no format for it. -//! - Made resident for a kernel that reads texture handles from memory, such a texture takes the -//! neutral's place there, and the dispatch announces it once ([`UNREADABLE`]); a kernel that -//! reads no handles announces nothing. +//! and of a whole level at another `bytesPerRow`, unmeasured. +//! - Where the device has no format for it, its reads go through a decoded twin of its codes, +//! announced `carried-decoded-twin` once: every format's texels read exactly as Metal's +//! (`metal2vulkan::bind::PvrtcDecode`, matched against an Apple M3 Max by its own tests), and so +//! do its view's as the format's other colour space, after a CPU copy, a row-linear blit and a +//! copy from another texture, each decoded into the twin (a blit's by a GPU decode pass, a CPU +//! copy's by one or on the CPU, counted in `WorkCounts`; [`pvrtc_texels_read_as_metal_s`]). +//! - A texture held for copies alone (a 4:2:2 texture in a heap over the caller's host pages, which +//! keeps no decoded twin, as a PVRTC texture there keeps none), made resident for a kernel that +//! reads texture handles from memory, takes the neutral's place there, and the dispatch announces +//! it once ([`UNREADABLE`]); a kernel that reads no handles announces nothing. +use super::astc_textures::{read_whole, reader}; use super::case_making_kinds; -use super::degrade_notices::{assert_made_once, shared_in_system_memory}; +use super::degrade_notices::{assert_made_once, counts, shared_in_system_memory}; +use super::host_memory::Mapping; +use super::no_copy_heaps::{no_copy_heap, shared, HEAP}; use super::{ bound_buffers, encode_case, pipeline_state, public_case, read_buffer, validated_device, CaseResources, Messages, PublicCase, ScratchCache, WAIT, }; use crate::candidate::engine::ComputeOutput; use crate::gpu::TEST_DEVICE; -use metal2vulkan::bind::Dispatch; -use metal2vulkan::error::{BindError, Feature, Needs, Unsupported}; +use metal2vulkan::bind::PvrtcDecode; +use metal2vulkan::device::FormatUsage; +use metal2vulkan::metal::format::{vk_format, FormatEmulation}; use metal2vulkan::metal::{PixelFormat, ResourceUsage, TextureUsage}; use metal2vulkan_runtime::{ BlitCommandEncoder, BlitOption, Buffer, CommandBufferStatus, CommandQueue, CpuCacheMode, - Degradation, Device, Error, HazardTrackingMode, Origin, Region, ResourceOptions, RuntimeGap, - Size, StorageMode, Texture, TextureDescriptor, + Degradation, Device, Error, HazardTrackingMode, HeapType, Origin, Region, ResourceOptions, + RuntimeGap, Size, StorageMode, Texture, TextureDescriptor, }; /// The 4-bit PVRTC formats, which the runtime holds where the device has no format for them. @@ -67,9 +77,6 @@ const TWO_BIT: [PixelFormat; 4] = [ PixelFormat::PVRTCRGBA2BPPSRGB, ]; -/// A public case that samples textures in a kernel (`kernel_textures.rs`'s). -const SAMPLED: &str = "sample-each-of-three-textures-through-one-dynamic-array-index"; - /// A public case whose kernel reads texture handles from memory: it samples an unsigned texture /// through a sampler, both held in its argument buffer (`resource_ids.rs`'s). const HANDLES: &str = @@ -78,7 +85,7 @@ const HANDLES: &str = /// A public case whose kernel reads buffers alone. const BUFFERS: &str = "store-through-a-selected-base-and-test-a-nullable-pointer"; -/// The kind [`a_pvrtc_texture_a_kernel_s_handles_reach_is_announced_once`] takes. +/// The kind [`a_texture_held_for_copies_a_kernel_s_handles_reach_is_announced_once`] takes. pub(super) const UNREADABLE: [Degradation; 1] = [Degradation::UnreadableHandleTexture]; /// The option a PVRTC copy takes. @@ -991,12 +998,9 @@ fn gap(result: Result, what: &str) { } /// The runtime's block-order gap is refused `NotImplemented(PvrtcBlockOrder)`, recording -/// nothing: `replaceRegion` and `getBytes` of a region other than a whole level (EV -/// CFR-probe7-m4: plain Metal places its blocks by no rule the runtime has found) and of a whole -/// level at a padded `bytesPerRow` (unmeasured). A kernel that samples a PVRTC RGB texture is -/// refused at its dispatch with the format's refusal, recording nothing. +/// (unmeasured). #[test] -fn pvrtc_block_order_and_reads_are_refused_typed() { +fn pvrtc_block_order_is_refused_typed() { on_device(|lane| { for pf in FOUR_BIT.into_iter().chain(TWO_BIT) { let texture = lane.texture(pf, 32, 1, StorageMode::Shared); @@ -1016,81 +1020,182 @@ fn pvrtc_block_order_and_reads_are_refused_typed() { gap(texture.get_bytes(&mut out, pitch, 0, region, 0, 0), &what); } } - // A kernel sampling the texture: every texture slot of the case bound to a PVRTC - // texture. - let case = public_case(SAMPLED).unwrap(); - let pipeline = pipeline_state(&lane.device, &case).unwrap(); - let resources = CaseResources::new(&lane.device, &case).unwrap(); - let texture = lane.texture(PixelFormat::PVRTCRGB4BPP, 16, 1, StorageMode::Private); - let command_buffer = lane.queue.command_buffer().unwrap(); - let mut encoder = command_buffer.compute_command_encoder().unwrap(); - encoder.set_compute_pipeline_state(&pipeline).unwrap(); - for (&index, bytes) in &case.compute.buffers { - encoder - .set_buffer(Some(&lane.buffer(bytes)), 0, index) - .unwrap(); - } - for &index in resources.textures.keys() { - encoder.set_texture(Some(&texture), index).unwrap(); - } - for (&index, sampler) in &resources.samplers { - encoder.set_sampler_state(Some(sampler), index).unwrap(); - } - for (&index, &length) in &case.compute.threadgroup_lengths { - encoder - .set_threadgroup_memory_length(length, index) - .unwrap(); - } - let dispatched = match case.compute.dispatch { - Dispatch::Threads { - threads, - threads_per_group, - } => encoder.dispatch_threads(size(threads), size(threads_per_group)), - Dispatch::Threadgroups { - groups, - threads_per_group, - } => encoder.dispatch_threadgroups(size(groups), size(threads_per_group)), - other => panic!("{SAMPLED}: dispatch {other:?}"), + }); +} + +/// Whether `device` holds a texture of `pf` in its own PVRTC format, decoding it its own way, +/// rather than in a carrier with a decoded twin. +fn holds_pvrtc(device: &Device, pf: PixelFormat) -> bool { + let usage = [FormatUsage::SampledImage].into(); + vk_format(pf, &usage, device.compile_device().profile()) + .is_ok_and(|m| m.emulation == FormatEmulation::Direct) +} + +/// `n` bytes of a seeded xorshift: random blocks of every mode. +fn seeded(seed: u64, n: usize) -> Vec { + let mut x = seed | 1; + let mut out = Vec::with_capacity(n + 8); + while out.len() < n { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + out.extend_from_slice(&x.wrapping_mul(0x2545_f491_4f6c_dd1d).to_le_bytes()); + } + out.truncate(n); + out +} + +/// The form of a PVRTC format in the other colour space, its sRGB or linear twin. +fn other_space(pf: PixelFormat) -> PixelFormat { + use PixelFormat as P; + match pf { + P::PVRTCRGB2BPP => P::PVRTCRGB2BPPSRGB, + P::PVRTCRGB2BPPSRGB => P::PVRTCRGB2BPP, + P::PVRTCRGB4BPP => P::PVRTCRGB4BPPSRGB, + P::PVRTCRGB4BPPSRGB => P::PVRTCRGB4BPP, + P::PVRTCRGBA2BPP => P::PVRTCRGBA2BPPSRGB, + P::PVRTCRGBA2BPPSRGB => P::PVRTCRGBA2BPP, + P::PVRTCRGBA4BPP => P::PVRTCRGBA4BPPSRGB, + P::PVRTCRGBA4BPPSRGB => P::PVRTCRGBA4BPP, + other => panic!("{other:?} is no PVRTC format"), + } +} + +/// Every PVRTC format's texels read exactly as Metal's on a device without the format (the module +/// docs), through the texture and through its view as the other colour space: a new texture's +/// zero blocks, then a whole level's blocks a CPU copy wrote (in Metal's CPU order), a row-linear +/// blit from a buffer, and a copy from another texture, each read by a command buffer after the +/// write's. A device with the format reads through its own decode (not compared). +#[test] +fn pvrtc_texels_read_as_metal_s() { + super::degrade_notices::on_device(|device, messages| { + let name = device.name().to_owned(); + let state = reader(device); + let queue = device.new_command_queue().unwrap(); + let lane = Lane { + device: device.clone(), + queue, + messages: messages.clone(), }; - encoder.end_encoding().unwrap(); - let committed = command_buffer.commit(); - command_buffer.wait_until_completed_for(WAIT).unwrap(); - println!( - "a kernel sampling PVRTC_RGB_4BPP textures at {:?}: dispatch {dispatched:?}, commit \ - {committed:?}, status {:?}, error {:?}", - resources.textures.keys().collect::>(), - command_buffer.status(), - command_buffer.error() - ); - // The format's own refusal: no Vulkan format holds PVRTC RGB texels a shader reads. - assert!( - matches!( - dispatched, - Err(Error::Bind(BindError::Unsupported(Unsupported { - feature: Feature::Format, - needs: Needs::NotImplemented, - .. - }))) + let mut wrong = Vec::new(); + let mut undecoded = Vec::new(); + let mut twinned = false; + // The GPU decode passes and CPU decodes so far. + let decodes = |device: &Device| { + let counts = device.work_counts(); + (counts.block_decode_passes, counts.cpu_block_decodes) + }; + for (f, pf) in FOUR_BIT.into_iter().chain(TWO_BIT).enumerate() { + let native = holds_pvrtc(device, pf); + twinned |= !native; + let decode = PvrtcDecode::of(pf).unwrap(); + let [bw, bh] = decode.block_extent().map(u64::from); + let blocks = [16 / bw, 16 / bh]; + let bytes = (blocks[0] * blocks[1] * 8) as usize; + let mut check = |what: &str, texture: &Texture, rows: &[u8]| { + if native { + return; + } + let codes = decode.decode(rows, [16, 16, 1]); + let view = texture.new_texture_view(other_space(pf)).unwrap(); + for (read, through) in [(texture, pf), (&view, other_space(pf))] { + let as_read = PvrtcDecode::of(through).unwrap(); + let got = read_whole(device, &state, read); + for (t, got) in got.iter().enumerate() { + for (c, &got) in got.iter().enumerate() { + let want = as_read.metal_value(c, codes[4 * t + c]); + if got.to_bits() != want.to_bits() && wrong.len() < 24 { + wrong.push(format!( + "{pf:?} {what} read as {through:?}, texel {t} channel {c}: \ + {got} against Metal's {want}" + )); + } + } + } + } + }; + let texture = lane.texture(pf, 16, 1, StorageMode::Shared); + check("fresh", &texture, &vec![0; bytes]); + // A CPU copy of the whole level, its blocks in Metal's CPU order. + let rows = seeded(0x9e37_0000 + 0x10 * f as u64, bytes); + let mut cpu = vec![0; bytes]; + for (i, block) in rows.as_chunks::<8>().0.iter().enumerate() { + let (x, y) = (i as u64 % blocks[0], i as u64 / blocks[0]); + let at = cpu_order(x, y, blocks) as usize * 8; + cpu[at..at + 8].copy_from_slice(block); + } + let before = decodes(device); + texture.replace_region(whole(16), 0, 0, &cpu, 0, 0).unwrap(); + check("CPU copy", &texture, &rows); + if !native && decodes(device) == before { + undecoded.push(format!("{pf:?} CPU copy: neither a pass nor a CPU decode")); + } + // A row-linear blit from a buffer, then a copy into another texture. + let blitted = seeded(0x9e37_0001 + 0x10 * f as u64, bytes); + let before = decodes(device); + let row = blocks[0] * 8; + lane.run(|blit| { + lane.put(blit, &texture, &blitted, At::rows(whole(16), row))?; + Ok(Vec::new()) + }) + .unwrap(); + check("blit", &texture, &blitted); + let copy = lane.texture(pf, 16, 1, StorageMode::Private); + lane.run(|blit| { + let at = Origin::new(0, 0, 0); + let size = Size::new(16, 16, 1); + blit.copy_from_texture_to_texture(&texture, 0, 0, at, size, ©, 0, 0, at)?; + Ok(Vec::new()) + }) + .unwrap(); + check("texture copy", ©, &blitted); + // Each blit's decode is a GPU pass. + let after = decodes(device); + if !native && after.0 < before.0 + 2 { + undecoded.push(format!( + "{pf:?} blits: GPU decode passes {before:?} -> {after:?}" + )); + } + } + assert!(wrong.is_empty(), "on {name}:\n{}", wrong.join("\n")); + assert!(undecoded.is_empty(), "on {name}:\n{}", undecoded.join("\n")); + let counts = counts(&messages.take_notices()); + let announced = |kind| counts.get(&kind).copied().unwrap_or(0); + assert_eq!( + ( + announced(Degradation::CarriedDecodedTwin), + announced(Degradation::DecodedTexelPrecision) ), - "{dispatched:?}" + (usize::from(twinned), 0), + "on {name}" ); }); } -/// A size of three axes. -fn size(axes: [u32; 3]) -> Size { - Size::new(axes[0].into(), axes[1].into(), axes[2].into()) -} - -/// A PVRTC RGB texture, whose blocks a carrier holds, made resident for a kernel that reads no -/// texture handles changes nothing and announces nothing. Made resident for a kernel that reads -/// texture handles from memory, it changes nothing the kernel reads through its own handle (its -/// element is the neutral texture), and the dispatch announces -/// [`Degradation::UnreadableHandleTexture`] once over two command buffers. +/// A 4:2:2 texture in a heap over the caller's host pages, whose texels a carrier holds for copies +/// alone (it keeps no decoded twin, as a PVRTC texture's blocks there keep none), made resident +/// for a kernel that reads no texture handles changes nothing and announces nothing. Made resident +/// for a kernel that reads texture handles from memory, it changes nothing the kernel reads +/// through its own handle (its element is the neutral texture), and the dispatch announces +/// [`Degradation::UnreadableHandleTexture`] once over two command buffers. The kernel samples an +/// unsigned texture and the 4:2:2 texture's class is a float one (`RGBX8Unorm`'s), so the element +/// is the neutral by class as well: [`Degradation::CrossClassTextureNeutral`], also once. Nothing +/// where the device imports no host memory. #[test] -fn a_pvrtc_texture_a_kernel_s_handles_reach_is_announced_once() { +fn a_texture_held_for_copies_a_kernel_s_handles_reach_is_announced_once() { on_device(|lane| { - let pvrtc = lane.texture(PixelFormat::PVRTCRGB4BPP, 16, 1, StorageMode::Private); + let pages = Mapping::anonymous(HEAP); + // SAFETY: the mapping holds `HEAP` writable bytes and outlives the heap, dropped after it. + let made = + unsafe { no_copy_heap(&lane.device, pages.pointer(), HeapType::Placement, None) }; + let Some(heap) = made else { + return; + }; + let mut held = descriptor(PixelFormat::GBGR422, 16, 1, StorageMode::Shared); + held.resource_options = shared(); + let pvrtc = heap.new_texture_at_offset(&held, 0).unwrap(); + // What the heap and its texture announce is theirs. + drop(lane.messages.take_notices()); // Beside the dispatches' own kind, what their steps force: the case's pipeline state's // making, and the `Shared` buffers' system memory. let forced = |case| { @@ -1109,6 +1214,8 @@ fn a_pvrtc_texture_a_kernel_s_handles_reach_is_announced_once() { for _ in 0..2 { assert_eq!(lane.dispatch(&handles, Some(&pvrtc)), alone, "{HANDLES}"); } - assert_made_once(&lane.messages, &UNREADABLE, &forced(&handles)); + let mut kinds = forced(&handles); + kinds.insert(Degradation::CrossClassTextureNeutral); + assert_made_once(&lane.messages, &UNREADABLE, &kinds); }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/texture_blits.rs b/crates/metal2vulkan-validation/src/runtime_lane/texture_blits.rs index ed01fea94..af1d95df0 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/texture_blits.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/texture_blits.rs @@ -8,7 +8,7 @@ use super::degrade_notices::{assert_made_once, assert_once, forced, loses_depth_denormals}; use super::degrade_notices::{decodes_blocks_its_way, shared_in_system_memory}; -use super::degrade_notices::{twins_blocks, twins_depth}; +use super::degrade_notices::{twins_blocks, twins_carried, twins_depth}; use super::{validated_device, Messages, ScratchCache}; use crate::gpu::TEST_DEVICE; use metal2vulkan::bind::{MipmapFilterChain, MipmapRule}; @@ -1577,6 +1577,14 @@ fn mipmaps_of_every_format_run_or_are_refused_typed() { pf == PixelFormat::Depth32Float && twins_depth(&device), ), (Degradation::DecodedBlockTwin, twins_blocks(&device, pf)), + ( + Degradation::CarriedDecodedTwin, + twins_carried(&device, pf)[0], + ), + ( + Degradation::DecodedTexelPrecision, + twins_carried(&device, pf)[1], + ), ( Degradation::CompressedTexelDecode, decodes_blocks_its_way(&device, pf), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/texture_fills.rs b/crates/metal2vulkan-validation/src/runtime_lane/texture_fills.rs index f94e220ad..e443c8941 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/texture_fills.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/texture_fills.rs @@ -22,7 +22,9 @@ //! their own memory replay `tfl4.swift` (EV XRR2-fill4-m4) the same way, 5 and 8 texels wide. use super::degrade_notices::{assert_made_once, forced, loses_depth_denormals, on_device}; -use super::degrade_notices::{decodes_blocks_its_way, shared_in_system_memory, twins_blocks}; +use super::degrade_notices::{ + decodes_blocks_its_way, shared_in_system_memory, twins_blocks, twins_carried, +}; use super::degrade_notices::{twins_depth, UNPACKED_FILL}; use super::extended_range_two_planes::{get, put}; use super::texture_blits::depth_images; @@ -586,6 +588,14 @@ fn texture_fills_write_metal_s_bytes() { let first = forced(&[ (Degradation::DepthTwin, twin), (Degradation::DecodedBlockTwin, twins_blocks(device, pf)), + ( + Degradation::CarriedDecodedTwin, + twins_carried(device, pf)[0], + ), + ( + Degradation::DecodedTexelPrecision, + twins_carried(device, pf)[1], + ), ( Degradation::CompressedTexelDecode, decodes_blocks_its_way(device, pf), diff --git a/crates/metal2vulkan/src/bind/astc_decode.rs b/crates/metal2vulkan/src/bind/astc_decode.rs new file mode 100644 index 000000000..2915a81ab --- /dev/null +++ b/crates/metal2vulkan/src/bind/astc_decode.rs @@ -0,0 +1,1094 @@ +//! An ASTC LDR texture's texels as Metal decodes them, from its blocks, for a device without +//! ASTC: the texels a decoded twin of the texture holds (the runtime's `texture/decoded_twin.rs`). +//! +//! **The decode** is the Khronos Data Format Specification's (its ASTC chapter): the block mode, +//! the integer sequence encoding of the colour endpoints and the weights, the colour endpoint +//! modes, the partition function and the weight grid's infill, written here from the +//! specification. Each channel of a texel comes out as its 16-bit interpolation result `C` of the +//! two 8-bit endpoints widened to 16 bits (`e · 257`, or `e · 256 + 128` for an `_sRGB` format). +//! +//! **Metal's answers** (an Apple M3 Max under macOS 27.0.1, our own probe: 4096 blocks of each of +//! the fourteen footprints, about 70% valid blocks of random modes, void-extent blocks and error +//! blocks, every texel read as `float` and `half` and sampled at its centre, linear and sRGB, +//! every channel equal to this decode's): +//! +//! - **Linear:** each channel reads `(C >> 4) / 4095`, a 12-bit value, correctly rounded to `f32` +//! (a `half` read rounds that to nearest even). +//! - **sRGB:** each colour channel reads Metal's twelve-bit table of the code `C >> 8` +//! (`k / 4095` for `lower::arith::srgb`'s step `k`), alpha `(C >> 8) / 255`. +//! - **Error blocks** read magenta, `(1, 0, 1, 1)`: a reserved block mode, a weight grid larger +//! than the block, more than 64 weights, fewer than 24 or more than 96 weight bits, two planes +//! of four partitions, more than 18 colour values, too few bits for a colour range of 6 levels, +//! an HDR void-extent block, a void-extent block whose reserved bits (10 and 11) are not both +//! set or whose extent is empty. A partition of an HDR colour endpoint mode reads magenta at its +//! own texels, the block's other partitions decoding as they are. +//! - A void-extent block's texels are its four 16-bit values, as `C`. +//! +//! **The twin's texels** ([`AstcTexels`]): [`AstcTexels::Float`] holds each texel's value exactly +//! (`R32G32B32A32_SFLOAT`); [`AstcTexels::Unorm8`] holds 8-bit codes (`R8G8B8A8_UNORM`): a linear +//! channel the code nearest its value, at most `1/510` off it, and an sRGB format's channels the +//! code `C >> 8` itself, which a function reads raw through the image's `R8G8B8A8_UNORM` view and +//! decodes through Metal's table (`metal::texel_format::srgb_raw_on`), exactly. The runtime holds +//! an sRGB format's twin in those codes whatever its policy. +//! +//! **The GPU's decode** ([`astc_decode_module`]) is this decode in integer operations, each +//! texel's from its block alone, writing the texels [`decode`](AstcDecode::decode) writes; its +//! bindings, shape and dispatch are the block decode's ([`BlockDecodeModule`]), its blocks and +//! texels laid out as [`decode`](AstcDecode::decode)'s are. + +use std::sync::OnceLock; + +use super::block_decode::{decode_module, BlockDecodeModule}; +use crate::device::Device; +use crate::error::Error; +use crate::lower::arith::srgb::SRGB_DECODE_STEPS; +use crate::metal::PixelFormat; +use crate::vk::Format; + +mod kernel; + +/// The module of `device` that decodes `decode`'s blocks into the texels of `texels` on the GPU +/// (the module docs): the bindings, shape and dispatch of [`BlockDecodeModule`], of which it +/// reads the shape's first three words (the region's width, height and depth), its blocks +/// `decode`'s, `⌈width / w⌉` across and `⌈height / h⌉` down of each layer for the footprint +/// `w` x `h`. +pub fn astc_decode_module( + device: &Device, + decode: AstcDecode, + texels: AstcTexels, +) -> Result { + decode_module(device, kernel::typed_module(decode, texels)?, "ASTC decode") +} + +/// How an ASTC LDR format's blocks decode: its footprint and whether its colour is sRGB-encoded. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct AstcDecode { + /// The block's texels across. + pub width: u32, + /// The block's texels down. + pub height: u32, + /// Whether the format is an `_sRGB` one. + pub srgb: bool, +} + +/// The texels a decoded twin of an ASTC texture holds (the module docs). +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum AstcTexels { + /// `R8G8B8A8_UNORM` codes: a linear channel the code nearest Metal's 12-bit value (at most + /// `1/510` off it), an sRGB format's channels Metal's own codes, which a function reads raw + /// and decodes through Metal's table. + Unorm8, + /// `R32G32B32A32_SFLOAT`: each channel Metal's value exactly. + Float, +} + +/// The 2D footprints Vulkan's ASTC formats have, in Metal's raw-value order. +const FOOTPRINTS: [[u32; 2]; 14] = [ + [4, 4], + [5, 4], + [5, 5], + [6, 5], + [6, 6], + [8, 5], + [8, 6], + [8, 8], + [10, 5], + [10, 6], + [10, 8], + [10, 10], + [12, 10], + [12, 12], +]; + +/// The most texels a block holds (12 x 12). +const MOST_TEXELS: usize = 144; + +impl AstcDecode { + /// The bytes of every block. + pub const BLOCK_BYTES: u32 = 16; + + /// The decode of `pf`'s blocks: the ASTC LDR formats of the fourteen 2D footprints and their + /// `_sRGB` forms; `None` for every other format (the HDR ones, and Apple's 4x2 and 8x4 + /// footprints, included). + pub fn of(pf: PixelFormat) -> Option { + use PixelFormat as P; + let (srgb, index) = match pf { + P::ASTC4x4SRGB => (true, 0), + P::ASTC5x4SRGB => (true, 1), + P::ASTC5x5SRGB => (true, 2), + P::ASTC6x5SRGB => (true, 3), + P::ASTC6x6SRGB => (true, 4), + P::ASTC8x5SRGB => (true, 5), + P::ASTC8x6SRGB => (true, 6), + P::ASTC8x8SRGB => (true, 7), + P::ASTC10x5SRGB => (true, 8), + P::ASTC10x6SRGB => (true, 9), + P::ASTC10x8SRGB => (true, 10), + P::ASTC10x10SRGB => (true, 11), + P::ASTC12x10SRGB => (true, 12), + P::ASTC12x12SRGB => (true, 13), + P::ASTC4x4LDR => (false, 0), + P::ASTC5x4LDR => (false, 1), + P::ASTC5x5LDR => (false, 2), + P::ASTC6x5LDR => (false, 3), + P::ASTC6x6LDR => (false, 4), + P::ASTC8x5LDR => (false, 5), + P::ASTC8x6LDR => (false, 6), + P::ASTC8x8LDR => (false, 7), + P::ASTC10x5LDR => (false, 8), + P::ASTC10x6LDR => (false, 9), + P::ASTC10x8LDR => (false, 10), + P::ASTC10x10LDR => (false, 11), + P::ASTC12x10LDR => (false, 12), + P::ASTC12x12LDR => (false, 13), + _ => return None, + }; + let [width, height] = FOOTPRINTS[index]; + Some(AstcDecode { + width, + height, + srgb, + }) + } + + /// The block's footprint, texels across and down. + pub fn block_extent(self) -> [u32; 2] { + [self.width, self.height] + } + + /// The Vulkan format of the twin's texels of `texels`: `R8G8B8A8_UNORM` (an sRGB format's + /// viewed as `R8G8B8A8_SRGB` too, where its linear samples are the device's filter) or + /// `R32G32B32A32_SFLOAT`. + pub fn texel_format(self, texels: AstcTexels) -> Format { + match texels { + AstcTexels::Unorm8 => Format::R8G8B8A8_UNORM, + AstcTexels::Float => Format::R32G32B32A32_SFLOAT, + } + } + + /// The Metal pixel format whose texels the twin's of `texels` are: `RGBA8Unorm` or + /// `RGBA32Float`. + pub fn texel_pixel_format(self, texels: AstcTexels) -> PixelFormat { + match texels { + AstcTexels::Unorm8 => PixelFormat::RGBA8Unorm, + AstcTexels::Float => PixelFormat::RGBA32Float, + } + } + + /// The bytes of a twin's texel of `texels`: 4 or 16. + pub fn texel_bytes(texels: AstcTexels) -> u32 { + match texels { + AstcTexels::Unorm8 => 4, + AstcTexels::Float => 16, + } + } + + /// The block's texels, each channel's 16-bit interpolation result `C` (red, green, blue, + /// alpha), row-major; `None` for an error block (whose texels read magenta). + pub fn block_values(self, block: &[u8; 16]) -> Option> { + self.block_values_why(block).ok() + } + + /// [`block_values`](Self::block_values), with why a block is an error block. + pub(crate) fn block_values_why(self, block: &[u8; 16]) -> Result, Illegal> { + let mut out = [[0; 4]; MOST_TEXELS]; + decode_block(self, u128::from_le_bytes(*block), &mut out)?; + Ok(out[..(self.width * self.height) as usize].to_vec()) + } + + /// The `float` channels Metal reads of a texel whose 16-bit interpolation results are `c` + /// (the module docs). + pub fn metal_value(self, c: [u16; 4]) -> [f32; 4] { + let table = twelve_bit_values(); + std::array::from_fn(|ch| match (self.srgb, ch) { + (true, 3) => (f64::from(c[ch] >> 8) / 255.0) as f32, + (true, _) => table[usize::from(SRGB_DECODE_STEPS[usize::from(c[ch] >> 8)])], + (false, _) => table[usize::from(c[ch] >> 4)], + }) + } + + /// The twin's texel of `texels` of a texel whose 16-bit interpolation results are `c`, its + /// bytes in `out` ([`texel_bytes`](Self::texel_bytes) of them). + fn twin_texel(self, texels: AstcTexels, c: [u16; 4], out: &mut [u8]) { + match texels { + AstcTexels::Unorm8 => { + for (byte, c) in out.iter_mut().zip(c) { + *byte = match self.srgb { + true => (c >> 8) as u8, + // The code nearest `k / 4095`: no `k` lies on a half code. + false => ((u32::from(c >> 4) * 255 + 2047) / 4095) as u8, + }; + } + } + AstcTexels::Float => { + for (word, value) in out + .as_chunks_mut::<4>() + .0 + .iter_mut() + .zip(self.metal_value(c)) + { + *word = value.to_le_bytes(); + } + } + } + } + + /// The twin's texels of `texels` of a region `width` x `height` x `depth` whose `blocks` are + /// laid out as a copy of the region out of the texture lays them (tight rows of blocks, each + /// image's after the last), laid out as a copy into the twin reads them. + pub fn decode(self, texels: AstcTexels, blocks: &[u8], size: [u32; 3]) -> Vec { + let [width, height, depth] = size.map(|axis| axis as usize); + let bytes = AstcDecode::texel_bytes(texels) as usize; + let mut out = vec![0; width * height * depth * bytes]; + self.decode_into(texels, blocks, size, &mut out); + out + } + + /// [`decode`](Self::decode) into `out`, which holds exactly the region's texels: so bands of a + /// region's block rows can be decoded on several threads into one buffer. + /// + /// # Panics + /// + /// Where `blocks` holds fewer blocks than the region, or `out` another length. + pub fn decode_into( + self, + texels: AstcTexels, + blocks: &[u8], + [width, height, depth]: [u32; 3], + out: &mut [u8], + ) { + let (bw, bh) = (self.width as usize, self.height as usize); + let (width, height) = (width as usize, height as usize); + let (across, down) = (width.div_ceil(bw), height.div_ceil(bh)); + let bytes = AstcDecode::texel_bytes(texels) as usize; + let row = width * bytes; + assert_eq!( + out.len(), + row * height * depth as usize, + "the region's texels" + ); + let mut values = [[0u16; 4]; MOST_TEXELS]; + for b in 0..across * down * depth as usize { + let block: [u8; 16] = blocks[b * 16..b * 16 + 16] + .try_into() + .expect("a block's 16 bytes"); + if decode_block(self, u128::from_le_bytes(block), &mut values).is_err() { + values.fill(ERROR_TEXEL); + } + let (z, by, bx) = (b / (across * down), b / across % down, b % across); + for (ty, y) in (by * bh..(by * bh + bh).min(height)).enumerate() { + for (tx, x) in (bx * bw..(bx * bw + bw).min(width)).enumerate() { + let at = (z * height + y) * row + x * bytes; + self.twin_texel(texels, values[ty * bw + tx], &mut out[at..at + bytes]); + } + } + } + } +} + +/// `k / 4095` correctly rounded to `f32`, for every 12-bit `k`. (`k / 4095` lies on no `f32` +/// tie, so rounding its `f64` quotient once more is the correctly rounded `f32`.) +fn twelve_bit_values() -> &'static [f32; 4096] { + static TABLE: OnceLock<[f32; 4096]> = OnceLock::new(); + TABLE.get_or_init(|| std::array::from_fn(|k| (k as f64 / 4095.0) as f32)) +} + +/// Why a block is an error block (the module docs). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Illegal { + ReservedMode, + GridPastBlock, + TooManyWeights, + WeightBits, + DualPlaneFourPartitions, + ConfigPastWeights, + ColorPastWeights, + TooManyValues, + NoColorRange, + HdrVoidExtent, + VoidExtentReserved, + VoidExtentEmpty, +} + +/// The error colour's 16-bit values: magenta. +const ERROR_TEXEL: [u16; 4] = [0xFFFF, 0, 0xFFFF, 0xFFFF]; + +// --------------------------------------------------------------------------------------------- +// The integer sequence encoding. + +/// A range of values the integer sequence encoding holds: `levels` values, `bits` low bits each +/// and a trit (3), a quint (5) or neither (1) on top. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Range { + bits: u32, + /// 1, 3 or 5. + base: u32, +} + +impl Range { + const fn levels(self) -> u32 { + self.base << self.bits + } + + /// The bits `count` values of the range take. + const fn ise_bits(self, count: u32) -> u32 { + count * self.bits + + match self.base { + 3 => (8 * count).div_ceil(5), + 5 => (7 * count).div_ceil(3), + _ => 0, + } + } +} + +const fn r(base: u32, bits: u32) -> Range { + Range { bits, base } +} + +/// Every range, by their levels: 2, 3, 4, 5, 6, 8, 10, 12, 16, 20, 24, 32, 40, 48, 64, 80, 96, +/// 128, 160, 192 and 256. +const RANGES: [Range; 21] = [ + r(1, 1), + r(3, 0), + r(1, 2), + r(5, 0), + r(3, 1), + r(1, 3), + r(5, 1), + r(3, 2), + r(1, 4), + r(5, 2), + r(3, 3), + r(1, 5), + r(5, 3), + r(3, 4), + r(1, 6), + r(5, 4), + r(3, 5), + r(1, 7), + r(5, 5), + r(3, 6), + r(1, 8), +]; + +/// The five trits of a trit block's 8 bits `t`. +fn trits(t: u32) -> [u32; 5] { + let bit = |v: u32, i: u32| (v >> i) & 1; + let (c, t4, t3); + if (t >> 2) & 7 == 7 { + c = ((t >> 5) & 7) << 2 | (t & 3); + t4 = 2; + t3 = 2; + } else { + c = t & 0x1F; + if (t >> 5) & 3 == 3 { + t4 = 2; + t3 = bit(t, 7); + } else { + t4 = bit(t, 7); + t3 = (t >> 5) & 3; + } + } + let (t2, t1, t0); + if c & 3 == 3 { + t2 = 2; + t1 = bit(c, 4); + t0 = bit(c, 3) << 1 | (bit(c, 2) & !bit(c, 3) & 1); + } else if (c >> 2) & 3 == 3 { + t2 = 2; + t1 = 2; + t0 = c & 3; + } else { + t2 = bit(c, 4); + t1 = (c >> 2) & 3; + t0 = bit(c, 1) << 1 | (bit(c, 0) & !bit(c, 1) & 1); + } + [t0, t1, t2, t3, t4] +} + +/// The three quints of a quint block's 7 bits `q`. +fn quints(q: u32) -> [u32; 3] { + let bit = |v: u32, i: u32| (v >> i) & 1; + if (q >> 1) & 3 == 3 && (q >> 5) & 3 == 0 { + let q2 = bit(q, 0) << 2 | (bit(q, 4) & !bit(q, 0) & 1) << 1 | (bit(q, 3) & !bit(q, 0) & 1); + return [4, 4, q2]; + } + let (q2, c); + if (q >> 1) & 3 == 3 { + q2 = 4; + c = ((q >> 3) & 3) << 3 | (!(q >> 5) & 3) << 1 | bit(q, 0); + } else { + q2 = (q >> 5) & 3; + c = q & 0x1F; + } + let (q1, q0) = match c & 7 == 5 { + true => (4, (c >> 3) & 3), + false => ((c >> 3) & 3, c & 7), + }; + [q0, q1, q2] +} + +/// `count` values of `range` from the stream `stream` (its bits past the encoding's are zero), +/// each the trit or quint times `2^bits` plus its low bits. +fn ise_decode(stream: u128, range: Range, count: usize, out: &mut [u32]) { + let n = range.bits; + let mut at = 0u32; + let mut take = |width: u32| -> u32 { + let v = ((stream >> at) as u32) & ((1u32 << width) - 1); + at += width; + v + }; + match range.base { + 3 => { + for group in 0..count.div_ceil(5) { + let mut m = [0u32; 5]; + let mut t = 0; + m[0] = take(n); + t |= take(2); + m[1] = take(n); + t |= take(2) << 2; + m[2] = take(n); + t |= take(1) << 4; + m[3] = take(n); + t |= take(2) << 5; + m[4] = take(n); + t |= take(1) << 7; + let tr = trits(t); + for k in 0..5 { + if let Some(slot) = out.get_mut(group * 5 + k).filter(|_| group * 5 + k < count) + { + *slot = tr[k] << n | m[k]; + } + } + } + } + 5 => { + for group in 0..count.div_ceil(3) { + let mut m = [0u32; 3]; + let mut q = 0; + m[0] = take(n); + q |= take(3); + m[1] = take(n); + q |= take(2) << 3; + m[2] = take(n); + q |= take(2) << 5; + let qu = quints(q); + for k in 0..3 { + if let Some(slot) = out.get_mut(group * 3 + k).filter(|_| group * 3 + k < count) + { + *slot = qu[k] << n | m[k]; + } + } + } + } + _ => { + for slot in out.iter_mut().take(count) { + *slot = take(n); + } + } + } +} + +/// The `bits` bits of `block` from bit `start`. +fn field(block: u128, start: u32, bits: u32) -> u128 { + if bits == 0 { + return 0; + } + (block >> start) & (u128::MAX >> (128 - bits)) +} + +// --------------------------------------------------------------------------------------------- +// Unquantization. + +/// A colour endpoint value `v` of `range` unquantized to 0 to 255. +fn unquantize_color(range: Range, v: u32) -> u32 { + if range.base == 1 { + // Replicate the bits up to 8. + let n = range.bits; + let mut out = 0; + let mut have = 0; + while have < 8 { + let shift = 8 - have; + out |= if shift >= n { + v << (shift - n) + } else { + v >> (n - shift) + }; + have += n; + } + return out & 0xFF; + } + let n = range.bits; + let d = v >> n; + let m = v & ((1 << n) - 1); + let bit = |i: u32| (m >> i) & 1; + let a = if m & 1 == 1 { 0x1FF } else { 0 }; + let (b, c) = match (range.base, n) { + (3, 1) => (0, 204), + (3, 2) => { + let b = bit(1); + // b000b0bb0 + (b << 8 | b << 4 | b << 2 | b << 1, 93) + } + (3, 3) => { + let (b, c) = (bit(1), bit(2)); + // cb000cbcb + (c << 8 | b << 7 | c << 3 | b << 2 | c << 1 | b, 44) + } + (3, 4) => { + let (b, c, d) = (bit(1), bit(2), bit(3)); + // dcb000dcb + (d << 8 | c << 7 | b << 6 | d << 2 | c << 1 | b, 22) + } + (3, 5) => { + let (b, c, d, e) = (bit(1), bit(2), bit(3), bit(4)); + // edcb000ed + (e << 8 | d << 7 | c << 6 | b << 5 | e << 1 | d, 11) + } + (3, 6) => { + let (b, c, d, e, f) = (bit(1), bit(2), bit(3), bit(4), bit(5)); + // fedcb000f + (f << 8 | e << 7 | d << 6 | c << 5 | b << 4 | f, 5) + } + (5, 1) => (0, 113), + (5, 2) => { + let b = bit(1); + // b0000bb00 + (b << 8 | b << 3 | b << 2, 54) + } + (5, 3) => { + let (b, c) = (bit(1), bit(2)); + // cb0000cbc + (c << 8 | b << 7 | c << 2 | b << 1 | c, 26) + } + (5, 4) => { + let (b, c, d) = (bit(1), bit(2), bit(3)); + // dcb0000dc + (d << 8 | c << 7 | b << 6 | d << 1 | c, 13) + } + (5, 5) => { + let (b, c, d, e) = (bit(1), bit(2), bit(3), bit(4)); + // edcb0000e + (e << 8 | d << 7 | c << 6 | b << 5 | e, 6) + } + _ => unreachable!("colour endpoints take 6 levels or more"), + }; + let t = (d * c + b) ^ a; + (a & 0x80) | (t >> 2) +} + +/// A weight `v` of `range` unquantized to 0 to 64. +fn unquantize_weight(range: Range, v: u32) -> u32 { + let t = if range.base == 1 { + let n = range.bits; + let mut out = 0; + let mut have = 0; + while have < 6 { + let shift = 6 - have; + out |= if shift >= n { + v << (shift - n) + } else { + v >> (n - shift) + }; + have += n; + } + out & 0x3F + } else { + let n = range.bits; + let d = v >> n; + let m = v & ((1 << n) - 1); + match (range.base, n) { + (3, 0) => [0, 32, 63][d as usize], + (5, 0) => [0, 16, 32, 47, 63][d as usize], + _ => { + let bit = |i: u32| (m >> i) & 1; + let a = if m & 1 == 1 { 0x7F } else { 0 }; + let (b, c) = match (range.base, n) { + (3, 1) => (0, 50), + (3, 2) => { + let b = bit(1); + // b000b0b + (b << 6 | b << 2 | b, 23) + } + (3, 3) => { + let (b, c) = (bit(1), bit(2)); + // cb000cb + (c << 6 | b << 5 | c << 1 | b, 11) + } + (5, 1) => (0, 28), + (5, 2) => { + let b = bit(1); + // b0000b0 + (b << 6 | b << 1, 13) + } + _ => unreachable!("weights take 32 levels or fewer"), + }; + let t = (d * c + b) ^ a; + (a & 0x20) | (t >> 2) + } + } + }; + if t > 32 { + t + 1 + } else { + t + } +} + +// --------------------------------------------------------------------------------------------- +// Colour endpoints. + +/// Moves a bit from `a` (the offset) to `b` (the base): `a` becomes a signed 6-bit offset. +fn bit_transfer_signed(a: i32, b: i32) -> (i32, i32) { + let b = (b >> 1) | (a & 0x80); + let mut a = (a >> 1) & 0x3F; + if a & 0x20 != 0 { + a -= 0x40; + } + (a, b) +} + +fn blue_contract(r: i32, g: i32, b: i32, a: i32) -> [i32; 4] { + [(r + b) >> 1, (g + b) >> 1, b, a] +} + +fn clamp8(e: [i32; 4]) -> [u32; 4] { + e.map(|c| c.clamp(0, 255) as u32) +} + +/// The two 8-bit endpoints of an LDR colour endpoint mode `cem` from its unquantized values `v`; +/// `None` for an HDR mode. +fn endpoints(cem: u32, v: &[i32; 8]) -> Option<[[u32; 4]; 2]> { + let u = |i: usize| v[i] as u32; + Some(match cem { + 0 => [[u(0), u(0), u(0), 255], [u(1), u(1), u(1), 255]], + 1 => { + let l0 = (v[0] >> 2) | (v[1] & 0xC0); + let l1 = (l0 + (v[1] & 0x3F)).min(255); + let (l0, l1) = (l0 as u32, l1 as u32); + [[l0, l0, l0, 255], [l1, l1, l1, 255]] + } + 4 => [[u(0), u(0), u(0), u(2)], [u(1), u(1), u(1), u(3)]], + 5 => { + let (o1, b0) = bit_transfer_signed(v[1], v[0]); + let (o3, b2) = bit_transfer_signed(v[3], v[2]); + [ + clamp8([b0, b0, b0, b2]), + clamp8([b0 + o1, b0 + o1, b0 + o1, b2 + o3]), + ] + } + 6 | 10 => { + let (a0, a1) = match cem { + 10 => (u(4), u(5)), + _ => (255, 255), + }; + let scaled = |i: usize| ((v[i] * v[3]) >> 8) as u32; + [ + [scaled(0), scaled(1), scaled(2), a0], + [u(0), u(1), u(2), a1], + ] + } + 8 | 12 => { + let (a0, a1) = match cem { + 12 => (v[6], v[7]), + _ => (255, 255), + }; + if v[1] + v[3] + v[5] >= v[0] + v[2] + v[4] { + [ + clamp8([v[0], v[2], v[4], a0]), + clamp8([v[1], v[3], v[5], a1]), + ] + } else { + [ + clamp8(blue_contract(v[1], v[3], v[5], a1)), + clamp8(blue_contract(v[0], v[2], v[4], a0)), + ] + } + } + 9 | 13 => { + let (o1, b0) = bit_transfer_signed(v[1], v[0]); + let (o3, b2) = bit_transfer_signed(v[3], v[2]); + let (o5, b4) = bit_transfer_signed(v[5], v[4]); + let (o7, b6) = match cem { + 13 => bit_transfer_signed(v[7], v[6]), + _ => (0, 255), + }; + if o1 + o3 + o5 >= 0 { + [ + clamp8([b0, b2, b4, b6]), + clamp8([b0 + o1, b2 + o3, b4 + o5, b6 + o7]), + ] + } else { + [ + clamp8(blue_contract(b0 + o1, b2 + o3, b4 + o5, b6 + o7)), + clamp8(blue_contract(b0, b2, b4, b6)), + ] + } + } + // 2, 3, 7, 11, 14 and 15: HDR modes. + _ => return None, + }) +} + +// --------------------------------------------------------------------------------------------- +// Partitions. + +fn hash52(mut p: u32) -> u32 { + p ^= p >> 15; + p = p.wrapping_sub(p << 17); + p = p.wrapping_add(p << 7); + p = p.wrapping_add(p << 4); + p ^= p >> 5; + p = p.wrapping_add(p << 16); + p ^= p >> 7; + p ^= p >> 3; + p ^= p << 6; + p ^= p >> 17; + p +} + +/// The partition function of a block: its partition index `seed`, its partition count and +/// whether the block is small (fewer than 31 texels), worked out once for its texels. +struct Partitions { + /// The twelve seeds, squared and shifted. + s: [u32; 12], + /// The hash. + rnum: u32, + count: u32, + small: bool, +} + +impl Partitions { + fn new(seed: u32, count: u32, texels: u32) -> Partitions { + let seed = seed + (count - 1) * 1024; + let rnum = hash52(seed); + let mut s = [ + rnum & 0xF, + (rnum >> 4) & 0xF, + (rnum >> 8) & 0xF, + (rnum >> 12) & 0xF, + (rnum >> 16) & 0xF, + (rnum >> 20) & 0xF, + (rnum >> 24) & 0xF, + (rnum >> 28) & 0xF, + (rnum >> 18) & 0xF, + (rnum >> 22) & 0xF, + (rnum >> 26) & 0xF, + rnum.rotate_left(2) & 0xF, + ]; + let (sh1, sh2) = match seed & 1 { + 1 => ( + if seed & 2 != 0 { 4 } else { 5 }, + if count == 3 { 6 } else { 5 }, + ), + _ => ( + if count == 3 { 6 } else { 5 }, + if seed & 2 != 0 { 4 } else { 5 }, + ), + }; + let sh3 = if seed & 0x10 != 0 { sh1 } else { sh2 }; + for (i, v) in s.iter_mut().enumerate() { + *v *= *v; + *v >>= match i { + 0 | 2 | 4 | 6 => sh1, + 1 | 3 | 5 | 7 => sh2, + _ => sh3, + }; + } + Partitions { + s, + rnum, + count, + small: texels < 31, + } + } + + /// The partition of texel `(x, y)` (a 2D block's `z` is 0). + fn of(&self, x: u32, y: u32) -> usize { + let (x, y) = match self.small { + true => (x << 1, y << 1), + false => (x, y), + }; + let s = &self.s; + let rnum = self.rnum; + let a = (s[0] * x + s[1] * y + (rnum >> 14)) & 0x3F; + let b = (s[2] * x + s[3] * y + (rnum >> 10)) & 0x3F; + let c = match self.count < 3 { + true => 0, + false => (s[4] * x + s[5] * y + (rnum >> 6)) & 0x3F, + }; + let d = match self.count < 4 { + true => 0, + false => (s[6] * x + s[7] * y + (rnum >> 2)) & 0x3F, + }; + if a >= b && a >= c && a >= d { + 0 + } else if b >= c && b >= d { + 1 + } else if c >= d { + 2 + } else { + 3 + } + } +} + +// --------------------------------------------------------------------------------------------- +// Blocks. + +/// The weights' ranges by a block mode's precision bit and range bits: levels 2, 3, 4, 5, 6 and 8 +/// (low precision), then 10, 12, 16, 20, 24 and 32 (high). +const WEIGHT_RANGES: [Range; 12] = [ + r(1, 1), + r(3, 0), + r(1, 2), + r(5, 0), + r(3, 1), + r(1, 3), + r(5, 1), + r(3, 2), + r(1, 4), + r(5, 2), + r(3, 3), + r(1, 5), +]; + +/// A block mode's weight grid and weights: grid across and down, two planes, the weights' +/// range. +struct BlockMode { + grid: [u32; 2], + dual: bool, + range: Range, +} + +/// The block mode `mode` (11 bits) describes; `None` for a reserved one. +fn block_mode(mode: u32) -> Option { + let bit = |i: u32| (mode >> i) & 1; + let bits = |i: u32, n: u32| (mode >> i) & ((1 << n) - 1); + let (range_bits, grid, high, dual); + if mode & 3 != 0 { + range_bits = bit(4) | (mode & 3) << 1; + high = bit(9); + dual = bit(10); + let a = bits(5, 2); + let b = bits(7, 2); + grid = match bits(2, 2) { + 0 => [b + 4, a + 2], + 1 => [b + 8, a + 2], + 2 => [a + 2, b + 8], + _ => match bit(8) { + 0 => [a + 2, (b & 1) + 6], + _ => [(b & 1) + 2, a + 2], + }, + }; + } else { + if mode & 0xF == 0 { + return None; + } + range_bits = bit(4) | bits(2, 2) << 1; + let a = bits(5, 2); + (grid, high, dual) = match bits(7, 2) { + 0 => ([12, a + 2], bit(9), bit(10)), + 1 => ([a + 2, 12], bit(9), bit(10)), + 2 => ([a + 6, bits(9, 2) + 6], 0, 0), + _ => match a { + 0 => ([6, 10], bit(9), bit(10)), + 1 => ([10, 6], bit(9), bit(10)), + _ => return None, + }, + }; + } + if range_bits < 2 { + return None; + } + Some(BlockMode { + grid, + dual: dual == 1, + range: WEIGHT_RANGES[(range_bits - 2) as usize + if high == 1 { 6 } else { 0 }], + }) +} + +/// Decodes `block` of `fmt` into `out` (its texels' 16-bit interpolation results, row-major), or +/// says why it is an error block. +fn decode_block(fmt: AstcDecode, block: u128, out: &mut [[u16; 4]]) -> Result<(), Illegal> { + let (bw, bh) = (fmt.width, fmt.height); + let mode = field(block, 0, 11) as u32; + if mode & 0x1FF == 0x1FC { + return void_extent(block, &mut out[..(bw * bh) as usize]); + } + let bm = block_mode(mode).ok_or(Illegal::ReservedMode)?; + let [gw, gh] = bm.grid; + if gw > bw || gh > bh { + return Err(Illegal::GridPastBlock); + } + let planes = if bm.dual { 2 } else { 1 }; + let weight_count = gw * gh * planes; + if weight_count > 64 { + return Err(Illegal::TooManyWeights); + } + let weight_bits = bm.range.ise_bits(weight_count); + if !(24..=96).contains(&weight_bits) { + return Err(Illegal::WeightBits); + } + let partitions = field(block, 11, 2) as u32 + 1; + if bm.dual && partitions == 4 { + return Err(Illegal::DualPlaneFourPartitions); + } + let below_weights = 128 - weight_bits; + let mut cems = [0u32; 4]; + let (color_start, extra, seed); + if partitions == 1 { + cems[0] = field(block, 13, 4) as u32; + (color_start, extra, seed) = (17, 0, 0); + } else { + seed = field(block, 13, 10) as u32; + color_start = 29; + let low = field(block, 23, 6) as u32; + if low & 3 == 0 { + extra = 0; + cems[..partitions as usize].fill(low >> 2); + } else { + // The selector's class, then each partition's class bit and its 2-bit mode, the + // fields past the first 6 bits just below the weights. + extra = 3 * partitions - 4; + let at = below_weights + .checked_sub(extra) + .ok_or(Illegal::ConfigPastWeights)?; + let config = low | (field(block, at, extra) as u32) << 6; + let base = (config & 3) - 1; + for (i, cem) in (0..).zip(cems.iter_mut().take(partitions as usize)) { + let class = base + ((config >> (2 + i)) & 1); + let m = (config >> (2 + partitions + 2 * i)) & 3; + *cem = class << 2 | m; + } + } + } + let color_end = below_weights + .checked_sub(extra + 2 * (planes - 1)) + .ok_or(Illegal::ColorPastWeights)?; + // The plane-2 channel, just below the weights and the configuration's high bits. + let ccs = match bm.dual { + true => field(block, color_end, 2) as usize, + false => usize::MAX, + }; + let value_count: u32 = cems[..partitions as usize] + .iter() + .map(|c| 2 * ((c >> 2) + 1)) + .sum(); + if value_count > 18 { + return Err(Illegal::TooManyValues); + } + let color_bits = color_end + .checked_sub(color_start) + .ok_or(Illegal::ColorPastWeights)?; + // The largest range whose encoding of the values fits, of 6 levels or more. + let color_range = *RANGES + .iter() + .rev() + .find(|range| range.ise_bits(value_count) <= color_bits) + .filter(|range| range.levels() >= 6) + .ok_or(Illegal::NoColorRange)?; + let mut values = [0u32; 18]; + ise_decode( + field(block, color_start, color_range.ise_bits(value_count)), + color_range, + value_count as usize, + &mut values, + ); + let mut ends: [Option<[[u32; 4]; 2]>; 4] = [None; 4]; + let mut at = 0; + for (p, end) in ends.iter_mut().enumerate().take(partitions as usize) { + let n = (2 * ((cems[p] >> 2) + 1)) as usize; + let mut v = [0i32; 8]; + for (slot, &raw) in v.iter_mut().zip(&values[at..at + n]) { + *slot = unquantize_color(color_range, raw) as i32; + } + at += n; + *end = endpoints(cems[p], &v); + } + // The weights, read from bit 127 down. + let mut weights = [0u32; 64]; + ise_decode( + field(block.reverse_bits(), 0, weight_bits), + bm.range, + weight_count as usize, + &mut weights, + ); + for w in weights.iter_mut().take(weight_count as usize) { + *w = unquantize_weight(bm.range, *w); + } + let partition = (partitions > 1).then(|| Partitions::new(seed, partitions, bw * bh)); + // The infill's steps of a texel across and down, in 1/1024ths of the block. + let ds = (1024 + bw / 2) / (bw - 1); + let dt = (1024 + bh / 2) / (bh - 1); + for t in 0..bh { + let gt = (dt * t * (gh - 1) + 32) >> 6; + let (jt, ft) = (gt >> 4, gt & 0xF); + for s in 0..bw { + let gs = (ds * s * (gw - 1) + 32) >> 6; + let (js, fs) = (gs >> 4, gs & 0xF); + let w11 = (fs * ft + 8) >> 4; + let w10 = ft - w11; + let w01 = fs - w11; + let w00 = 16 + w11 - fs - ft; + let v0 = js + jt * gw; + // A tap of weight 0 may lie past the grid, read as 0. + let tap = |i: u32, plane: u32| -> u32 { + weights + .get((i * planes + plane) as usize) + .copied() + .unwrap_or(0) + }; + let infill = |plane: u32| -> u32 { + let p00 = tap(v0, plane); + let p01 = if w01 != 0 { tap(v0 + 1, plane) } else { 0 }; + let p10 = if w10 != 0 { tap(v0 + gw, plane) } else { 0 }; + let p11 = if w11 != 0 { tap(v0 + gw + 1, plane) } else { 0 }; + (p00 * w00 + p01 * w01 + p10 * w10 + p11 * w11 + 8) >> 4 + }; + let w0 = infill(0); + let w1 = if bm.dual { infill(1) } else { w0 }; + let p = partition.as_ref().map_or(0, |parts| parts.of(s, t)); + let texel = &mut out[(t * bw + s) as usize]; + let Some([e0, e1]) = ends[p] else { + *texel = ERROR_TEXEL; + continue; + }; + for ch in 0..4 { + let (c0, c1) = match fmt.srgb { + true => (e0[ch] << 8 | 0x80, e1[ch] << 8 | 0x80), + false => (e0[ch] * 257, e1[ch] * 257), + }; + let w = if ch == ccs { w1 } else { w0 }; + texel[ch] = ((c0 * (64 - w) + c1 * w + 32) >> 6) as u16; + } + } + } + Ok(()) +} + +/// A void-extent block's texels: its constant colour, or why it is an error block. +fn void_extent(block: u128, out: &mut [[u16; 4]]) -> Result<(), Illegal> { + if (block >> 9) & 1 == 1 { + return Err(Illegal::HdrVoidExtent); + } + if (block >> 10) & 3 != 3 { + return Err(Illegal::VoidExtentReserved); + } + let coord = |i: u32| field(block, 12 + 13 * i, 13) as u32; + let (s0, s1, t0, t1) = (coord(0), coord(1), coord(2), coord(3)); + let all_ones = [s0, s1, t0, t1].iter().all(|&c| c == 0x1FFF); + if !all_ones && (s0 >= s1 || t0 >= t1) { + return Err(Illegal::VoidExtentEmpty); + } + let color: [u16; 4] = std::array::from_fn(|i| field(block, 64 + 16 * i as u32, 16) as u16); + out.fill(color); + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/metal2vulkan/src/bind/astc_decode/kernel.rs b/crates/metal2vulkan/src/bind/astc_decode/kernel.rs new file mode 100644 index 000000000..1fd8469d5 --- /dev/null +++ b/crates/metal2vulkan/src/bind/astc_decode/kernel.rs @@ -0,0 +1,1148 @@ +//! The GPU's decode of ASTC LDR blocks into a decoded twin's texels: the module +//! [`astc_decode_module`](super::astc_decode_module) serializes, the same decode as the CPU's +//! ([`AstcDecode::decode`]) in integer operations alone. +//! +//! One invocation per texel decodes its block's header, its partition's endpoints and its own +//! weights, straight-line: each reading of the integer sequence encoding (a colour value or a +//! weight) computes the plain, trit and quint forms of its value and selects the range's, and +//! every error condition joins one flag, which turns the texel magenta. The tables of the trits, +//! the quints and the unquantizations are the CPU decode's own functions, tabulated as the module +//! is built. + +use super::{ + quints, trits, unquantize_color, unquantize_weight, AstcDecode, AstcTexels, Range, RANGES, + WEIGHT_RANGES, +}; +use crate::bind::block_decode::{table, BlockDecodeModule, BLOCKS, SHAPE, TEXELS}; +use crate::bind::ycbcr_convert::{scalar, words_buffer}; +use crate::lower::arith::exact_division::div_exact; +use crate::lower::arith::legal::{Form, Held}; +use crate::lower::arith::srgb::SRGB_DECODE_STEPS; +use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; +use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; +use crate::spirv::error::BResult; +use crate::spirv::ids::{GlobalId, TypeId, Value}; +use crate::spirv::ir::{ + BinOp, ConstBits, Constant, ConvOp, ExecMode, ExecModel, IoDir, MemAccess, Type, TypedModule, + UnOp, +}; + +/// The module's tables (the module docs), as `Private` arrays. +#[derive(Clone, Copy)] +struct Tables { + /// The five trits of each 8-bit trit block, 2 bits each. + trits: GlobalId, + /// The three quints of each 7-bit quint block, 3 bits each. + quints: GlobalId, + /// Each range of [`RANGES`]: its bits, and its base at bit 8. + ranges: GlobalId, + /// Each range of [`WEIGHT_RANGES`], likewise. + weight_ranges: GlobalId, + /// The first entry of each range of [`RANGES`] in `colors`. + color_at: GlobalId, + /// Every colour value of every range of 6 levels or more, unquantized (0 elsewhere). + colors: GlobalId, + /// The first entry of each range of [`WEIGHT_RANGES`] in `weights`. + weight_at: GlobalId, + /// Every weight of every weight range, unquantized. + weights: GlobalId, + /// Metal's sRGB decode step of each 8-bit code. + srgb_steps: GlobalId, +} + +impl Tables { + fn new(b: &mut ModuleBuilder, u32_: TypeId) -> BResult { + let info = |r: &Range| r.bits | r.base << 8; + let mut color_at = Vec::with_capacity(RANGES.len()); + let mut colors = Vec::new(); + for range in RANGES { + color_at.push(colors.len() as u32); + for v in 0..range.levels() { + colors.push(match range.levels() >= 6 { + true => unquantize_color(range, v), + false => 0, + }); + } + } + let mut weight_at = Vec::with_capacity(WEIGHT_RANGES.len()); + let mut weights = Vec::new(); + for range in WEIGHT_RANGES { + weight_at.push(weights.len() as u32); + weights.extend((0..range.levels()).map(|v| unquantize_weight(range, v))); + } + let trit_words: Vec = (0..256) + .map(|t| { + (trits(t).into_iter()) + .enumerate() + .fold(0, |w, (k, v)| w | v << (2 * k)) + }) + .collect(); + let quint_words: Vec = (0..128) + .map(|q| { + (quints(q).into_iter()) + .enumerate() + .fold(0, |w, (k, v)| w | v << (3 * k)) + }) + .collect(); + let ranges: Vec = RANGES.iter().map(info).collect(); + let weight_ranges: Vec = WEIGHT_RANGES.iter().map(info).collect(); + let steps: Vec = SRGB_DECODE_STEPS.iter().map(|&s| u32::from(s)).collect(); + Ok(Tables { + trits: table(b, u32_, &trit_words)?, + quints: table(b, u32_, &quint_words)?, + ranges: table(b, u32_, &ranges)?, + weight_ranges: table(b, u32_, &weight_ranges)?, + color_at: table(b, u32_, &color_at)?, + colors: table(b, u32_, &colors)?, + weight_at: table(b, u32_, &weight_at)?, + weights: table(b, u32_, &weights)?, + srgb_steps: table(b, u32_, &steps)?, + }) + } +} + +/// A 128-bit stream of four words, its lowest bit first. +type Stream = [Value; 4]; + +/// A range of the integer sequence encoding, read from a table at decode time: its low bits and +/// its base (1, 3 or 5). +#[derive(Clone, Copy)] +struct Ise { + bits: Value, + base: Value, +} + +/// The decode of one texel: the function it builds in, and the values every step reads. +struct K<'a, 'b> { + f: &'a mut FunctionBuilder<'b>, + u32_: TypeId, + tables: Tables, +} + +impl K<'_, '_> { + fn k(&mut self, v: u32) -> BResult { + scalar(self.f, self.u32_, u64::from(v)) + } + + /// The `bool` constant `v`. + fn boolean(&mut self, v: bool) -> BResult { + let ty = self.f.module().ty(Type::Bool)?; + let c = self.f.module().constant(Constant::Scalar { + ty, + bits: ConstBits(u64::from(v)), + })?; + self.f.module().const_value(c) + } + + /// Whether `v` is one of `values`. + fn one_of(&mut self, v: Value, values: &[u32]) -> BResult { + let mut any = self.boolean(false)?; + for &value in values { + let is = self.eqk(v, value)?; + any = self.lor(any, is)?; + } + Ok(any) + } + + fn op(&mut self, op: BinOp, a: Value, b: Value) -> BResult { + self.f.binary(op, a, b) + } + + fn opk(&mut self, op: BinOp, a: Value, b: u32) -> BResult { + let b = self.k(b)?; + self.f.binary(op, a, b) + } + + fn add(&mut self, a: Value, b: Value) -> BResult { + self.op(BinOp::IAdd, a, b) + } + + fn addk(&mut self, a: Value, b: u32) -> BResult { + self.opk(BinOp::IAdd, a, b) + } + + fn sub(&mut self, a: Value, b: Value) -> BResult { + self.op(BinOp::ISub, a, b) + } + + fn mul(&mut self, a: Value, b: Value) -> BResult { + self.op(BinOp::IMul, a, b) + } + + fn mulk(&mut self, a: Value, b: u32) -> BResult { + self.opk(BinOp::IMul, a, b) + } + + fn and(&mut self, a: Value, b: Value) -> BResult { + self.op(BinOp::BitwiseAnd, a, b) + } + + fn andk(&mut self, a: Value, b: u32) -> BResult { + self.opk(BinOp::BitwiseAnd, a, b) + } + + fn or(&mut self, a: Value, b: Value) -> BResult { + self.op(BinOp::BitwiseOr, a, b) + } + + fn shl(&mut self, a: Value, b: Value) -> BResult { + self.op(BinOp::ShiftLeftLogical, a, b) + } + + fn shlk(&mut self, a: Value, b: u32) -> BResult { + self.opk(BinOp::ShiftLeftLogical, a, b) + } + + fn shr(&mut self, a: Value, b: Value) -> BResult { + self.op(BinOp::ShiftRightLogical, a, b) + } + + fn shrk(&mut self, a: Value, b: u32) -> BResult { + self.opk(BinOp::ShiftRightLogical, a, b) + } + + fn sel(&mut self, c: Value, a: Value, b: Value) -> BResult { + self.f.select(c, a, b) + } + + fn eqk(&mut self, a: Value, b: u32) -> BResult { + self.opk(BinOp::IEqual, a, b) + } + + fn lor(&mut self, a: Value, b: Value) -> BResult { + self.op(BinOp::LogicalOr, a, b) + } + + fn land(&mut self, a: Value, b: Value) -> BResult { + self.op(BinOp::LogicalAnd, a, b) + } + + fn not(&mut self, a: Value) -> BResult { + self.f.unary(UnOp::LogicalNot, a) + } + + /// `(v >> at) & (2^n - 1)` for a constant field. + fn field(&mut self, v: Value, at: u32, n: u32) -> BResult { + let shifted = self.shrk(v, at)?; + self.andk(shifted, (1 << n) - 1) + } + + /// Entry `index` of the `Private` table `table`. + fn entry(&mut self, table: GlobalId, index: Value) -> BResult { + let table = self.f.module().global_value(table)?; + let p = self.f.access_chain(table, &[index])?; + self.f.load(p, MemAccess::default()) + } + + /// Word `i` of `stream`, 0 past its fourth. + fn word(&mut self, stream: &Stream, i: Value) -> BResult { + let mut word = self.k(0)?; + for (k, &w) in (0..4).zip(stream).rev() { + let at = self.eqk(i, k)?; + word = self.sel(at, w, word)?; + } + Ok(word) + } + + /// `2^n - 1` for `n` of 0 to 31. + fn mask(&mut self, n: Value) -> BResult { + let one = self.k(1)?; + let top = self.shl(one, n)?; + self.sub(top, one) + } + + /// The `n` bits (0 to 31) of `stream` from bit `at`, a bit past 127 read as 0. + fn read(&mut self, stream: &Stream, at: Value, n: Value) -> BResult { + let i = self.shrk(at, 5)?; + let shift = self.andk(at, 31)?; + let low = self.word(stream, i)?; + let low = self.shr(low, shift)?; + let next = self.addk(i, 1)?; + let high = self.word(stream, next)?; + let thirty_two = self.k(32)?; + let up = self.sub(thirty_two, shift)?; + let up = self.andk(up, 31)?; + let high = self.shl(high, up)?; + let aligned = self.eqk(shift, 0)?; + let zero = self.k(0)?; + let high = self.sel(aligned, zero, high)?; + let bits = self.or(low, high)?; + let mask = self.mask(n)?; + self.and(bits, mask) + } + + /// [`read`](Self::read) of a stream whose bits from `end` on are zero. + fn read_to(&mut self, stream: &Stream, at: Value, n: Value, end: Value) -> BResult { + let bits = self.read(stream, at, n)?; + let past = self.op(BinOp::UGreaterThanEqual, at, end)?; + let left = self.sub(end, at)?; + let left = self.op(BinOp::ULessThan, left, n)?; + let available = self.sub(end, at)?; + let available = self.sel(left, available, n)?; + let zero = self.k(0)?; + let available = self.sel(past, zero, available)?; + let mask = self.mask(available)?; + self.and(bits, mask) + } + + /// [`read_to`](Self::read_to) of a constant width. + fn read_tok(&mut self, stream: &Stream, at: Value, n: u32, end: Value) -> BResult { + let n = self.k(n)?; + self.read_to(stream, at, n, end) + } + + /// The range of entry `index` of a range table. + fn ise(&mut self, ranges: GlobalId, index: Value) -> BResult { + let info = self.entry(ranges, index)?; + let bits = self.andk(info, 0xff)?; + let base = self.shrk(info, 8)?; + Ok(Ise { bits, base }) + } + + /// The bits `count` values of `range` take in the encoding. + fn ise_bits(&mut self, range: Ise, count: Value) -> BResult { + let plain = self.mul(count, range.bits)?; + let eight = self.mulk(count, 8)?; + let eight = self.addk(eight, 4)?; + let trit_bits = self.opk(BinOp::UDiv, eight, 5)?; + let seven = self.mulk(count, 7)?; + let seven = self.addk(seven, 2)?; + let quint_bits = self.opk(BinOp::UDiv, seven, 3)?; + let zero = self.k(0)?; + let is_trit = self.eqk(range.base, 3)?; + let is_quint = self.eqk(range.base, 5)?; + let extra = self.sel(is_quint, quint_bits, zero)?; + let extra = self.sel(is_trit, trit_bits, extra)?; + self.add(plain, extra) + } + + /// Value `i` of the integer sequence encoding of `range` from bit `start` of `stream`, whose + /// bits from `end` on are zero: its trit or quint times `2^bits` plus its low bits. + fn ise_value( + &mut self, + stream: &Stream, + (start, end): (Value, Value), + range: Ise, + i: Value, + ) -> BResult { + let n = range.bits; + // Plain: `bits` bits at `start + i · bits`. + let at = self.mul(i, n)?; + let at = self.add(start, at)?; + let plain = self.read_to(stream, at, n, end)?; + // Trits: groups of five values in `5 bits + 8` bits. + let group = self.opk(BinOp::UDiv, i, 5)?; + let first = self.mulk(group, 5)?; + let k = self.sub(i, first)?; + let size = self.mulk(n, 5)?; + let size = self.addk(size, 8)?; + let size = self.mul(group, size)?; + let base = self.add(start, size)?; + let mut t = self.k(0)?; + // The trit block's bits: 2 after the first value, 2 after the second, 1, 2, 1. + for (values, gaps, width, at) in [ + (1, 0, 2, 0), + (2, 2, 2, 2), + (3, 4, 1, 4), + (4, 5, 2, 5), + (5, 7, 1, 7), + ] { + let pos = self.mulk(n, values)?; + let pos = self.addk(pos, gaps)?; + let pos = self.add(base, pos)?; + let piece = self.read_tok(stream, pos, width, end)?; + let piece = self.shlk(piece, at)?; + t = self.or(t, piece)?; + } + let mut gap = self.k(0)?; + for (index, before) in [(1, 2), (2, 4), (3, 5), (4, 7)] { + let here = self.eqk(k, index)?; + let before = self.k(before)?; + gap = self.sel(here, before, gap)?; + } + let at = self.mul(k, n)?; + let at = self.add(at, gap)?; + let at = self.add(base, at)?; + let low = self.read_to(stream, at, n, end)?; + let trit_word = self.entry(self.tables.trits, t)?; + let shift = self.shlk(k, 1)?; + let trit = self.shr(trit_word, shift)?; + let trit = self.andk(trit, 3)?; + let trit = self.shl(trit, n)?; + let trit_value = self.or(trit, low)?; + // Quints: groups of three values in `3 bits + 7` bits. + let group = self.opk(BinOp::UDiv, i, 3)?; + let first = self.mulk(group, 3)?; + let k = self.sub(i, first)?; + let size = self.mulk(n, 3)?; + let size = self.addk(size, 7)?; + let size = self.mul(group, size)?; + let base = self.add(start, size)?; + let mut q = self.k(0)?; + // The quint block's bits: 3 after the first value, 2 after the second, 2 after the third. + for (values, gaps, width, at) in [(1, 0, 3, 0), (2, 3, 2, 3), (3, 5, 2, 5)] { + let pos = self.mulk(n, values)?; + let pos = self.addk(pos, gaps)?; + let pos = self.add(base, pos)?; + let piece = self.read_tok(stream, pos, width, end)?; + let piece = self.shlk(piece, at)?; + q = self.or(q, piece)?; + } + let mut gap = self.k(0)?; + for (index, before) in [(1, 3), (2, 5)] { + let here = self.eqk(k, index)?; + let before = self.k(before)?; + gap = self.sel(here, before, gap)?; + } + let at = self.mul(k, n)?; + let at = self.add(at, gap)?; + let at = self.add(base, at)?; + let low = self.read_to(stream, at, n, end)?; + let quint_word = self.entry(self.tables.quints, q)?; + let shift = self.mulk(k, 3)?; + let quint = self.shr(quint_word, shift)?; + let quint = self.andk(quint, 7)?; + let quint = self.shl(quint, n)?; + let quint_value = self.or(quint, low)?; + let is_trit = self.eqk(range.base, 3)?; + let is_quint = self.eqk(range.base, 5)?; + let value = self.sel(is_quint, quint_value, plain)?; + self.sel(is_trit, trit_value, value) + } + + /// `v` clamped into 0 to 255, as a signed value. + fn clamp8(&mut self, v: Value) -> BResult { + let zero = self.k(0)?; + let top = self.k(255)?; + let low = self.op(BinOp::SLessThan, v, zero)?; + let v = self.sel(low, zero, v)?; + let high = self.op(BinOp::SGreaterThan, v, top)?; + self.sel(high, top, v) + } + + /// `bit_transfer_signed(a, b)`: the signed 6-bit offset and the base. + fn bit_transfer(&mut self, a: Value, b: Value) -> BResult<(Value, Value)> { + let b = self.shrk(b, 1)?; + let top = self.andk(a, 0x80)?; + let b = self.or(b, top)?; + let a = self.shrk(a, 1)?; + let a = self.andk(a, 0x3f)?; + let negative = self.andk(a, 0x20)?; + let negative = self.opk(BinOp::INotEqual, negative, 0)?; + let lowered = self.opk(BinOp::ISub, a, 0x40)?; + let a = self.sel(negative, lowered, a)?; + Ok((a, b)) + } + + /// `blue_contract(r, g, b, a)`, signed. + fn blue_contract(&mut self, [r, g, b, a]: [Value; 4]) -> BResult<[Value; 4]> { + let r = self.add(r, b)?; + let r = self.opk(BinOp::ShiftRightArithmetic, r, 1)?; + let g = self.add(g, b)?; + let g = self.opk(BinOp::ShiftRightArithmetic, g, 1)?; + Ok([r, g, b, a]) + } + + fn clamp4(&mut self, e: [Value; 4]) -> BResult<[Value; 4]> { + Ok([ + self.clamp8(e[0])?, + self.clamp8(e[1])?, + self.clamp8(e[2])?, + self.clamp8(e[3])?, + ]) + } + + fn sel4(&mut self, c: Value, a: [Value; 4], b: [Value; 4]) -> BResult<[Value; 4]> { + Ok([ + self.sel(c, a[0], b[0])?, + self.sel(c, a[1], b[1])?, + self.sel(c, a[2], b[2])?, + self.sel(c, a[3], b[3])?, + ]) + } + + /// The two endpoints of colour endpoint mode `cem` from its unquantized values `v` + /// (`super::endpoints`), and whether the mode is an HDR one. + fn endpoints(&mut self, cem: Value, v: [Value; 8]) -> BResult<([[Value; 4]; 2], Value)> { + let opaque = self.k(255)?; + let zero = self.k(0)?; + // 0: luminance. + let lum = [[v[0], v[0], v[0], opaque], [v[1], v[1], v[1], opaque]]; + // 1: luminance, base and offset. + let l0 = self.shrk(v[0], 2)?; + let high = self.andk(v[1], 0xc0)?; + let l0 = self.or(l0, high)?; + let offset = self.andk(v[1], 0x3f)?; + let l1 = self.add(l0, offset)?; + let past = self.opk(BinOp::UGreaterThan, l1, 255)?; + let l1 = self.sel(past, opaque, l1)?; + let lum_delta = [[l0, l0, l0, opaque], [l1, l1, l1, opaque]]; + // 4: luminance and alpha. + let lum_alpha = [[v[0], v[0], v[0], v[2]], [v[1], v[1], v[1], v[3]]]; + // 5: luminance and alpha, base and offset. + let (o1, b0) = self.bit_transfer(v[1], v[0])?; + let (o3, b2) = self.bit_transfer(v[3], v[2])?; + let l1 = self.add(b0, o1)?; + let a1 = self.add(b2, o3)?; + let lum_alpha_delta = [ + self.clamp4([b0, b0, b0, b2])?, + self.clamp4([l1, l1, l1, a1])?, + ]; + // 6 and 10: RGB scaled, and alpha. + let is_ten = self.eqk(cem, 10)?; + let a0 = self.sel(is_ten, v[4], opaque)?; + let a1 = self.sel(is_ten, v[5], opaque)?; + let mut scaled = [zero; 3]; + for (c, slot) in scaled.iter_mut().enumerate() { + let product = self.mul(v[c], v[3])?; + *slot = self.shrk(product, 8)?; + } + let rgb_scale = [ + [scaled[0], scaled[1], scaled[2], a0], + [v[0], v[1], v[2], a1], + ]; + // 8 and 12: RGB, and alpha. + let is_twelve = self.eqk(cem, 12)?; + let a0 = self.sel(is_twelve, v[6], opaque)?; + let a1 = self.sel(is_twelve, v[7], opaque)?; + let s1 = self.add(v[1], v[3])?; + let s1 = self.add(s1, v[5])?; + let s0 = self.add(v[0], v[2])?; + let s0 = self.add(s0, v[4])?; + let forward = self.op(BinOp::UGreaterThanEqual, s1, s0)?; + let e0 = self.clamp4([v[0], v[2], v[4], a0])?; + let e1 = self.clamp4([v[1], v[3], v[5], a1])?; + let c0 = self.blue_contract([v[1], v[3], v[5], a1])?; + let c0 = self.clamp4(c0)?; + let c1 = self.blue_contract([v[0], v[2], v[4], a0])?; + let c1 = self.clamp4(c1)?; + let rgb = [self.sel4(forward, e0, c0)?, self.sel4(forward, e1, c1)?]; + // 9 and 13: RGB, and alpha, base and offset. + let is_thirteen = self.eqk(cem, 13)?; + let (o1, b0) = self.bit_transfer(v[1], v[0])?; + let (o3, b2) = self.bit_transfer(v[3], v[2])?; + let (o5, b4) = self.bit_transfer(v[5], v[4])?; + let (o7, b6) = self.bit_transfer(v[7], v[6])?; + let o7 = self.sel(is_thirteen, o7, zero)?; + let b6 = self.sel(is_thirteen, b6, opaque)?; + let sum = self.add(o1, o3)?; + let sum = self.add(sum, o5)?; + let forward = self.op(BinOp::SGreaterThanEqual, sum, zero)?; + let ends = [ + self.add(b0, o1)?, + self.add(b2, o3)?, + self.add(b4, o5)?, + self.add(b6, o7)?, + ]; + let e0 = self.clamp4([b0, b2, b4, b6])?; + let e1 = self.clamp4(ends)?; + let c0 = self.blue_contract(ends)?; + let c0 = self.clamp4(c0)?; + let c1 = self.blue_contract([b0, b2, b4, b6])?; + let c1 = self.clamp4(c1)?; + let rgb_delta = [self.sel4(forward, e0, c0)?, self.sel4(forward, e1, c1)?]; + // The mode's. + let mut out = lum; + let modes: [(&[u32], _); 6] = [ + (&[1], lum_delta), + (&[4], lum_alpha), + (&[5], lum_alpha_delta), + (&[6, 10], rgb_scale), + (&[8, 12], rgb), + (&[9, 13], rgb_delta), + ]; + for (modes, ends) in modes { + let here = self.one_of(cem, modes)?; + out = [ + self.sel4(here, ends[0], out[0])?, + self.sel4(here, ends[1], out[1])?, + ]; + } + let hdr = self.one_of(cem, &[2, 3, 7, 11, 14, 15])?; + Ok((out, hdr)) + } + + /// `hash52(p)`. + fn hash52(&mut self, p: Value) -> BResult { + let xor = |k: &mut Self, a: Value, b: Value| k.op(BinOp::BitwiseXor, a, b); + let t = self.shrk(p, 15)?; + let p = xor(self, p, t)?; + let t = self.shlk(p, 17)?; + let p = self.sub(p, t)?; + let t = self.shlk(p, 7)?; + let p = self.add(p, t)?; + let t = self.shlk(p, 4)?; + let p = self.add(p, t)?; + let t = self.shrk(p, 5)?; + let p = xor(self, p, t)?; + let t = self.shlk(p, 16)?; + let p = self.add(p, t)?; + let t = self.shrk(p, 7)?; + let p = xor(self, p, t)?; + let t = self.shrk(p, 3)?; + let p = xor(self, p, t)?; + let t = self.shlk(p, 6)?; + let p = xor(self, p, t)?; + let t = self.shrk(p, 17)?; + xor(self, p, t) + } + + /// The partition of texel `(x, y)` of a block of `texels` texels, `count` partitions (2 to + /// 4) and partition index `seed` (`super::Partitions`). + fn partition( + &mut self, + seed: Value, + count: Value, + texels: u32, + [x, y]: [Value; 2], + ) -> BResult { + let seed = { + let less = self.addk(count, u32::MAX)?; + let shifted = self.shlk(less, 10)?; + self.add(seed, shifted)? + }; + let rnum = self.hash52(seed)?; + let mut s = [rnum; 8]; + for (i, slot) in s.iter_mut().enumerate() { + *slot = self.field(rnum, 4 * i as u32, 4)?; + } + let four = self.k(4)?; + let five = self.k(5)?; + let six = self.k(6)?; + let three = self.eqk(count, 3)?; + let odd = self.andk(seed, 1)?; + let odd = self.opk(BinOp::INotEqual, odd, 0)?; + let two = self.andk(seed, 2)?; + let two = self.opk(BinOp::INotEqual, two, 0)?; + let by_two = self.sel(two, four, five)?; + let by_three = self.sel(three, six, five)?; + let sh1 = self.sel(odd, by_two, by_three)?; + let sh2 = self.sel(odd, by_three, by_two)?; + for (i, slot) in s.iter_mut().enumerate() { + let square = self.mul(*slot, *slot)?; + let shift = if i % 2 == 0 { sh1 } else { sh2 }; + *slot = self.shr(square, shift)?; + } + let (x, y) = match texels < 31 { + true => (self.shlk(x, 1)?, self.shlk(y, 1)?), + false => (x, y), + }; + let mut lines = [rnum; 4]; + for (line, (slot, shift)) in lines.iter_mut().zip([14, 10, 6, 2]).enumerate() { + let sx = self.mul(s[2 * line], x)?; + let sy = self.mul(s[2 * line + 1], y)?; + let sum = self.add(sx, sy)?; + let r = self.shrk(rnum, shift)?; + let sum = self.add(sum, r)?; + *slot = self.andk(sum, 0x3f)?; + } + let zero = self.k(0)?; + let under_three = self.opk(BinOp::ULessThan, count, 3)?; + let under_four = self.opk(BinOp::ULessThan, count, 4)?; + let [a, b, c, d] = lines; + let c = self.sel(under_three, zero, c)?; + let d = self.sel(under_four, zero, d)?; + let ge = |k: &mut Self, p: Value, q: Value| k.op(BinOp::UGreaterThanEqual, p, q); + let ab = ge(self, a, b)?; + let ac = ge(self, a, c)?; + let ad = ge(self, a, d)?; + let bc = ge(self, b, c)?; + let bd = ge(self, b, d)?; + let cd = ge(self, c, d)?; + let first = self.land(ab, ac)?; + let first = self.land(first, ad)?; + let second = self.land(bc, bd)?; + let one = self.k(1)?; + let two = self.k(2)?; + let three = self.k(3)?; + let p = self.sel(cd, two, three)?; + let p = self.sel(second, one, p)?; + self.sel(first, zero, p) + } + + /// Entry `v` of the unquantization table of `range` (an index into its range table) whose + /// ranges start at `at` in `values`. + fn unquantize( + &mut self, + (at, values): (GlobalId, GlobalId), + range: Value, + v: Value, + ) -> BResult { + let first = self.entry(at, range)?; + let index = self.add(first, v)?; + self.entry(values, index) + } +} + +/// The texel's channels, each its 16-bit interpolation result `C`, and whether the texel is an +/// error one: the decode of the block `words` at texel `(s, t)` of a block of `decode`'s +/// footprint (`super::decode_block` and `super::void_extent`). +fn texel( + k: &mut K<'_, '_>, + decode: AstcDecode, + words: Stream, + [s, t]: [Value; 2], +) -> BResult<([Value; 4], Value)> { + let (bw, bh) = (decode.width, decode.height); + let zero = k.k(0)?; + let no = k.boolean(false)?; + let w0 = words[0]; + let mode = k.andk(w0, 0x7ff)?; + let bit = |k: &mut K<'_, '_>, i: u32| k.field(mode, i, 1); + let bits = |k: &mut K<'_, '_>, i: u32, n: u32| k.field(mode, i, n); + // The block mode (`super::block_mode`): the first form where its low two bits are set. + let low2 = k.andk(mode, 3)?; + let first_form = k.opk(BinOp::INotEqual, low2, 0)?; + let b4 = bit(k, 4)?; + let b8 = bit(k, 8)?; + let b9 = bit(k, 9)?; + let b10 = bit(k, 10)?; + let a = bits(k, 5, 2)?; + let b = bits(k, 7, 2)?; + let low2_up = k.shlk(low2, 1)?; + let range_first = k.or(b4, low2_up)?; + let a2 = k.addk(a, 2)?; + let b4w = k.addk(b, 4)?; + let b8w = k.addk(b, 8)?; + let b_low = k.andk(b, 1)?; + let b6 = k.addk(b_low, 6)?; + let b2 = k.addk(b_low, 2)?; + let layout = bits(k, 2, 2)?; + let is0 = k.eqk(layout, 0)?; + let is1 = k.eqk(layout, 1)?; + let is2 = k.eqk(layout, 2)?; + let high8 = k.opk(BinOp::INotEqual, b8, 0)?; + let gw3 = k.sel(high8, b2, a2)?; + let gh3 = k.sel(high8, a2, b6)?; + let gw = k.sel(is2, a2, gw3)?; + let gh = k.sel(is2, b8w, gh3)?; + let gw = k.sel(is1, b8w, gw)?; + let gh = k.sel(is1, a2, gh)?; + let gw_first = k.sel(is0, b4w, gw)?; + let gh_first = k.sel(is0, a2, gh)?; + // The second form. + let layout_up = k.shlk(layout, 1)?; + let range_second = k.or(b4, layout_up)?; + let twelve = k.k(12)?; + let a6 = k.addk(a, 6)?; + let c9 = bits(k, 9, 2)?; + let c6 = k.addk(c9, 6)?; + let six = k.k(6)?; + let ten = k.k(10)?; + let c0 = k.eqk(b, 0)?; + let c1 = k.eqk(b, 1)?; + let c2 = k.eqk(b, 2)?; + let a0 = k.eqk(a, 0)?; + let gw3 = k.sel(a0, six, ten)?; + let gh3 = k.sel(a0, ten, six)?; + let gw = k.sel(c2, a6, gw3)?; + let gh = k.sel(c2, c6, gh3)?; + let gw = k.sel(c1, a2, gw)?; + let gh = k.sel(c1, twelve, gh)?; + let gw_second = k.sel(c0, twelve, gw)?; + let gh_second = k.sel(c0, a2, gh)?; + let plain_high = k.sel(c2, zero, b9)?; + let plain_dual = k.sel(c2, zero, b10)?; + let low4 = k.andk(mode, 0xf)?; + let reserved_low = k.eqk(low4, 0)?; + let a_past = k.opk(BinOp::UGreaterThan, a, 1)?; + let c3 = k.eqk(b, 3)?; + let reserved_c3 = k.land(c3, a_past)?; + let reserved_second = k.lor(reserved_low, reserved_c3)?; + let range_bits = k.sel(first_form, range_first, range_second)?; + let high = k.sel(first_form, b9, plain_high)?; + let dual = k.sel(first_form, b10, plain_dual)?; + let gw = k.sel(first_form, gw_first, gw_second)?; + let gh = k.sel(first_form, gh_first, gh_second)?; + let reserved = k.sel(first_form, no, reserved_second)?; + let few_range = k.opk(BinOp::ULessThan, range_bits, 2)?; + let mut bad = k.lor(reserved, few_range)?; + let high_at = k.mulk(high, 6)?; + let weight_range = k.addk(range_bits, u32::MAX - 1)?; + let weight_range = k.add(weight_range, high_at)?; + let weight_range = k.andk(weight_range, 15)?; + let eleven = k.k(11)?; + let past_table = k.op(BinOp::UGreaterThan, weight_range, eleven)?; + let weight_range = k.sel(past_table, zero, weight_range)?; + let wise = k.ise(k.tables.weight_ranges, weight_range)?; + let dual = k.opk(BinOp::INotEqual, dual, 0)?; + let one = k.k(1)?; + let two = k.k(2)?; + let planes = k.sel(dual, two, one)?; + // The grid fits the block, holds at most 64 weights in 24 to 96 bits. + let wide = k.opk(BinOp::UGreaterThan, gw, bw)?; + let tall = k.opk(BinOp::UGreaterThan, gh, bh)?; + bad = k.lor(bad, wide)?; + bad = k.lor(bad, tall)?; + let grid = k.mul(gw, gh)?; + let weight_count = k.mul(grid, planes)?; + let many = k.opk(BinOp::UGreaterThan, weight_count, 64)?; + bad = k.lor(bad, many)?; + let weight_bits = k.ise_bits(wise, weight_count)?; + let few = k.opk(BinOp::ULessThan, weight_bits, 24)?; + let lots = k.opk(BinOp::UGreaterThan, weight_bits, 96)?; + bad = k.lor(bad, few)?; + bad = k.lor(bad, lots)?; + // Partitions and colour endpoint modes. + let count = k.field(w0, 11, 2)?; + let count = k.addk(count, 1)?; + let four_parts = k.eqk(count, 4)?; + let dual_four = k.land(dual, four_parts)?; + bad = k.lor(bad, dual_four)?; + let single = k.eqk(count, 1)?; + let below = k.k(128)?; + let below = k.sub(below, weight_bits)?; + let cem_single = k.field(w0, 13, 4)?; + let seed = k.field(w0, 13, 10)?; + let low = k.field(w0, 23, 6)?; + let low_class = k.andk(low, 3)?; + let shared = k.eqk(low_class, 0)?; + let three_count = k.mulk(count, 3)?; + let extra_config = k.addk(three_count, u32::MAX - 3)?; + let extra_multi = k.sel(shared, zero, extra_config)?; + let extra = k.sel(single, zero, extra_multi)?; + let past_weights = k.op(BinOp::UGreaterThan, extra, below)?; + bad = k.lor(bad, past_weights)?; + let config_at = k.sub(below, extra)?; + let config_high = k.read(&words, config_at, extra)?; + let config_high = k.shlk(config_high, 6)?; + let config = k.or(low, config_high)?; + let class_base = k.andk(config, 3)?; + let class_base = k.addk(class_base, u32::MAX)?; + let shared_cem = k.shrk(low, 2)?; + let mut cems = [zero; 4]; + for (i, cem) in (0u32..).zip(cems.iter_mut()) { + let class_shift = k.k(2 + i)?; + let class = k.shr(config, class_shift)?; + let class = k.andk(class, 1)?; + let class = k.add(class_base, class)?; + let class = k.shlk(class, 2)?; + let m_shift = k.addk(count, 2 + 2 * i)?; + let m = k.shr(config, m_shift)?; + let m = k.andk(m, 3)?; + let own = k.or(class, m)?; + let multi = k.sel(shared, shared_cem, own)?; + *cem = match i { + 0 => k.sel(single, cem_single, multi)?, + _ => multi, + }; + } + let color_start = { + let seventeen = k.k(17)?; + let twenty_nine = k.k(29)?; + k.sel(single, seventeen, twenty_nine)? + }; + let plane_bits = k.sel(dual, two, zero)?; + let reserved_below = k.add(extra, plane_bits)?; + let short = k.op(BinOp::UGreaterThan, reserved_below, below)?; + bad = k.lor(bad, short)?; + let color_end = k.sub(below, reserved_below)?; + let two_bits = k.k(2)?; + let ccs = k.read(&words, color_end, two_bits)?; + let mut value_count = zero; + let mut counts = [zero; 4]; + for (i, cem) in cems.into_iter().enumerate() { + let class = k.shrk(cem, 2)?; + let n = k.addk(class, 1)?; + let n = k.shlk(n, 1)?; + let inside = k.opk(BinOp::UGreaterThan, count, i as u32)?; + counts[i] = k.sel(inside, n, zero)?; + value_count = k.add(value_count, counts[i])?; + } + let too_many = k.opk(BinOp::UGreaterThan, value_count, 18)?; + bad = k.lor(bad, too_many)?; + let backwards = k.op(BinOp::UGreaterThan, color_start, color_end)?; + bad = k.lor(bad, backwards)?; + let color_bits = k.sub(color_end, color_start)?; + // The largest colour range of 6 levels or more whose encoding fits. + let mut color_range = zero; + let mut color_used = zero; + for (index, range) in RANGES.iter().enumerate().filter(|(_, r)| r.levels() >= 6) { + let info = Ise { + bits: k.k(range.bits)?, + base: k.k(range.base)?, + }; + let used = k.ise_bits(info, value_count)?; + let fits = k.op(BinOp::ULessThanEqual, used, color_bits)?; + let index = k.k(index as u32)?; + color_range = k.sel(fits, index, color_range)?; + color_used = k.sel(fits, used, color_used)?; + } + let no_range = k.eqk(color_range, 0)?; + bad = k.lor(bad, no_range)?; + let cise = k.ise(k.tables.ranges, color_range)?; + let color_stream_end = k.add(color_start, color_used)?; + // The texel's partition, its mode and its values. + let multi = k.not(single)?; + let texels = bw * bh; + let p = k.partition(seed, count, texels, [s, t])?; + let p = k.sel(multi, p, zero)?; + let mut cem = cems[0]; + let mut first_value = zero; + let mut before = zero; + for i in 1..4u32 { + before = k.add(before, counts[i as usize - 1])?; + let here = k.eqk(p, i)?; + cem = k.sel(here, cems[i as usize], cem)?; + first_value = k.sel(here, before, first_value)?; + } + let mut v = [zero; 8]; + for (i, slot) in (0u32..).zip(v.iter_mut()) { + let index = k.addk(first_value, i)?; + let raw = k.ise_value(&words, (color_start, color_stream_end), cise, index)?; + let tables = (k.tables.color_at, k.tables.colors); + *slot = k.unquantize(tables, color_range, raw)?; + } + let ([e0, e1], hdr) = k.endpoints(cem, v)?; + let partition_bad = k.lor(bad, hdr)?; + // The weights, from bit 127 down: the stream of the block's bits reversed. + let mut reversed = words; + for (slot, &w) in reversed.iter_mut().zip(words.iter().rev()) { + *slot = k.f.unary(UnOp::BitReverse, w)?; + } + let ds = (1024 + bw / 2) / (bw - 1); + let dt = (1024 + bh / 2) / (bh - 1); + let gw_less = k.addk(gw, u32::MAX)?; + let gh_less = k.addk(gh, u32::MAX)?; + let gs = k.mulk(s, ds)?; + let gs = k.mul(gs, gw_less)?; + let gs = k.addk(gs, 32)?; + let gs = k.shrk(gs, 6)?; + let gt = k.mulk(t, dt)?; + let gt = k.mul(gt, gh_less)?; + let gt = k.addk(gt, 32)?; + let gt = k.shrk(gt, 6)?; + let js = k.shrk(gs, 4)?; + let fs = k.andk(gs, 15)?; + let jt = k.shrk(gt, 4)?; + let ft = k.andk(gt, 15)?; + let w11 = k.mul(fs, ft)?; + let w11 = k.addk(w11, 8)?; + let w11 = k.shrk(w11, 4)?; + let w10 = k.sub(ft, w11)?; + let w01 = k.sub(fs, w11)?; + let sixteen = k.k(16)?; + let w00 = k.sub(sixteen, fs)?; + let w00 = k.sub(w00, ft)?; + let w00 = k.add(w00, w11)?; + let row = k.mul(jt, gw)?; + let v0 = k.add(js, row)?; + let v1 = k.addk(v0, 1)?; + let v2 = k.add(v0, gw)?; + let v3 = k.addk(v2, 1)?; + let mut plane_weights = [zero; 2]; + for (plane, slot) in (0u32..).zip(plane_weights.iter_mut()) { + let mut sum = k.k(8)?; + for (index, factor) in [(v0, w00), (v1, w01), (v2, w10), (v3, w11)] { + let at = k.mul(index, planes)?; + let at = k.addk(at, plane)?; + let raw = k.ise_value(&reversed, (zero, weight_bits), wise, at)?; + let tables = (k.tables.weight_at, k.tables.weights); + let weight = k.unquantize(tables, weight_range, raw)?; + let inside = k.op(BinOp::ULessThan, at, weight_count)?; + let weight = k.sel(inside, weight, zero)?; + let term = k.mul(weight, factor)?; + sum = k.add(sum, term)?; + } + *slot = k.shrk(sum, 4)?; + } + let second = k.sel(dual, plane_weights[1], plane_weights[0])?; + let mut channels = [zero; 4]; + for (ch, slot) in (0u32..).zip(channels.iter_mut()) { + let is_ccs = k.eqk(ccs, ch)?; + let use_second = k.land(dual, is_ccs)?; + let w = k.sel(use_second, second, plane_weights[0])?; + let widen = |k: &mut K<'_, '_>, e: Value| match decode.srgb { + true => { + let up = k.shlk(e, 8)?; + k.opk(BinOp::BitwiseOr, up, 0x80) + } + false => k.mulk(e, 257), + }; + let c0 = widen(k, e0[ch as usize])?; + let c1 = widen(k, e1[ch as usize])?; + let sixty_four = k.k(64)?; + let rest = k.sub(sixty_four, w)?; + let a = k.mul(c0, rest)?; + let b = k.mul(c1, w)?; + let sum = k.add(a, b)?; + let sum = k.addk(sum, 32)?; + *slot = k.shrk(sum, 6)?; + } + // A void-extent block (`super::void_extent`). + let void_mode = k.andk(mode, 0x1ff)?; + let void = k.eqk(void_mode, 0x1fc)?; + let hdr_void = bit(k, 9)?; + let hdr_void = k.opk(BinOp::INotEqual, hdr_void, 0)?; + let reserved_void = k.field(w0, 10, 2)?; + let reserved_void = k.opk(BinOp::INotEqual, reserved_void, 3)?; + let mut coords = [zero; 4]; + let mut all_ones = k.boolean(true)?; + for (i, slot) in (0u32..).zip(coords.iter_mut()) { + let at = k.k(12 + 13 * i)?; + let n = k.k(13)?; + *slot = k.read(&words, at, n)?; + let ones = k.eqk(*slot, 0x1fff)?; + all_ones = k.land(all_ones, ones)?; + } + let empty_s = k.op(BinOp::UGreaterThanEqual, coords[0], coords[1])?; + let empty_t = k.op(BinOp::UGreaterThanEqual, coords[2], coords[3])?; + let empty = k.lor(empty_s, empty_t)?; + let some = k.not(all_ones)?; + let empty = k.land(some, empty)?; + let void_bad = k.lor(hdr_void, reserved_void)?; + let void_bad = k.lor(void_bad, empty)?; + let mut color = [zero; 4]; + for (i, slot) in color.iter_mut().enumerate() { + let word = words[2 + i / 2]; + *slot = k.field(word, 16 * (i as u32 % 2), 16)?; + } + let channels = k.sel4(void, color, channels)?; + let bad = k.sel(void, void_bad, partition_bad)?; + Ok((channels, bad)) +} + +/// The module of `decode` writing `texels` as a typed module, before serialization: the module +/// [`astc_decode_module`](super::astc_decode_module) serializes, which the CPU interpreter runs. +/// Its bindings are the block decode's (`BlockDecodeModule`); it reads the shape's first three +/// words, the region's size. +pub(super) fn typed_module(decode: AstcDecode, texels: AstcTexels) -> BResult { + let mut b = ModuleBuilder::new(); + let u32_ = b.ty(Type::Int { + width: 32, + signed: false, + })?; + let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; + let shape = words_buffer(&mut b, SHAPE, u32_)?; + let blocks = words_buffer(&mut b, BLOCKS, u32_)?; + let texel_words = words_buffer(&mut b, TEXELS, u32_)?; + let tables = Tables::new(&mut b, u32_)?; + let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?; + let void = b.ty(Type::Void)?; + let mut f = b.function(void)?; + let zero = scalar(&mut f, u32_, 0)?; + let invocation = f.module().global_value(invocation)?; + let invocation = f.load(invocation, MemAccess::default())?; + let x = f.composite_extract(invocation, &[0])?; + let y = f.composite_extract(invocation, &[1])?; + let z = f.composite_extract(invocation, &[2])?; + let shape = f.module().global_value(shape)?; + let field = |f: &mut FunctionBuilder<'_>, index: u32| -> BResult { + let index = scalar(f, u32_, u64::from(index))?; + let p = f.access_chain(shape, &[zero, index])?; + f.load(p, MemAccess::default()) + }; + let width = field(&mut f, 0)?; + let height = field(&mut f, 1)?; + let depth = field(&mut f, 2)?; + let in_x = f.binary(BinOp::ULessThan, x, width)?; + let in_y = f.binary(BinOp::ULessThan, y, height)?; + let in_z = f.binary(BinOp::ULessThan, z, depth)?; + let inside = f.binary(BinOp::LogicalAnd, in_x, in_y)?; + let inside = f.binary(BinOp::LogicalAnd, inside, in_z)?; + let blocks = f.module().global_value(blocks)?; + let texel_words = f.module().global_value(texel_words)?; + let decoded: ArmFn<'_, ()> = Box::new(move |f, _| { + let mut k = K { f, u32_, tables }; + let (bw, bh) = (decode.width, decode.height); + // The texel's block, `(z · down + y / bh) · across + x / bw`, and its place in it. + let across = k.addk(width, bw - 1)?; + let across = k.opk(BinOp::UDiv, across, bw)?; + let down = k.addk(height, bh - 1)?; + let down = k.opk(BinOp::UDiv, down, bh)?; + let bx = k.opk(BinOp::UDiv, x, bw)?; + let by = k.opk(BinOp::UDiv, y, bh)?; + let row = k.mul(z, down)?; + let row = k.add(row, by)?; + let block = k.mul(row, across)?; + let block = k.add(block, bx)?; + let base = k.shlk(block, 2)?; + let mut words = [zero; 4]; + for (i, slot) in (0u32..).zip(words.iter_mut()) { + let index = k.addk(base, i)?; + let p = k.f.access_chain(blocks, &[zero, index])?; + *slot = k.f.load(p, MemAccess::default())?; + } + let x0 = k.mulk(bx, bw)?; + let s = k.sub(x, x0)?; + let y0 = k.mulk(by, bh)?; + let t = k.sub(y, y0)?; + let (channels, bad) = texel(&mut k, decode, words, [s, t])?; + // An error texel is magenta: each channel's `C` all ones, green 0. + let all = k.k(0xffff)?; + let channels = k.sel4(bad, [all, zero, all, all], channels)?; + let out: Vec = match texels { + AstcTexels::Unorm8 => { + let mut packed = zero; + for (ch, c) in (0u32..).zip(channels) { + let code = match decode.srgb { + true => k.shrk(c, 8)?, + false => { + let twelve = k.shrk(c, 4)?; + let scaled = k.mulk(twelve, 255)?; + let scaled = k.addk(scaled, 2047)?; + k.opk(BinOp::UDiv, scaled, 4095)? + } + }; + let placed = k.shlk(code, 8 * ch)?; + packed = k.or(packed, placed)?; + } + vec![packed] + } + AstcTexels::Float => { + let u = Form { + held: Held::Int { + bits: 32, + container: 32, + }, + lanes: 1, + }; + let mut words = Vec::with_capacity(4); + for (ch, c) in channels.into_iter().enumerate() { + let value = match (decode.srgb, ch) { + (true, 3) => { + let code = k.shrk(c, 8)?; + div_exact(k.f, u, code, 255)? + } + (true, _) => { + let code = k.shrk(c, 8)?; + let step = k.entry(k.tables.srgb_steps, code)?; + div_exact(k.f, u, step, 4095)? + } + (false, _) => { + let twelve = k.shrk(c, 4)?; + div_exact(k.f, u, twelve, 4095)? + } + }; + words.push(k.f.convert(ConvOp::Bitcast, value, u32_)?); + } + words + } + }; + // The texel's first word, `((z · height + y) · width + x) · words`. + let at = k.mul(z, height)?; + let at = k.add(at, y)?; + let at = k.mul(at, width)?; + let at = k.add(at, x)?; + let at = k.mulk(at, out.len() as u32)?; + for (i, word) in (0u32..).zip(out) { + let index = k.addk(at, i)?; + let p = k.f.access_chain(texel_words, &[zero, index])?; + k.f.store(p, word, MemAccess::default())?; + } + Ok(ArmEnd::FallThrough(Vec::new())) + }); + f.if_(&mut (), inside, decoded, None)?; + f.ret(None)?; + let id = f.finish()?; + b.entry( + ExecModel::GLCompute, + id, + vec![ExecMode::LocalSize { + x: BlockDecodeModule::LOCAL_SIZE, + y: BlockDecodeModule::LOCAL_SIZE, + z: 1, + }], + )?; + b.finalize() +} diff --git a/crates/metal2vulkan/src/bind/astc_decode/tests.rs b/crates/metal2vulkan/src/bind/astc_decode/tests.rs new file mode 100644 index 000000000..44bd52188 --- /dev/null +++ b/crates/metal2vulkan/src/bind/astc_decode/tests.rs @@ -0,0 +1,445 @@ +//! The ASTC decode against blocks the specification's rules decide outright, and against Metal's +//! reads of seeded random blocks on an Apple M3 Max (macOS 27.0.1). + +use super::kernel::typed_module; +use super::{AstcDecode, AstcTexels, Illegal}; +use crate::bind::block_decode::{BlockDecodeModule, BLOCKS, SHAPE, TEXELS}; +use crate::metal::PixelFormat; +use crate::spirv::interp::{run, Buffer, Config, Order, Resources}; +use crate::spirv::testing::{assert_valid, committed_profiles}; + +/// The fourteen 2D footprints, linear and sRGB, decode, and no other format does (the HDR forms +/// and Apple's 4x2 and 8x4 footprints among them). +#[test] +fn the_ldr_and_srgb_formats_alone_decode() { + let decoded: Vec<(PixelFormat, AstcDecode)> = PixelFormat::ALL + .iter() + .filter_map(|&pf| AstcDecode::of(pf).map(|d| (pf, d))) + .collect(); + assert_eq!(decoded.len(), 28); + for (pf, d) in decoded { + let name = pf.name(); + let footprint = format!("_{}x{}_", d.width, d.height); + assert!(name.contains(&footprint), "{name}: {d:?}"); + assert_eq!(name.ends_with("_sRGB"), d.srgb, "{name}"); + assert!(name.ends_with("_LDR") || d.srgb, "{name}"); + } + for pf in [ + PixelFormat::ASTC8x8HDR, + PixelFormat::ASTC4x2LDR, + PixelFormat::ASTC8x4SRGB, + PixelFormat::BC7RGBAUnorm, + ] { + assert_eq!(AstcDecode::of(pf), None, "{pf:?}"); + } +} + +fn eight() -> AstcDecode { + AstcDecode::of(PixelFormat::ASTC8x8LDR).expect("a decode") +} + +/// A void-extent block reads its four 16-bit values everywhere; an HDR one, one whose reserved +/// bits 10 and 11 are not both set (Metal reads it magenta), one of an empty extent, and the zero +/// block (a reserved block mode, a new texture's) are error blocks. +#[test] +fn void_extent_and_error_blocks_read_as_the_rules_say() { + let d = eight(); + let color = [0x1234u16, 0xfedc, 0x0000, 0xffff]; + let block = |low: u64| { + let high = color + .iter() + .enumerate() + .fold(0u64, |acc, (i, &c)| acc | u64::from(c) << (16 * i)); + let mut bytes = [0u8; 16]; + bytes[..8].copy_from_slice(&low.to_le_bytes()); + bytes[8..].copy_from_slice(&high.to_le_bytes()); + bytes + }; + // Mode bits 0-8 `0x1FC`, reserved bits 10-11 set, every extent coordinate all ones. + let constant = 0xDFC | ((1u64 << 52) - 1) << 12; + assert_eq!(d.block_values(&block(constant)), Some(vec![color; 64])); + let why = |low: u64| d.block_values_why(&block(low)).err(); + assert_eq!(why(constant | 1 << 9), Some(Illegal::HdrVoidExtent)); + assert_eq!( + why(constant & !(1 << 11)), + Some(Illegal::VoidExtentReserved) + ); + // Extents of minimum 5 and maximum 5 across. + let empty = 0xDFC | 5 << 12 | 5 << 25 | 1 << 38 | 9 << 51; + assert_eq!(why(empty), Some(Illegal::VoidExtentEmpty)); + assert_eq!( + d.block_values_why(&[0; 16]).err(), + Some(Illegal::ReservedMode) + ); + // Error blocks read magenta: every channel 0 or 1. + let mut out = vec![0; 64 * 16]; + d.decode_into(AstcTexels::Float, &[0; 16], [8, 8, 1], &mut out); + let first: Vec = out[..16] + .as_chunks::<4>() + .0 + .iter() + .map(|&w| f32::from_le_bytes(w)) + .collect(); + assert_eq!(first, [1.0, 0.0, 1.0, 1.0]); +} + +/// A block built by the specification's layout: block mode `0x213` (a 4 x 2 grid of 32-level +/// weights, 40 bits), one partition, luminance direct (mode 0) of the 8-bit endpoints `0x40` and +/// `0xC0` (256 levels fit in the 71 colour bits). Weights of 0 read the first endpoint widened, +/// `e · 257`; weights of 64 (all ones) the second; each read is `(C >> 4) / 4095`. +#[test] +fn a_block_of_the_specification_s_layout_reads_its_endpoints() { + let d = eight(); + let base: u128 = 0x213 | 0x40 << 17 | 0xC0 << 25; + let zero = d.block_values(&base.to_le_bytes()).expect("valid"); + assert!(zero.iter().all(|&t| t == [0x4040, 0x4040, 0x4040, 0xffff])); + let ones = base | ((1u128 << 40) - 1) << 88; + let one = d.block_values(&ones.to_le_bytes()).expect("valid"); + assert!(one.iter().all(|&t| t == [0xc0c0, 0xc0c0, 0xc0c0, 0xffff])); + let value = d.metal_value([0x4040, 0, 0xffff, 0]); + assert_eq!(value, [1028.0 / 4095.0, 0.0, 1.0, 0.0]); + // The sRGB form widens to `e · 256 + 128`, reads the step of `C >> 8` and alpha over 255. + let srgb = AstcDecode::of(PixelFormat::ASTC8x8SRGB).expect("a decode"); + let texels = srgb.block_values(&base.to_le_bytes()).expect("valid"); + assert!(texels + .iter() + .all(|&t| t == [0x4080, 0x4080, 0x4080, 0xff80])); + let step = f32::from(crate::lower::arith::srgb::SRGB_DECODE_STEPS[0x40]); + assert_eq!(srgb.metal_value(texels[0])[0], step / 4095.0); + assert_eq!(srgb.metal_value(texels[0])[3], 1.0); +} + +/// The blocks Metal read for the committed digests: `count` blocks of xorshift64* from +/// `seed | 1`, two words each (low first) and a third draw, which makes 1 in 8 an LDR void-extent +/// block (reserved bits set), half of those with all-ones extents. +fn seeded_blocks(seed: u64, count: usize) -> Vec { + let mut state = seed | 1; + let mut next = || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state.wrapping_mul(0x2545_F491_4F6C_DD1D) + }; + let mut out = Vec::with_capacity(count * 16); + for _ in 0..count { + let (mut low, high, k) = (next(), next(), next()); + if k % 8 == 0 { + low = (low & !0xFFF) | 0xDFC; + if (k >> 8) & 1 == 1 { + low |= ((1 << 52) - 1) << 12; + } + } + out.extend_from_slice(&low.to_le_bytes()); + out.extend_from_slice(&high.to_le_bytes()); + } + out +} + +fn fnv1a(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| { + (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3) + }) +} + +/// Every texel of 1024 seeded blocks (32 x 32 of them, seeded by the LDR form's raw value) of each +/// footprint, linear and sRGB, is Metal's read: the `float` texels' FNV-1a digest equals the +/// digest of what an Apple M3 Max (macOS 27.0.1) read of the same blocks (`texture.read` into +/// `float4`, our probe). Of each footprint 117 to 283 blocks are valid, the rest error blocks of +/// every kind; the probe's wider run (4096 valid-biased blocks a footprint) matched as well. +#[test] +fn seeded_blocks_read_as_metal_read_them() { + const DIGESTS: [(u32, u64, u64); 14] = [ + (204, 0x1ec2_3532_f7f1_3267, 0xeac0_f14e_3953_0337), + (205, 0x8e4e_246a_e848_6e2a, 0xb1cf_2627_d93f_c546), + (206, 0xc623_781c_7ea9_9899, 0xdfe3_b392_ea47_125d), + (207, 0xdd08_c14c_7a5f_3780, 0x0420_3c4a_f814_a7a0), + (208, 0xe44f_f52e_9286_d9c4, 0xf220_12e7_30fa_4242), + (210, 0x564f_e279_bb73_0b0f, 0x01db_e80d_55f7_ef64), + (211, 0x85b6_584e_6ad0_f498, 0xb7d5_305f_87e2_ed09), + (212, 0x0f54_d281_abd1_482e, 0x1726_b4ef_e2b7_f156), + (213, 0x2cf6_29e2_d4d2_8730, 0xf660_ea51_94d0_1e84), + (214, 0xf6e3_2d62_dc3f_0a81, 0x74ed_bfbb_ce3d_0597), + (215, 0x340c_e23a_543b_2199, 0x69fe_1b2e_0cb5_cb34), + (216, 0xe5eb_eef0_6b57_ea2c, 0x979d_0419_fa81_a371), + (217, 0x3473_96ec_0297_8568, 0x4533_32fd_ec0e_d21b), + (218, 0xa285_9133_6da5_5eff, 0x87a5_68d7_f82c_594a), + ]; + for (raw, linear, srgb) in DIGESTS { + let blocks = seeded_blocks(u64::from(raw), 1024); + for (raw, digest) in [(raw, linear), (raw - 18, srgb)] { + let pf = PixelFormat::try_from(raw).expect("an ASTC format"); + let d = AstcDecode::of(pf).expect("a decode"); + let size = [32 * d.width, 32 * d.height, 1]; + let texels = d.decode(AstcTexels::Float, &blocks, size); + assert_eq!(fnv1a(&texels), digest, "{pf:?}"); + let valid = blocks + .as_chunks::<16>() + .0 + .iter() + .filter(|b| d.block_values(b).is_some()) + .count(); + assert!(valid > 100, "{pf:?}: {valid} valid blocks"); + } + } +} + +/// The 8-bit twin holds the code nearest each linear value (at most 1/510 off it) and an sRGB +/// format's own codes `C >> 8`, whose alpha reads exactly. +#[test] +fn the_eight_bit_twin_holds_the_nearest_codes() { + let blocks = seeded_blocks(212, 256); + for pf in [PixelFormat::ASTC8x8LDR, PixelFormat::ASTC8x8SRGB] { + let d = AstcDecode::of(pf).expect("a decode"); + let size = [16 * 8, 16 * 8, 1]; + let exact = d.decode(AstcTexels::Float, &blocks, size); + let codes = d.decode(AstcTexels::Unorm8, &blocks, size); + assert_eq!(codes.len() * 4, exact.len()); + for (i, (&code, &value)) in codes.iter().zip(exact.as_chunks::<4>().0).enumerate() { + let ch = i % 4; + let value = f32::from_le_bytes(value); + let read = f32::from(code) / 255.0; + match (d.srgb, ch) { + (true, 3) => assert_eq!(read, value), + (true, _) => { + let step = crate::lower::arith::srgb::SRGB_DECODE_STEPS[usize::from(code)]; + assert_eq!(f32::from(step) / 4095.0, value); + } + (false, _) => assert!((read - value).abs() <= 1.0 / 510.0, "{read} {value}"), + } + } + } +} + +#[test] +fn the_astc_decode_kernels_are_valid_on_every_committed_profile() { + let profiles = committed_profiles().expect("profiles"); + for pf in [PixelFormat::ASTC4x4LDR, PixelFormat::ASTC12x12SRGB] { + let decode = AstcDecode::of(pf).expect("a decode"); + for texels in [AstcTexels::Unorm8, AstcTexels::Float] { + for (_, p) in &profiles { + assert_valid(typed_module(decode, texels).expect("module"), p); + } + } + } +} + +/// The kernel's texels of `blocks` of a region of `size` of `decode`, in `order`; the texel +/// buffer's words past the region's stay unwritten. +fn kernel_texels( + decode: AstcDecode, + texels: AstcTexels, + blocks: &[u8], + size: [u32; 3], + order: Order, +) -> Vec { + let m = typed_module(decode, texels).expect("module"); + let [w, h, d] = size; + let length = (w * h * d * AstcDecode::texel_bytes(texels)) as usize; + let res = Resources { + buffers: vec![ + Buffer { + slot: Some(SHAPE), + address: None, + bytes: BlockDecodeModule::shape(size).to_vec(), + }, + Buffer { + slot: Some(BLOCKS), + address: None, + bytes: blocks.to_vec(), + }, + Buffer { + slot: Some(TEXELS), + address: None, + bytes: vec![0xcd; length + 64], + }, + ], + push: Vec::new(), + spec: Default::default(), + }; + let groups = |n: u32| n.div_ceil(BlockDecodeModule::LOCAL_SIZE); + let cfg = Config { + order, + workgroups: [groups(w) + 1, groups(h), d + 1], + ..Config::default() + }; + let mut out = run(&m, &cfg, res).expect("run").buffers; + let written = out.swap_remove(2); + assert!(written[length..].iter().all(|&b| b == 0xcd), "{decode:?}"); + written[..length].to_vec() +} + +/// The colour endpoint modes of the partitions of `block`, a valid block that is no void-extent +/// block, and whether it has two planes. +fn modes_of(block: &[u8; 16]) -> (Vec, bool) { + let bits = u128::from_le_bytes(*block); + let mode = super::block_mode((bits & 0x7FF) as u32).expect("a valid mode"); + let count = ((bits >> 11) & 3) as u32 + 1; + if count == 1 { + return (vec![((bits >> 13) & 15) as u32], mode.dual); + } + let low = ((bits >> 23) & 63) as u32; + if low & 3 == 0 { + return (vec![low >> 2; count as usize], mode.dual); + } + // The configuration's high bits lie just below the weights. + let [gw, gh] = mode.grid; + let weight_bits = mode.range.ise_bits(gw * gh * (1 + u32::from(mode.dual))); + let extra = 3 * count - 4; + let config = low | (super::field(bits, 128 - weight_bits - extra, extra) as u32) << 6; + let modes = (0..count) + .map(|i| { + let class = (config & 3) - 1 + ((config >> (2 + i)) & 1); + class << 2 | (config >> (2 + count + 2 * i)) & 3 + }) + .collect(); + (modes, mode.dual) +} + +/// Seeded blocks of `decode` that cover its valid blocks' kinds, then `invalid` error blocks: of +/// the seeded blocks of `seed`, each valid one that adds a colour endpoint mode, a partition +/// count, two planes or a void-extent block seen fewer than `each` times so far. +fn covering_blocks(decode: AstcDecode, seed: u64, each: usize, invalid: usize) -> Vec { + let (mut modes, mut partitions, mut planes, mut void) = ([0; 16], [0; 5], 0, 0); + let (mut good, mut bad) = (Vec::new(), Vec::new()); + for block in seeded_blocks(seed, 8192).as_chunks::<16>().0 { + if decode.block_values(block).is_none() { + if bad.len() < invalid * 16 { + bad.extend_from_slice(block); + } + continue; + } + let bits = u128::from_le_bytes(*block); + if bits & 0x1FF == 0x1FC { + if void < each { + void += 1; + good.extend_from_slice(block); + } + continue; + } + let (kinds, dual) = modes_of(block); + let adds = kinds.iter().any(|&m| modes[m as usize] < each) + || partitions[kinds.len()] < each + || (dual && planes < each); + if adds { + for &m in &kinds { + modes[m as usize] += 1; + } + partitions[kinds.len()] += 1; + planes += usize::from(dual); + good.extend_from_slice(block); + } + } + good.extend(bad); + good +} + +/// The GPU's decode equals the CPU's, in `orders`: the first texel of `size` where they differ, +/// named. +fn assert_kernel_decodes( + decode: AstcDecode, + texels: AstcTexels, + blocks: &[u8], + size: [u32; 3], + orders: &[Order], +) { + let want = decode.decode(texels, blocks, size); + for &order in orders { + let got = kernel_texels(decode, texels, blocks, size, order); + let bytes = AstcDecode::texel_bytes(texels) as usize; + let differs = (got.chunks(bytes).zip(want.chunks(bytes))).position(|(g, w)| g != w); + if let Some(t) = differs { + let [w, h, _] = size.map(|axis| axis as usize); + let (x, y, z) = (t % w, t / w % h, t / (w * h)); + let [bw, bh] = decode.block_extent().map(|axis| axis as usize); + let b = (z * h.div_ceil(bh) + y / bh) * w.div_ceil(bw) + x / bw; + panic!( + "{decode:?} {texels:?} {order:?}: texel ({x}, {y}, {z}) of block {b} \ + {:032x}: {:?} against the CPU's {:?}", + u128::from_le_bytes(blocks[16 * b..16 * b + 16].try_into().expect("a block")), + &got[t * bytes..(t + 1) * bytes], + &want[t * bytes..(t + 1) * bytes], + ); + } + } +} + +/// `blocks` padded with zero blocks (error blocks) to two layers of rows of `across`, and the +/// region of `decode` they fill, its last column and row of blocks partial. +fn two_layers(decode: AstcDecode, mut blocks: Vec, across: usize) -> (Vec, [u32; 3]) { + let rows = (blocks.len() / 16).div_ceil(2 * across); + blocks.resize(2 * rows * across * 16, 0); + let size = [ + across as u32 * decode.width - 1, + rows as u32 * decode.height - 2, + 2, + ]; + (blocks, size) +} + +/// The GPU's decode is the CPU's, bit for bit, linear and sRGB, in regions of two layers with +/// partial blocks at their right and bottom edges: every texel of seeded 4x4 blocks that cover +/// every colour endpoint mode (an HDR one's partition reading magenta), partition count, two +/// planes and void-extent blocks ([`covering_blocks`]) and of error blocks, as `float`s and as +/// 8-bit codes (in both orders); of a dozen such blocks of the 5x5 and 6x6 footprints (fewer and +/// more than 31 texels: the partition function's two forms), and of three of each other +/// footprint, as `float`s. +#[test] +fn the_astc_kernel_is_the_decode_on_every_texel() { + let both = [Order::Forward, Order::Reverse]; + let four = AstcDecode::of(PixelFormat::ASTC4x4LDR).expect("a decode"); + let (blocks, size) = two_layers(four, covering_blocks(four, 204, 2, 4), 8); + for decode in [four, AstcDecode { srgb: true, ..four }] { + assert_kernel_decodes(decode, AstcTexels::Float, &blocks, size, &both[..1]); + assert_kernel_decodes(decode, AstcTexels::Unorm8, &blocks, size, &both); + } + for raw in 205..=218u32 { + let Some(linear) = PixelFormat::try_from(raw).ok().and_then(AstcDecode::of) else { + continue; + }; + let valid = match linear.block_extent() { + [5, 5] | [6, 6] => 12, + _ => 3, + }; + let mut blocks = covering_blocks(linear, u64::from(raw), 1, 0); + blocks.truncate(16 * valid); + blocks.extend_from_slice(&covering_blocks(linear, u64::from(raw), 0, 1)); + let (blocks, size) = two_layers(linear, blocks, 2); + let srgb = AstcDecode { + srgb: true, + ..linear + }; + for decode in [linear, srgb] { + assert_kernel_decodes(decode, AstcTexels::Float, &blocks, size, &both[..1]); + } + } +} + +/// The blocks the comparison above decodes cover every colour endpoint mode, partition count, two +/// planes and void-extent blocks, on the 4x4 footprint (whose small grids leave the fewest valid +/// blocks) and the 12x12. +#[test] +fn the_compared_blocks_cover_every_mode() { + for pf in [PixelFormat::ASTC4x4LDR, PixelFormat::ASTC12x12LDR] { + let decode = AstcDecode::of(pf).expect("a decode"); + let blocks = covering_blocks(decode, u64::from(pf.as_raw()), 2, 0); + let (mut modes, mut partitions, mut planes, mut void) = ([0; 16], [0; 5], 0, 0); + for block in blocks.as_chunks::<16>().0 { + if u128::from_le_bytes(*block) & 0x1FF == 0x1FC { + void += 1; + continue; + } + let (kinds, dual) = modes_of(block); + for m in &kinds { + modes[*m as usize] += 1; + } + partitions[kinds.len()] += 1; + planes += usize::from(dual); + } + assert!(void > 0 && planes > 0, "{pf:?}"); + assert!( + partitions[1..].iter().all(|&n| n > 0), + "{pf:?}: {partitions:?}" + ); + assert!(modes.iter().all(|&n| n > 0), "{pf:?}: {modes:?}"); + } +} diff --git a/crates/metal2vulkan/src/bind/block_decode.rs b/crates/metal2vulkan/src/bind/block_decode.rs index cc509c5ef..bb110c309 100644 --- a/crates/metal2vulkan/src/bind/block_decode.rs +++ b/crates/metal2vulkan/src/bind/block_decode.rs @@ -416,26 +416,26 @@ impl BlockDecodeModule { } /// The binding symbol of the shape in the typed module. -const SHAPE: ResourceSlot = ResourceSlot { +pub(super) const SHAPE: ResourceSlot = ResourceSlot { stage: Stage::Kernel, kind: ResourceKind::Buffer, index: 0, }; /// The binding symbol of the blocks in the typed module. -const BLOCKS: ResourceSlot = ResourceSlot { +pub(super) const BLOCKS: ResourceSlot = ResourceSlot { stage: Stage::Kernel, kind: ResourceKind::Buffer, index: 1, }; /// The binding symbol of the texels in the typed module. -const TEXELS: ResourceSlot = ResourceSlot { +pub(super) const TEXELS: ResourceSlot = ResourceSlot { stage: Stage::Kernel, kind: ResourceKind::Buffer, index: 2, }; /// A `u32[n]` `Private` table initialized to `values`. -fn table(b: &mut ModuleBuilder, u32_: TypeId, values: &[u32]) -> BResult { +pub(super) fn table(b: &mut ModuleBuilder, u32_: TypeId, values: &[u32]) -> BResult { let len = b.constant(Constant::Scalar { ty: u32_, bits: ConstBits(values.len() as u64), @@ -867,16 +867,27 @@ fn binding_of(sym: &Symbol) -> Option { pub fn block_decode_module( device: &Device, decode: BlockDecode, +) -> Result { + decode_module(device, typed_module(decode)?, "block decode") +} + +/// The decode module of `device` of the typed module `m` (whose bindings are the symbols +/// `SHAPE`, `BLOCKS` and `TEXELS`, `what` its kind): checked by the owned verifier against the +/// device's profile (requirements included), serialized, and numbered with the fixed bindings of +/// [`BlockDecodeModule`]. +pub(super) fn decode_module( + device: &Device, + m: TypedModule, + what: &str, ) -> Result { let profile = device.profile(); - let m = typed_module(decode)?; let mut meter = Meter::new(&Budget::default()); crate::spirv::verify::verify(&m, profile, &mut meter)?; let r = crate::spirv::serialize::serialize(m)?; profile.check(&r.requirements).map_err(|c| { Error::Internal(InternalError::new( InternalKind::RequirementsExceedProfile, - format!("the block decode module needs {c:?}"), + format!("the {what} module needs {c:?}"), )) })?; let words = crate::spirv::serialize::relocate(&r, &binding_of)?; diff --git a/crates/metal2vulkan/src/bind/chroma_decode.rs b/crates/metal2vulkan/src/bind/chroma_decode.rs new file mode 100644 index 000000000..8748aac03 --- /dev/null +++ b/crates/metal2vulkan/src/bind/chroma_decode.rs @@ -0,0 +1,257 @@ +//! A 4:2:2 texture's texels as Metal reads them, from its pairs: the texels the decoded twin of a +//! `GBGR422` or `BGRG422` texture holds (the runtime's `chroma_pairs.rs`), which +//! [`chroma_decode_module`] writes on the GPU. +//! +//! **The decode.** Two texels share 4 bytes: their own green codes and one blue and one red code +//! (`G0 B G1 R` for `GBGR422`, `B G0 R G1` for `BGRG422`), sited between the two. Metal reads +//! texel `x` as its own green code and, for red and blue, the codes interpolated at its centre: +//! `(3 c + n + 2) >> 2` of its pair's code `c` and the code `n` of the pair beside it on its side +//! (the pair before an even texel, after an odd one; its own pair at the row's ends), each +//! `code / 255`, alpha 1. Our probe on an Apple M3 Max under macOS 27.0.1 (both formats, 16 x 4 +//! texels of random bytes): every `float` and `half` read, nearest, linear and bicubic sample +//! (`float` and `half`) and gather is bit for bit the one of an `RGBA8Unorm` texture holding those +//! codes, whose treatment their class takes (`metal::texel_format`, `RGBX8Unorm`'s). The +//! twin holds them (`R8G8B8A8_UNORM`, alpha 255), exact, and the device samples and filters it as +//! it does any 8-bit format's texture, which is how Metal samples them. +//! +//! A texel's codes read its row's pairs alone, so a decode is of whole rows. + +use super::block_decode::{decode_module, BlockDecodeModule, BLOCKS, SHAPE, TEXELS}; +use super::ycbcr_convert::{scalar, words_buffer}; +use crate::device::Device; +use crate::error::Error; +use crate::metal::PixelFormat; +use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; +use crate::spirv::error::BResult; +use crate::spirv::ir::{BinOp, ExecMode, ExecModel, IoDir, MemAccess, Type, TypedModule}; +use crate::vk::Format; + +/// The 4:2:2 decode module of `device` for `decode`'s pairs: one invocation per texel on the block +/// decode's bindings and shape ([`BlockDecodeModule`]), built with the typed builder, checked by +/// the owned verifier against the device's profile (requirements included), serialized, and +/// numbered with the fixed bindings. +pub fn chroma_decode_module( + device: &Device, + decode: ChromaDecode, +) -> Result { + decode_module(device, typed_module(decode)?, "4:2:2 decode") +} + +/// How a 4:2:2 format's pairs lie (the module docs). +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum ChromaDecode { + /// `GBGR422`: `G0 B G1 R`. + Gbgr, + /// `BGRG422`: `B G0 R G1`. + Bgrg, +} + +impl ChromaDecode { + /// The decode of a texture of `pf`; `None` for a format of no pairs. + pub fn of(pf: PixelFormat) -> Option { + match pf { + PixelFormat::GBGR422 => Some(ChromaDecode::Gbgr), + PixelFormat::BGRG422 => Some(ChromaDecode::Bgrg), + _ => None, + } + } + + /// Both decodes. + pub const ALL: [ChromaDecode; 2] = [ChromaDecode::Gbgr, ChromaDecode::Bgrg]; + + /// The texels across and down of a pair. + pub fn block_extent(self) -> [u32; 2] { + [2, 1] + } + + /// The bytes of a pair. + pub const BLOCK_BYTES: u32 = 4; + + /// The bytes of a decoded texel. + pub const TEXEL_BYTES: u32 = 4; + + /// The twin's format: `R8G8B8A8_UNORM` codes. + pub fn texel_format(self) -> Format { + Format::R8G8B8A8_UNORM + } + + /// The Metal format of the twin's texels. + pub fn texel_pixel_format(self) -> PixelFormat { + PixelFormat::RGBA8Unorm + } + + /// The byte of a pair (its 4 bytes as a little-endian word, byte `k` at bits `8k`) holding + /// red, blue, and the green of the pair's texel `t` (0 or 1). + fn bytes(self) -> (u32, u32, [u32; 2]) { + match self { + ChromaDecode::Gbgr => (3, 1, [0, 2]), + ChromaDecode::Bgrg => (2, 0, [1, 3]), + } + } + + /// Texel `t` (0 or 1) of `pair` beside `next` (the pair before an even texel, after an odd + /// one), each its 4 bytes as a little-endian word: the twin's codes as a little-endian word + /// (red lowest, alpha 255). + fn texel(self, pair: u32, next: u32, t: usize) -> u32 { + let (r, b, g) = self.bytes(); + let byte = |word: u32, k: u32| (word >> (8 * k)) & 0xff; + let chroma = |k: u32| (3 * byte(pair, k) + byte(next, k) + 2) >> 2; + chroma(r) | byte(pair, g[t]) << 8 | chroma(b) << 16 | 0xff << 24 + } + + /// The twin's texels of whole rows `width` x `height` x `depth` (images one after another) + /// whose `pairs` are laid out as a copy of the rows out of the texture's carrier lays them + /// (each texel's 2 bytes, tight rows), laid out as a copy into the twin reads them. + pub fn decode(self, pairs: &[u8], size: [u32; 3]) -> Vec { + let [width, height, depth] = size.map(|axis| axis as usize); + let mut out = vec![0; width * height * depth * Self::TEXEL_BYTES as usize]; + self.decode_into(pairs, size, &mut out); + out + } + + /// [`decode`](Self::decode) into `out`, which holds exactly the rows' texels. A row of an odd + /// width ends inside a pair, whose bytes it holds whole. + /// + /// # Panics + /// + /// Where `pairs` holds fewer pairs than the rows, or `out` another length. + pub fn decode_into(self, pairs: &[u8], [width, height, depth]: [u32; 3], out: &mut [u8]) { + let (width, rows) = (width as usize, height as usize * depth as usize); + let across = width.div_ceil(2); + assert_eq!(out.len(), width * rows * 4, "the rows' texels"); + let word = |at: usize| { + u32::from_le_bytes([pairs[at], pairs[at + 1], pairs[at + 2], pairs[at + 3]]) + }; + for (y, row) in out.chunks_exact_mut(width * 4).enumerate() { + for (x, texel) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() { + let p = x / 2; + let next = match x % 2 { + 0 => p.saturating_sub(1), + _ => (p + 1).min(across - 1), + }; + let (pair, next) = (word((y * across + p) * 4), word((y * across + next) * 4)); + *texel = self.texel(pair, next, x % 2).to_le_bytes(); + } + } + } +} + +/// The GPU's decode: the module [`chroma_decode_module`] serializes, the same decode as the CPU's +/// ([`ChromaDecode::decode_into`]). One invocation per texel of whole rows (the block decode's +/// dispatch and shape, `BlockDecodeModule::shape`) reads its pair's word, at `(z · height + y) · +/// ceil(width / 2) + x / 2`, and the word of the pair beside it, and writes its texel's word. +fn typed_module(decode: ChromaDecode) -> BResult { + let mut b = crate::spirv::builder::ModuleBuilder::new(); + let u32_ = b.ty(Type::Int { + width: 32, + signed: false, + })?; + let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; + let shape = words_buffer(&mut b, SHAPE, u32_)?; + let pairs = words_buffer(&mut b, BLOCKS, u32_)?; + let texels = words_buffer(&mut b, TEXELS, u32_)?; + let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?; + let void = b.ty(Type::Void)?; + let mut f = b.function(void)?; + let zero = scalar(&mut f, u32_, 0)?; + let invocation = f.module().global_value(invocation)?; + let invocation = f.load(invocation, MemAccess::default())?; + let [x, y, z] = [0, 1, 2].map(|i| f.composite_extract(invocation, &[i])); + let (x, y, z) = (x?, y?, z?); + let shape = f.module().global_value(shape)?; + let mut field = |index: u32| -> BResult<_> { + let index = scalar(&mut f, u32_, u64::from(index))?; + let p = f.access_chain(shape, &[zero, index])?; + f.load(p, MemAccess::default()) + }; + let (width, height, depth) = (field(0)?, field(1)?, field(2)?); + let in_x = f.binary(BinOp::ULessThan, x, width)?; + let in_y = f.binary(BinOp::ULessThan, y, height)?; + let in_z = f.binary(BinOp::ULessThan, z, depth)?; + let inside = f.binary(BinOp::LogicalAnd, in_x, in_y)?; + let inside = f.binary(BinOp::LogicalAnd, inside, in_z)?; + let pairs = f.module().global_value(pairs)?; + let texels = f.module().global_value(texels)?; + let decoded: ArmFn<'_, ()> = Box::new(move |f, _| { + let k = |f: &mut crate::spirv::builder::FunctionBuilder<'_>, v: u32| { + scalar(f, u32_, u64::from(v)) + }; + let one = k(f, 1)?; + // The row's index through the region, and its pairs across. + let row = f.binary(BinOp::IMul, z, height)?; + let row = f.binary(BinOp::IAdd, row, y)?; + let across = f.binary(BinOp::IAdd, width, one)?; + let across = f.binary(BinOp::ShiftRightLogical, across, one)?; + let half = f.binary(BinOp::ShiftRightLogical, x, one)?; + let at = f.binary(BinOp::IMul, row, across)?; + let at = f.binary(BinOp::IAdd, at, half)?; + let p = f.access_chain(pairs, &[zero, at])?; + let pair = f.load(p, MemAccess::default())?; + // The pair beside it: before an even texel, after an odd one, its own at the row's ends. + let odd = f.binary(BinOp::BitwiseAnd, x, one)?; + let odd = f.binary(BinOp::INotEqual, odd, zero)?; + let first = f.binary(BinOp::IEqual, half, zero)?; + let before = f.binary(BinOp::ISub, at, one)?; + let before = f.select(first, at, before)?; + let last = f.binary(BinOp::ISub, across, one)?; + let last = f.binary(BinOp::IEqual, half, last)?; + let after = f.binary(BinOp::IAdd, at, one)?; + let after = f.select(last, at, after)?; + let beside = f.select(odd, after, before)?; + let p = f.access_chain(pairs, &[zero, beside])?; + let next = f.load(p, MemAccess::default())?; + let (r, b, g) = decode.bytes(); + let byte = |f: &mut crate::spirv::builder::FunctionBuilder<'_>, word, at: u32| { + let shift = k(f, 8 * at)?; + let mask = k(f, 0xff)?; + let v = f.binary(BinOp::ShiftRightLogical, word, shift)?; + f.binary(BinOp::BitwiseAnd, v, mask) + }; + // `(3 c + n + 2) >> 2`. + let chroma = |f: &mut crate::spirv::builder::FunctionBuilder<'_>, at: u32| { + let c = byte(f, pair, at)?; + let n = byte(f, next, at)?; + let three = k(f, 3)?; + let two = k(f, 2)?; + let v = f.binary(BinOp::IMul, c, three)?; + let v = f.binary(BinOp::IAdd, v, n)?; + let v = f.binary(BinOp::IAdd, v, two)?; + f.binary(BinOp::ShiftRightLogical, v, two) + }; + let red = chroma(f, r)?; + let blue = chroma(f, b)?; + let green = [byte(f, pair, g[0])?, byte(f, pair, g[1])?]; + let green = f.select(odd, green[1], green[0])?; + let eight = k(f, 8)?; + let sixteen = k(f, 16)?; + let green = f.binary(BinOp::ShiftLeftLogical, green, eight)?; + let blue = f.binary(BinOp::ShiftLeftLogical, blue, sixteen)?; + let alpha = k(f, 0xff << 24)?; + let word = f.binary(BinOp::BitwiseOr, red, green)?; + let word = f.binary(BinOp::BitwiseOr, word, blue)?; + let word = f.binary(BinOp::BitwiseOr, word, alpha)?; + let t = f.binary(BinOp::IMul, row, width)?; + let t = f.binary(BinOp::IAdd, t, x)?; + let ptr = f.access_chain(texels, &[zero, t])?; + f.store(ptr, word, MemAccess::default())?; + Ok(ArmEnd::FallThrough(Vec::new())) + }); + f.if_(&mut (), inside, decoded, None)?; + f.ret(None)?; + let id = f.finish()?; + b.entry( + ExecModel::GLCompute, + id, + vec![ExecMode::LocalSize { + x: BlockDecodeModule::LOCAL_SIZE, + y: BlockDecodeModule::LOCAL_SIZE, + z: 1, + }], + )?; + b.finalize() +} + +#[cfg(test)] +mod tests; diff --git a/crates/metal2vulkan/src/bind/chroma_decode/tests.rs b/crates/metal2vulkan/src/bind/chroma_decode/tests.rs new file mode 100644 index 000000000..f9cdbeb25 --- /dev/null +++ b/crates/metal2vulkan/src/bind/chroma_decode/tests.rs @@ -0,0 +1,152 @@ +use super::{typed_module, ChromaDecode}; +use crate::bind::block_decode::{BlockDecodeModule, BLOCKS, SHAPE, TEXELS}; +use crate::spirv::interp::{run, Buffer, Config, Order, Resources}; +use crate::spirv::testing::{assert_valid, committed_profiles}; + +/// `n` bytes of the xorshift64* stream from `seed`. +fn stream(seed: u64, n: usize) -> Vec { + let mut x = seed; + let mut out = Vec::with_capacity(n + 8); + while out.len() < n { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + out.extend_from_slice(&x.wrapping_mul(0x2545_F491_4F6C_DD1D).to_le_bytes()); + } + out.truncate(n); + out +} + +/// Each texel reads its own green and its red and blue interpolated with the pair beside it, +/// `(3 c + n + 2) >> 2`, alpha 255, in either order; a row's end reads its own pair. +#[test] +fn a_texel_interpolates_red_and_blue_with_the_pair_beside_it() { + // `GBGR422` (G0 B G1 R): pair 0 red 0x40 blue 0x20, pair 1 red 0x80 blue 0x61. + let pairs = [0x10, 0x20, 0x30, 0x40, 0x50, 0x61, 0x70, 0x80]; + let red = |c: u32, n: u32| ((3 * c + n + 2) >> 2) as u8; + assert_eq!( + ChromaDecode::Gbgr.decode(&pairs, [4, 1, 1]), + [ + [0x40, 0x10, 0x20, 0xff], + [red(0x40, 0x80), 0x30, red(0x20, 0x61), 0xff], + [red(0x80, 0x40), 0x50, red(0x61, 0x20), 0xff], + [0x80, 0x70, 0x61, 0xff], + ] + .concat() + ); + // `BGRG422` (B G0 R G1): pair 0 red 0x30 blue 0x10, pair 1 red 0x70 blue 0x50. + assert_eq!( + ChromaDecode::Bgrg.decode(&pairs, [4, 1, 1]), + [ + [0x30, 0x20, 0x10, 0xff], + [red(0x30, 0x70), 0x40, red(0x10, 0x50), 0xff], + [red(0x70, 0x30), 0x61, red(0x50, 0x10), 0xff], + [0x70, 0x80, 0x50, 0xff], + ] + .concat() + ); + // One pair a row reads itself on both sides; rows read their own pairs alone. + assert_eq!( + ChromaDecode::Gbgr.decode(&pairs, [2, 2, 1]), + [ + [0x40, 0x10, 0x20, 0xff], + [0x40, 0x30, 0x20, 0xff], + [0x80, 0x50, 0x61, 0xff], + [0x80, 0x70, 0x61, 0xff], + ] + .concat() + ); +} + +/// Metal's reads of our M3 probe's textures (16 x 4 texels of both formats over the same bytes, +/// each the top byte of one xorshift64* step from `0x422422422`): the FNV-1a digest of the codes +/// of every texel's `float` read (each `c / 255` exactly, row by row) is this decode's. +#[test] +fn the_probe_s_textures_decode_as_metal_reads_them() { + let mut x: u64 = 0x4_2242_2422; + let bytes: Vec = (0..16 * 4 * 2) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + (x.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 56) as u8 + }) + .collect(); + let fnv = |codes: &[u8]| { + codes.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &c| { + (h ^ u64::from(c)).wrapping_mul(0x0100_0000_01b3) + }) + }; + for (decode, digest) in [ + (ChromaDecode::Gbgr, 0x9f08_e255_b1af_8809), + (ChromaDecode::Bgrg, 0xb1c8_3abd_161a_5a90), + ] { + let codes = decode.decode(&bytes, [16, 4, 1]); + assert_eq!(fnv(&codes), digest, "{decode:?}: {:02x?}", &codes[..16]); + } +} + +#[test] +fn the_chroma_decode_kernels_are_valid_on_every_committed_profile() { + let profiles = committed_profiles().expect("profiles"); + for decode in ChromaDecode::ALL { + for (_, p) in &profiles { + assert_valid(typed_module(decode).expect("module"), p); + } + } +} + +/// The kernel's texels of a region `size` of `decode`'s `pairs`; the texel buffer's bytes past the +/// region's stay unwritten. +fn kernel_texels(decode: ChromaDecode, pairs: &[u8], size: [u32; 3]) -> Vec { + let m = typed_module(decode).expect("module"); + let [w, h, d] = size; + let length = (w * h * d * ChromaDecode::TEXEL_BYTES) as usize; + let res = Resources { + buffers: vec![ + Buffer { + slot: Some(SHAPE), + address: None, + bytes: BlockDecodeModule::shape(size).to_vec(), + }, + Buffer { + slot: Some(BLOCKS), + address: None, + bytes: pairs.to_vec(), + }, + Buffer { + slot: Some(TEXELS), + address: None, + bytes: vec![0xcd; length + 64], + }, + ], + push: Vec::new(), + spec: Default::default(), + }; + let groups = |n: u32| n.div_ceil(BlockDecodeModule::LOCAL_SIZE); + let cfg = Config { + order: Order::Forward, + workgroups: [groups(w) + 1, groups(h), d + 1], + ..Config::default() + }; + let mut out = run(&m, &cfg, res).expect("run").buffers; + let written = out.swap_remove(2); + assert!(written[length..].iter().all(|&b| b == 0xcd), "{decode:?}"); + written[..length].to_vec() +} + +/// The kernel writes the CPU's decode on every texel of both orders: random pairs, two images, odd +/// widths and heights, rows of one pair and of one texel. +#[test] +fn the_chroma_kernel_is_the_decode_on_every_texel() { + for (k, decode) in ChromaDecode::ALL.into_iter().enumerate() { + for size in [[16u32, 12, 2], [13, 9, 1], [7, 5, 2], [2, 1, 1], [1, 1, 1]] { + let [w, h, d] = size; + let n = (w.div_ceil(2) * h * d * ChromaDecode::BLOCK_BYTES) as usize; + let pairs = stream(0x422_0000 + k as u64, n); + let cpu = decode.decode(&pairs, size); + let gpu = kernel_texels(decode, &pairs, size); + assert_eq!(gpu, cpu, "{decode:?} {size:?}"); + } + } +} diff --git a/crates/metal2vulkan/src/bind/etc_decode.rs b/crates/metal2vulkan/src/bind/etc_decode.rs new file mode 100644 index 000000000..698ec85b2 --- /dev/null +++ b/crates/metal2vulkan/src/bind/etc_decode.rs @@ -0,0 +1,547 @@ +//! An ETC2 or EAC texture's texels as Metal decodes them, from its blocks: the texels the decoded +//! twin of the texture holds on a device without the format (the runtime's `etc.rs`), which +//! [`etc_decode_module`] writes on the GPU. +//! +//! **The decode** is the Khronos Data Format Specification's (its ETC2 and EAC chapters), written +//! here from the specification. A block is 64 bits read most significant byte first; its texels +//! are numbered down each column (texel `(x, y)` is index `4x + y`). +//! +//! - **ETC2 RGB** ([`EtcDecode::Rgb8`]): bit 33 chooses the individual mode (two 4-bit base +//! colors) or the differential one (a 5-bit base and a 3-bit signed delta per channel), where a +//! red, green or blue sum outside `[0, 31]` selects the T, H or planar mode instead. A texel is +//! its subblock's base plus the modifier its table and 2-bit index pick, a paint color of the T +//! and H modes, or the planar mode's gradient `(x (H - O) + y (V - O) + 4 O + 2) >> 2`, each +//! channel clamped to `[0, 255]`; alpha is 255. +//! - **ETC2 RGB8A1** ([`EtcDecode::Rgb8A1`]): bit 33 is the opaque flag and the individual mode +//! does not exist. With the flag clear, index 2 is transparent black (all four channels 0) in the +//! differential, T and H modes, and the differential mode's modifiers are `0, b, 0, -b`; a planar +//! block is opaque. +//! - **EAC** (the alpha of [`EtcDecode::Rgba8`], [`EtcDecode::R11Unorm`] and the others): an +//! 8-bit base, a 4-bit multiplier `m`, one of sixteen modifier tables and a 3-bit index per +//! texel. Alpha is `clamp(base + modifier m, 0, 255)`; an unsigned 11-bit channel is +//! `clamp(8 base + 4 + 8 modifier m, 0, 2047)` and a signed one `clamp(8 base + 8 modifier m, +//! -1023, 1023)`, where `m = 0` takes the modifier itself instead of `8 modifier m` and a signed +//! base of -128 is -127. `EAC_RGBA8`'s block is the alpha block, then the RGB block; `RG11`'s is +//! red's block, then green's. +//! +//! **Metal's answers** (an Apple M3 Max under macOS 27.0.1, our own probe: 4096 random blocks of +//! each format, every texel read as `float`, equal to this decode's in every channel): an 8-bit +//! channel reads `c / 255`, an sRGB format's color channel the step of Metal's twelve-bit table +//! (`lower::arith::srgb`, as BC1 to BC3's sRGB forms read, `metal::texel_format::srgb_raw`), +//! alpha `c / 255`; an unsigned 11-bit channel reads `c / 2047` and a signed one `c / 1023`, +//! correctly rounded to `f32` (not the 16-bit code the specification widens them to). +//! +//! **The twin's texels** ([`EtcTexels`]): `R8G8B8A8_UNORM` codes of the ETC2 formats and +//! `EAC_RGBA8` either way (an sRGB form's codes too, for a raw view decoded by Metal's table). An 11-bit format's: [`EtcTexels::Compact`] holds the 16-bit +//! normalized code nearest each value (`R16_UNORM`, `R16_SNORM` and their two-channel forms), at +//! most half a 16-bit step off it; [`EtcTexels::Float`] holds the values exactly (`R32_SFLOAT`, +//! `R32G32_SFLOAT`). + +use super::block_decode::{decode_module, BlockDecodeModule}; +use crate::device::Device; +use crate::error::Error; +use crate::metal::PixelFormat; +use crate::vk::Format; + +mod kernel; + +/// The ETC2 and EAC decode module of `device` for `decode`'s blocks into `texels` (the module +/// docs; an sRGB format's is its unorm form's): one invocation per texel on the block decode's +/// bindings and shape ([`BlockDecodeModule`]), built with the typed builder, checked by the owned +/// verifier against the device's profile (requirements included), serialized, and numbered with +/// the fixed bindings. +pub fn etc_decode_module( + device: &Device, + decode: EtcDecode, + texels: EtcTexels, +) -> Result { + decode_module( + device, + kernel::typed_module(decode, texels)?, + "ETC2 and EAC decode", + ) +} + +/// How an ETC2 or EAC format's blocks decode (the module docs). The sRGB forms decode to their +/// unorm forms' codes. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum EtcDecode { + /// `ETC2_RGB8` and its sRGB form: one RGB block. + Rgb8, + /// `ETC2_RGB8A1` and its sRGB form: one RGB block with punch-through alpha. + Rgb8A1, + /// `EAC_RGBA8` and its sRGB form: an alpha block, then an RGB block. + Rgba8, + /// `EAC_R11Unorm`: one unsigned 11-bit block. + R11Unorm, + /// `EAC_R11Snorm`: one signed 11-bit block. + R11Snorm, + /// `EAC_RG11Unorm`: two unsigned 11-bit blocks, red then green. + Rg11Unorm, + /// `EAC_RG11Snorm`: two signed 11-bit blocks, red then green. + Rg11Snorm, +} + +/// The texels a decoded twin of an ETC2 or EAC texture holds (the module docs): they differ for +/// the 11-bit formats alone. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum EtcTexels { + /// 8-bit codes, and an 11-bit format's 16-bit normalized codes nearest Metal's values. + Compact, + /// 8-bit codes, and an 11-bit format's values exactly, as `float`s. + Float, +} + +/// The individual and differential modes' modifier pairs `(a, b)` of each table: index 0 is `a`, +/// 1 is `b`, 2 is `-a` and 3 is `-b`. +const MODIFIERS: [(i32, i32); 8] = [ + (2, 8), + (5, 17), + (9, 29), + (13, 42), + (18, 60), + (24, 80), + (33, 106), + (47, 183), +]; + +/// The T and H modes' distances. +const DISTANCES: [i32; 8] = [3, 6, 11, 16, 23, 32, 41, 64]; + +/// The EAC modifier tables. +const EAC_MODIFIERS: [[i32; 8]; 16] = [ + [-3, -6, -9, -15, 2, 5, 8, 14], + [-3, -7, -10, -13, 2, 6, 9, 12], + [-2, -5, -8, -13, 1, 4, 7, 12], + [-2, -4, -6, -13, 1, 3, 5, 12], + [-3, -6, -8, -12, 2, 5, 7, 11], + [-3, -7, -9, -11, 2, 6, 8, 10], + [-4, -7, -8, -11, 3, 6, 7, 10], + [-3, -5, -8, -11, 2, 4, 7, 10], + [-2, -6, -8, -10, 1, 5, 7, 9], + [-2, -5, -8, -10, 1, 4, 7, 9], + [-2, -4, -8, -10, 1, 3, 7, 9], + [-2, -5, -7, -10, 1, 4, 6, 9], + [-3, -4, -7, -10, 2, 3, 6, 9], + [-1, -2, -3, -10, 0, 1, 2, 9], + [-4, -6, -8, -9, 3, 5, 7, 8], + [-3, -5, -7, -9, 2, 4, 6, 8], +]; + +impl EtcDecode { + /// The decode of `pf`'s blocks: the ETC2 and EAC formats, the sRGB forms decoding to the unorm + /// forms' codes; `None` for every other format. + pub fn of(pf: PixelFormat) -> Option { + use PixelFormat as P; + Some(match pf { + P::ETC2RGB8 | P::ETC2RGB8SRGB => EtcDecode::Rgb8, + P::ETC2RGB8A1 | P::ETC2RGB8A1SRGB => EtcDecode::Rgb8A1, + P::EACRGBA8 | P::EACRGBA8SRGB => EtcDecode::Rgba8, + P::EACR11Unorm => EtcDecode::R11Unorm, + P::EACR11Snorm => EtcDecode::R11Snorm, + P::EACRG11Unorm => EtcDecode::Rg11Unorm, + P::EACRG11Snorm => EtcDecode::Rg11Snorm, + _ => return None, + }) + } + + /// Every decode. + pub const ALL: [EtcDecode; 7] = [ + EtcDecode::Rgb8, + EtcDecode::Rgb8A1, + EtcDecode::Rgba8, + EtcDecode::R11Unorm, + EtcDecode::R11Snorm, + EtcDecode::Rg11Unorm, + EtcDecode::Rg11Snorm, + ]; + + /// The texels across and down of a block: 4 x 4. + pub fn block_extent(self) -> [u32; 2] { + [4, 4] + } + + /// The bytes of a block: 8, or 16 for `EAC_RGBA8` and the `RG11` formats. + pub fn block_bytes(self) -> u32 { + match self { + EtcDecode::Rgba8 | EtcDecode::Rg11Unorm | EtcDecode::Rg11Snorm => 16, + _ => 8, + } + } + + /// Whether the decode's values are 11-bit ones (the `R11` and `RG11` formats'), which no 8-bit + /// code holds. + pub fn eleven_bit(self) -> bool { + !matches!(self, EtcDecode::Rgb8 | EtcDecode::Rgb8A1 | EtcDecode::Rgba8) + } + + /// The bytes of a twin's texel of `texels`: 4 for the 8-bit codes; an 11-bit format's 2 or 4 + /// a channel. + pub fn texel_bytes(self, texels: EtcTexels) -> u32 { + let channel = match texels { + EtcTexels::Compact => 2, + EtcTexels::Float => 4, + }; + match self { + EtcDecode::Rgb8 | EtcDecode::Rgb8A1 | EtcDecode::Rgba8 => 4, + EtcDecode::R11Unorm | EtcDecode::R11Snorm => channel, + EtcDecode::Rg11Unorm | EtcDecode::Rg11Snorm => 2 * channel, + } + } + + /// The Vulkan format of a twin's texels of `texels`: `R8G8B8A8_UNORM` codes; an 11-bit + /// format's 16-bit normalized codes or `float` values. + pub fn texel_format(self, texels: EtcTexels) -> Format { + use EtcTexels as T; + match (self, texels) { + (EtcDecode::Rgb8 | EtcDecode::Rgb8A1 | EtcDecode::Rgba8, _) => Format::R8G8B8A8_UNORM, + (EtcDecode::R11Unorm, T::Compact) => Format::R16_UNORM, + (EtcDecode::R11Snorm, T::Compact) => Format::R16_SNORM, + (EtcDecode::Rg11Unorm, T::Compact) => Format::R16G16_UNORM, + (EtcDecode::Rg11Snorm, T::Compact) => Format::R16G16_SNORM, + (EtcDecode::R11Unorm | EtcDecode::R11Snorm, T::Float) => Format::R32_SFLOAT, + (EtcDecode::Rg11Unorm | EtcDecode::Rg11Snorm, T::Float) => Format::R32G32_SFLOAT, + } + } + + /// The Metal pixel format whose texels a twin's of `texels` are. + pub fn texel_pixel_format(self, texels: EtcTexels) -> PixelFormat { + use EtcTexels as T; + match (self, texels) { + (EtcDecode::Rgb8 | EtcDecode::Rgb8A1 | EtcDecode::Rgba8, _) => PixelFormat::RGBA8Unorm, + (EtcDecode::R11Unorm, T::Compact) => PixelFormat::R16Unorm, + (EtcDecode::R11Snorm, T::Compact) => PixelFormat::R16Snorm, + (EtcDecode::Rg11Unorm, T::Compact) => PixelFormat::RG16Unorm, + (EtcDecode::Rg11Snorm, T::Compact) => PixelFormat::RG16Snorm, + (EtcDecode::R11Unorm | EtcDecode::R11Snorm, T::Float) => PixelFormat::R32Float, + (EtcDecode::Rg11Unorm | EtcDecode::Rg11Snorm, T::Float) => PixelFormat::RG32Float, + } + } + + /// The values of the 16 texels of `block`, row-major (texel `(x, y)` at `4y + x`): the packed + /// 8-bit codes, red in the low byte, or an 11-bit format's values (red, then an `RG11` + /// format's green; 0 elsewhere). + pub fn block_values(self, block: &[u8]) -> [[i32; 2]; 16] { + let codes = |[r, g, b, a]: [u8; 4]| i32::from_le_bytes([r, g, b, a]); + let word = |block: &[u8]| u64::from_be_bytes(block[..8].try_into().expect("8 bytes")); + match self { + EtcDecode::Rgb8 | EtcDecode::Rgb8A1 => { + let texels = rgb_block(word(block), self == EtcDecode::Rgb8A1); + std::array::from_fn(|j| [codes(texels[j]), 0]) + } + EtcDecode::Rgba8 => { + let alpha = eac_block(word(block), Channel::Alpha); + let texels = rgb_block(word(&block[8..]), false); + std::array::from_fn(|j| { + let [r, g, b, _] = texels[j]; + [codes([r, g, b, alpha[j] as u8]), 0] + }) + } + EtcDecode::R11Unorm | EtcDecode::R11Snorm => { + let red = eac_block(word(block), self.channel()); + std::array::from_fn(|j| [red[j], 0]) + } + EtcDecode::Rg11Unorm | EtcDecode::Rg11Snorm => { + let red = eac_block(word(block), self.channel()); + let green = eac_block(word(&block[8..]), self.channel()); + std::array::from_fn(|j| [red[j], green[j]]) + } + } + } + + /// The `float` Metal reads of an 11-bit format's value `c`: `c / 2047` (unsigned) or + /// `c / 1023` (signed), correctly rounded. (`c` over the divisor lies on no `f32` tie, so + /// rounding the `f64` quotient again is the correctly rounded `f32`.) + pub fn metal_value(self, c: i32) -> f32 { + (f64::from(c) / f64::from(self.channel().divisor())) as f32 + } + + /// The channel kind of an 11-bit format's blocks. + fn channel(self) -> Channel { + match self { + EtcDecode::R11Snorm | EtcDecode::Rg11Snorm => Channel::Signed, + _ => Channel::Unsigned, + } + } + + /// The twin's texel of `texels` of a texel whose values are `v` ([`block_values`]), into + /// `out` ([`texel_bytes`](Self::texel_bytes) of them). + /// + /// [`block_values`]: Self::block_values + fn twin_texel(self, texels: EtcTexels, v: [i32; 2], out: &mut [u8]) { + if !self.eleven_bit() { + out.copy_from_slice(&v[0].to_le_bytes()); + return; + } + let divisor = self.channel().divisor(); + for (k, out) in out + .chunks_exact_mut(out.len() / self.channels()) + .enumerate() + { + match texels { + // The 16-bit normalized code nearest `c / divisor`: `c · (2^b - 1) / divisor` + // rounded, which is never a tie (the divisor is odd). + EtcTexels::Compact => { + let top = match self.channel() { + Channel::Signed => 32767, + _ => 65535, + }; + let c = v[k]; + let code = c.signum() * ((2 * c.abs() * top + divisor) / (2 * divisor)); + out.copy_from_slice(&(code as i16 as u16).to_le_bytes()); + } + EtcTexels::Float => out.copy_from_slice(&self.metal_value(v[k]).to_le_bytes()), + } + } + } + + /// The channels of a decoded texel: 4 codes count as one word, an `RG11` format's 2. + fn channels(self) -> usize { + match self { + EtcDecode::Rg11Unorm | EtcDecode::Rg11Snorm => 2, + _ => 1, + } + } + + /// The twin's texels of `texels` of a region `width` x `height` x `depth` whose `blocks` are + /// laid out as a copy of the region out of the texture lays them (tight rows of blocks, each + /// image's after the last), laid out as a copy into the twin reads them. + pub fn decode(self, texels: EtcTexels, blocks: &[u8], size: [u32; 3]) -> Vec { + let [width, height, depth] = size.map(|axis| axis as usize); + let bytes = self.texel_bytes(texels) as usize; + let mut out = vec![0; width * height * depth * bytes]; + self.decode_into(texels, blocks, size, &mut out); + out + } + + /// [`decode`](Self::decode) into `out`, which holds exactly the region's texels: so bands of + /// a region's block rows can be decoded on several threads into one buffer. + /// + /// # Panics + /// + /// Where `blocks` holds fewer blocks than the region, or `out` another length. + pub fn decode_into( + self, + texels: EtcTexels, + blocks: &[u8], + [width, height, depth]: [u32; 3], + out: &mut [u8], + ) { + let size = self.block_bytes() as usize; + let (width, height) = (width as usize, height as usize); + let (across, down) = (width.div_ceil(4), height.div_ceil(4)); + let bytes = self.texel_bytes(texels) as usize; + let row = width * bytes; + assert_eq!( + out.len(), + row * height * depth as usize, + "the region's texels" + ); + for b in 0..across * down * depth as usize { + let values = self.block_values(&blocks[b * size..(b + 1) * size]); + let (z, by, bx) = (b / (across * down), b / across % down, b % across); + for (ty, y) in (by * 4..(by * 4 + 4).min(height)).enumerate() { + for (tx, x) in (bx * 4..(bx * 4 + 4).min(width)).enumerate() { + let at = (z * height + y) * row + x * bytes; + self.twin_texel(texels, values[ty * 4 + tx], &mut out[at..at + bytes]); + } + } + } + } +} + +/// Bits `lo..=hi` of `v`. +fn bits(v: u64, hi: u32, lo: u32) -> i32 { + ((v >> lo) & ((1 << (hi - lo + 1)) - 1)) as i32 +} + +/// `v`, of `n` bits, widened to 8 by replicating its high bits. +fn widen(v: i32, n: u32) -> i32 { + (v << (8 - n)) | (v >> (2 * n - 8)) +} + +/// A 3-bit two's complement delta. +fn delta(v: i32) -> i32 { + if v & 4 != 0 { + v - 8 + } else { + v + } +} + +/// `v` clamped to a byte. +fn byte(v: i32) -> u8 { + v.clamp(0, 255) as u8 +} + +/// Each of a color's channels plus `d`, clamped. +fn shift([r, g, b]: [i32; 3], d: i32) -> [u8; 3] { + [byte(r + d), byte(g + d), byte(b + d)] +} + +/// The texels of an ETC2 RGB block `v` (most significant byte first), row-major, red to alpha; +/// `punch`: the RGB8A1 form, whose bit 33 is the opaque flag. +fn rgb_block(v: u64, punch: bool) -> [[u8; 4]; 16] { + let flag = bits(v, 33, 33) == 1; + let opaque = !punch || flag; + let differential = punch || flag; + // Texel `p`'s 2-bit index (texels numbered down each column). + let index = |p: u32| (bits(v, 16 + p, 16 + p) << 1 | bits(v, p, p)) as usize; + let mut out = [[0u8; 4]; 16]; + let mut put = |p: u32, rgb: Option<[u8; 3]>| { + let (x, y) = (p / 4, p % 4); + out[(4 * y + x) as usize] = match rgb { + Some([r, g, b]) => [r, g, b, 255], + None => [0; 4], + }; + }; + let (base1, base2) = if differential { + let (r, g, b) = (bits(v, 63, 59), bits(v, 55, 51), bits(v, 47, 43)); + let (dr, dg, db) = ( + delta(bits(v, 58, 56)), + delta(bits(v, 50, 48)), + delta(bits(v, 42, 40)), + ); + let outside = |c: i32| !(0..=31).contains(&c); + if outside(r + dr) || outside(g + dg) { + // The T mode (red overflows) or the H mode (green does): four paint colors. + let paint = if outside(r + dr) { + let c1 = [ + bits(v, 60, 59) << 2 | bits(v, 57, 56), + bits(v, 55, 52), + bits(v, 51, 48), + ] + .map(|c| widen(c, 4)); + let c2 = [bits(v, 47, 44), bits(v, 43, 40), bits(v, 39, 36)].map(|c| widen(c, 4)); + let d = DISTANCES[(bits(v, 35, 34) << 1 | bits(v, 32, 32)) as usize]; + [shift(c1, 0), shift(c2, d), shift(c2, 0), shift(c2, -d)] + } else { + let c1 = [ + bits(v, 62, 59), + bits(v, 58, 56) << 1 | bits(v, 52, 52), + bits(v, 51, 51) << 3 | bits(v, 49, 47), + ] + .map(|c| widen(c, 4)); + let c2 = [bits(v, 46, 43), bits(v, 42, 39), bits(v, 38, 35)].map(|c| widen(c, 4)); + let key = |[r, g, b]: [i32; 3]| r << 16 | g << 8 | b; + let low = i32::from(key(c1) >= key(c2)); + let d = DISTANCES[(bits(v, 34, 34) << 2 | bits(v, 32, 32) << 1 | low) as usize]; + [shift(c1, d), shift(c1, -d), shift(c2, d), shift(c2, -d)] + }; + for p in 0..16 { + let i = index(p); + put(p, (opaque || i != 2).then_some(paint[i])); + } + return out; + } + if outside(b + db) { + // The planar mode: always opaque. + let o = [ + widen(bits(v, 62, 57), 6), + widen(bits(v, 56, 56) << 6 | bits(v, 54, 49), 7), + widen( + bits(v, 48, 48) << 5 | bits(v, 44, 43) << 3 | bits(v, 41, 39), + 6, + ), + ]; + let h = [ + widen(bits(v, 38, 34) << 1 | bits(v, 32, 32), 6), + widen(bits(v, 31, 25), 7), + widen(bits(v, 24, 19), 6), + ]; + let vert = [ + widen(bits(v, 18, 13), 6), + widen(bits(v, 12, 6), 7), + widen(bits(v, 5, 0), 6), + ]; + for p in 0..16 { + let (x, y) = ((p / 4) as i32, (p % 4) as i32); + let channel = + |k: usize| byte((x * (h[k] - o[k]) + y * (vert[k] - o[k]) + 4 * o[k] + 2) >> 2); + put(p, Some([channel(0), channel(1), channel(2)])); + } + return out; + } + ( + [r, g, b].map(|c| widen(c, 5)), + [r + dr, g + dg, b + db].map(|c| widen(c, 5)), + ) + } else { + ( + [bits(v, 63, 60), bits(v, 55, 52), bits(v, 47, 44)].map(|c| widen(c, 4)), + [bits(v, 59, 56), bits(v, 51, 48), bits(v, 43, 40)].map(|c| widen(c, 4)), + ) + }; + let (table1, table2) = (bits(v, 39, 37) as usize, bits(v, 36, 34) as usize); + let flip = bits(v, 32, 32) == 1; + for p in 0..16 { + let (x, y) = (p / 4, p % 4); + let second = if flip { y >= 2 } else { x >= 2 }; + let (base, (a, b)) = match second { + true => (base2, MODIFIERS[table2]), + false => (base1, MODIFIERS[table1]), + }; + let i = index(p); + let modifier = match opaque { + true => [a, b, -a, -b][i], + false => [0, b, 0, -b][i], + }; + put(p, (opaque || i != 2).then(|| shift(base, modifier))); + } + out +} + +/// What an EAC block's values are. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Channel { + /// `EAC_RGBA8`'s alpha: 8-bit codes. + Alpha, + /// An unsigned 11-bit channel, `[0, 2047]`. + Unsigned, + /// A signed 11-bit channel, `[-1023, 1023]`. + Signed, +} + +impl Channel { + /// The divisor of an 11-bit channel's value: 2047, or 1023 for a signed one. + fn divisor(self) -> i32 { + match self { + Channel::Signed => 1023, + _ => 2047, + } + } +} + +/// The values of an EAC block `v` (most significant byte first), row-major. +fn eac_block(v: u64, channel: Channel) -> [i32; 16] { + let base = bits(v, 63, 56); + let multiplier = bits(v, 55, 52); + let table = EAC_MODIFIERS[bits(v, 51, 48) as usize]; + let mut out = [0; 16]; + for p in 0..16u32 { + let modifier = table[bits(v, 47 - 3 * p, 45 - 3 * p) as usize]; + // An 11-bit block with a multiplier of 0 adds the modifier itself, as an eighth of a step. + let step = match multiplier { + 0 => modifier, + m => 8 * modifier * m, + }; + let value = match channel { + Channel::Alpha => (base + modifier * multiplier).clamp(0, 255), + Channel::Unsigned => (8 * base + 4 + step).clamp(0, 2047), + Channel::Signed => { + let base = (base as u8 as i8).max(-127); + (8 * i32::from(base) + step).clamp(-1023, 1023) + } + }; + let (x, y) = (p / 4, p % 4); + out[(4 * y + x) as usize] = value; + } + out +} + +#[cfg(test)] +mod tests; diff --git a/crates/metal2vulkan/src/bind/etc_decode/kernel.rs b/crates/metal2vulkan/src/bind/etc_decode/kernel.rs new file mode 100644 index 000000000..51279a435 --- /dev/null +++ b/crates/metal2vulkan/src/bind/etc_decode/kernel.rs @@ -0,0 +1,796 @@ +//! The GPU's decode of ETC2 and EAC blocks into a decoded twin's texels: the module +//! [`etc_decode_module`](super::etc_decode_module) serializes, the same decode as the CPU's +//! ([`EtcDecode::decode_into`]) in integer operations alone. +//! +//! The dispatch and shape are the block decode's (`BlockDecodeModule::shape`): one invocation per +//! texel of the region reads its block's 64-bit words, each the byte-swapped pair of the buffer's +//! little-endian words (a block is read most significant byte first), and writes its texel +//! straight-line: an ETC2 RGB block's five modes are each decoded and the block's own selected. An +//! `R11` format's compact texels are 2 bytes, two to a word: the invocation of each even texel +//! (counted through the region row by row, image by image) writes the word of it and the next. + +use super::{Channel, EtcDecode, EtcTexels, DISTANCES, EAC_MODIFIERS, MODIFIERS}; +use crate::bind::block_decode::{table, BlockDecodeModule, BLOCKS, SHAPE, TEXELS}; +use crate::bind::ycbcr_convert::{scalar, words_buffer}; +use crate::lower::arith::exact_division::div_exact; +use crate::lower::arith::legal::{Form, Held}; +use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; +use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; +use crate::spirv::error::BResult; +use crate::spirv::ids::{GlobalId, TypeId, Value}; +use crate::spirv::ir::{ + BinOp, ConstBits, Constant, ConvOp, ExecMode, ExecModel, IoDir, MemAccess, Type, TypedModule, +}; + +/// The decode of one texel: the function it builds in, and what every step reads. +struct E<'a, 'b> { + f: &'a mut FunctionBuilder<'b>, + u32_: TypeId, + zero: Value, + /// The blocks' words. + blocks: Value, + /// The region's blocks across and down. + across: Value, + down: Value, + /// The individual and differential modes' modifier pairs, `a` then `b` of each table + /// (`MODIFIERS`). + modifiers: GlobalId, + /// The T and H modes' distances (`DISTANCES`). + distances: GlobalId, + /// The EAC modifier tables, eight entries each, two's complement (`EAC_MODIFIERS`). + eac: GlobalId, +} + +/// A texel's place in its region: its column, row and image. +#[derive(Clone, Copy)] +struct At { + x: Value, + y: Value, + z: Value, +} + +impl E<'_, '_> { + fn k(&mut self, v: u32) -> BResult { + scalar(self.f, self.u32_, u64::from(v)) + } + + /// The two's complement constant `v`. + fn signed(&mut self, v: i32) -> BResult { + self.k(v as u32) + } + + /// The `bool` constant `v`. + fn boolean(&mut self, v: bool) -> BResult { + let ty = self.f.module().ty(Type::Bool)?; + let c = self.f.module().constant(Constant::Scalar { + ty, + bits: ConstBits(u64::from(v)), + })?; + self.f.module().const_value(c) + } + + fn op(&mut self, op: BinOp, a: Value, b: Value) -> BResult { + self.f.binary(op, a, b) + } + + fn opk(&mut self, op: BinOp, a: Value, b: u32) -> BResult { + let b = self.k(b)?; + self.f.binary(op, a, b) + } + + fn add(&mut self, a: Value, b: Value) -> BResult { + self.op(BinOp::IAdd, a, b) + } + + fn sel(&mut self, c: Value, a: Value, b: Value) -> BResult { + self.f.select(c, a, b) + } + + fn and(&mut self, a: Value, b: Value) -> BResult { + self.op(BinOp::LogicalAnd, a, b) + } + + fn not(&mut self, a: Value) -> BResult { + self.f.unary(crate::spirv::ir::UnOp::LogicalNot, a) + } + + /// `0 - v`. + fn negate(&mut self, v: Value) -> BResult { + self.op(BinOp::ISub, self.zero, v) + } + + /// `(v >> at) & (2^n - 1)` for a constant field. + fn field(&mut self, v: Value, at: u32, n: u32) -> BResult { + let shifted = self.opk(BinOp::ShiftRightLogical, v, at)?; + self.opk(BinOp::BitwiseAnd, shifted, (1 << n) - 1) + } + + /// Whether bit `at` of `v` is set. + fn bit(&mut self, v: Value, at: u32) -> BResult { + let field = self.field(v, at, 1)?; + self.opk(BinOp::INotEqual, field, 0) + } + + /// `a << n | b`, two fields joined. + fn join(&mut self, a: Value, n: u32, b: Value) -> BResult { + let a = self.opk(BinOp::ShiftLeftLogical, a, n)?; + self.op(BinOp::BitwiseOr, a, b) + } + + /// `v`, of `n` bits, widened to 8 by replicating its high bits (`super::widen`). + fn widen(&mut self, v: Value, n: u32) -> BResult { + let high = self.opk(BinOp::ShiftLeftLogical, v, 8 - n)?; + let low = self.opk(BinOp::ShiftRightLogical, v, 2 * n - 8)?; + self.op(BinOp::BitwiseOr, high, low) + } + + /// The `n`-bit two's complement field `v`, sign-extended. + fn extend(&mut self, v: Value, n: u32) -> BResult { + let up = self.opk(BinOp::ShiftLeftLogical, v, 32 - n)?; + self.opk(BinOp::ShiftRightArithmetic, up, 32 - n) + } + + /// The signed `v` clamped to `[lo, hi]`. + fn clamp(&mut self, v: Value, lo: i32, hi: i32) -> BResult { + let (lo, hi) = (self.signed(lo)?, self.signed(hi)?); + let below = self.op(BinOp::SLessThan, v, lo)?; + let above = self.op(BinOp::SGreaterThan, v, hi)?; + let v = self.sel(above, hi, v)?; + self.sel(below, lo, v) + } + + /// Entry `index` of the `Private` table `table`. + fn entry(&mut self, table: GlobalId, index: Value) -> BResult { + let table = self.f.module().global_value(table)?; + let p = self.f.access_chain(table, &[index])?; + self.f.load(p, MemAccess::default()) + } + + /// `w` with its bytes reversed. + fn swap(&mut self, w: Value) -> BResult { + let b0 = self.opk(BinOp::ShiftLeftLogical, w, 24)?; + let b1 = self.opk(BinOp::BitwiseAnd, w, 0xff00)?; + let b1 = self.opk(BinOp::ShiftLeftLogical, b1, 8)?; + let b2 = self.opk(BinOp::ShiftRightLogical, w, 8)?; + let b2 = self.opk(BinOp::BitwiseAnd, b2, 0xff00)?; + let b3 = self.opk(BinOp::ShiftRightLogical, w, 24)?; + let v = self.op(BinOp::BitwiseOr, b0, b1)?; + let v = self.op(BinOp::BitwiseOr, v, b2)?; + self.op(BinOp::BitwiseOr, v, b3) + } + + /// The texel's block's first word, `((z · down + y / 4) · across + x / 4) · words`, and its + /// index in the block numbered down each column, `4 (x mod 4) + y mod 4`, with its column and + /// row in the block. + fn place(&mut self, at: At, words: u32) -> BResult<(Value, [Value; 3])> { + let row = self.op(BinOp::IMul, at.z, self.down)?; + let block_y = self.opk(BinOp::ShiftRightLogical, at.y, 2)?; + let row = self.add(row, block_y)?; + let block = self.op(BinOp::IMul, row, self.across)?; + let block_x = self.opk(BinOp::ShiftRightLogical, at.x, 2)?; + let block = self.add(block, block_x)?; + let base = self.opk(BinOp::IMul, block, words)?; + let bx = self.opk(BinOp::BitwiseAnd, at.x, 3)?; + let by = self.opk(BinOp::BitwiseAnd, at.y, 3)?; + let p = self.join(bx, 2, by)?; + Ok((base, [p, bx, by])) + } + + /// The high and low 32 bits of the 64-bit block half `half` (0 or 1) of the block whose first + /// word is `base`. + fn half(&mut self, base: Value, half: u32) -> BResult<[Value; 2]> { + let mut out = [self.zero; 2]; + for (k, word) in out.iter_mut().enumerate() { + let index = self.opk(BinOp::IAdd, base, 2 * half + k as u32)?; + let p = self.f.access_chain(self.blocks, &[self.zero, index])?; + let raw = self.f.load(p, MemAccess::default())?; + *word = self.swap(raw)?; + } + Ok(out) + } + + /// The value of texel `p` (numbered down each column) of the EAC block `[hi, lo]` as + /// `channel` reads it (`super::eac_block`), two's complement. + fn eac(&mut self, [hi, lo]: [Value; 2], p: Value, channel: Channel) -> BResult { + let base = self.field(hi, 24, 8)?; + let multiplier = self.field(hi, 20, 4)?; + let table = self.field(hi, 16, 4)?; + // The texel's 3-bit index from bit `s = 45 - 3 p` of the 64: in the high word past 32, in + // the low word below 30, across both at 30. + let three_p = self.opk(BinOp::IMul, p, 3)?; + let k45 = self.k(45)?; + let s = self.op(BinOp::ISub, k45, three_p)?; + let high_shift = self.opk(BinOp::ISub, s, 32)?; + let high_shift = self.opk(BinOp::BitwiseAnd, high_shift, 31)?; + let from_high = self.op(BinOp::ShiftRightLogical, hi, high_shift)?; + let low_shift = self.opk(BinOp::BitwiseAnd, s, 31)?; + let from_low = self.op(BinOp::ShiftRightLogical, lo, low_shift)?; + let k32 = self.k(32)?; + let up = self.op(BinOp::ISub, k32, s)?; + let up = self.opk(BinOp::BitwiseAnd, up, 31)?; + let carried = self.op(BinOp::ShiftLeftLogical, hi, up)?; + let across = self.opk(BinOp::UGreaterThan, s, 29)?; + let carried = self.sel(across, carried, self.zero)?; + let from_low = self.op(BinOp::BitwiseOr, from_low, carried)?; + let in_high = self.opk(BinOp::UGreaterThanEqual, s, 32)?; + let index = self.sel(in_high, from_high, from_low)?; + let index = self.opk(BinOp::BitwiseAnd, index, 7)?; + let entry = self.opk(BinOp::ShiftLeftLogical, table, 3)?; + let entry = self.add(entry, index)?; + let modifier = self.entry(self.eac, entry)?; + let scaled = self.op(BinOp::IMul, modifier, multiplier)?; + if channel == Channel::Alpha { + let sum = self.add(base, scaled)?; + return self.clamp(sum, 0, 255); + } + // A multiplier of 0 adds the modifier itself, an eighth of a step. + let none = self.opk(BinOp::IEqual, multiplier, 0)?; + let eight = self.opk(BinOp::ShiftLeftLogical, scaled, 3)?; + let step = self.sel(none, modifier, eight)?; + match channel { + Channel::Unsigned => { + let base = self.opk(BinOp::ShiftLeftLogical, base, 3)?; + let base = self.opk(BinOp::IAdd, base, 4)?; + let sum = self.add(base, step)?; + self.clamp(sum, 0, 2047) + } + _ => { + // A signed base of -128 is -127. + let base = self.extend(base, 8)?; + let low = self.signed(-127)?; + let below = self.op(BinOp::SLessThan, base, low)?; + let base = self.sel(below, low, base)?; + let base = self.opk(BinOp::ShiftLeftLogical, base, 3)?; + let sum = self.add(base, step)?; + self.clamp(sum, -1023, 1023) + } + } + } + + /// The four 8-bit codes of texel `p` (numbered down each column, at column `bx` and row `by` + /// of its block) of the ETC2 RGB block `[hi, lo]` (`super::rgb_block`): `punch`, the RGB8A1 + /// form's. + fn rgb( + &mut self, + [hi, lo]: [Value; 2], + [p, bx, by]: [Value; 3], + punch: bool, + ) -> BResult<[Value; 4]> { + let flag = self.bit(hi, 1)?; + let yes = self.boolean(true)?; + let (opaque, differential) = match punch { + true => (flag, yes), + false => (yes, flag), + }; + // The texel's 2-bit index: bit `16 + p` above bit `p`. + let msb_at = self.opk(BinOp::IAdd, p, 16)?; + let msb = self.op(BinOp::ShiftRightLogical, lo, msb_at)?; + let msb = self.opk(BinOp::BitwiseAnd, msb, 1)?; + let lsb = self.op(BinOp::ShiftRightLogical, lo, p)?; + let lsb = self.opk(BinOp::BitwiseAnd, lsb, 1)?; + let index = self.join(msb, 1, lsb)?; + let odd = self.opk(BinOp::IEqual, lsb, 1)?; + let index_is = |e: &mut Self, v: u32| e.opk(BinOp::IEqual, index, v); + // The differential mode's bases and deltas, and whether a sum leaves `[0, 31]` (a + // negative one wraps past 31). + let mut diff = [[self.zero; 3]; 2]; + let mut outside = [self.zero; 3]; + for (ch, at) in [27, 19, 11].into_iter().enumerate() { + let c = self.field(hi, at, 5)?; + let d = self.field(hi, at - 3, 3)?; + let d = self.extend(d, 3)?; + let sum = self.add(c, d)?; + outside[ch] = self.opk(BinOp::UGreaterThan, sum, 31)?; + let sum = self.opk(BinOp::BitwiseAnd, sum, 31)?; + diff[0][ch] = self.widen(c, 5)?; + diff[1][ch] = self.widen(sum, 5)?; + } + // The individual mode's. + let mut individual = [[self.zero; 3]; 2]; + for (ch, at) in [28, 20, 12].into_iter().enumerate() { + let first = self.field(hi, at, 4)?; + let second = self.field(hi, at - 4, 4)?; + individual[0][ch] = self.widen(first, 4)?; + individual[1][ch] = self.widen(second, 4)?; + } + // The individual and differential modes' texel: its subblock's base plus the modifier + // its table and index pick (`[a, b, -a, -b]`, or `[0, b, 0, -b]` where not opaque). + let flip = self.bit(hi, 0)?; + let low_x = self.opk(BinOp::UGreaterThanEqual, bx, 2)?; + let low_y = self.opk(BinOp::UGreaterThanEqual, by, 2)?; + let second = self.sel(flip, low_y, low_x)?; + let first_table = self.field(hi, 5, 3)?; + let second_table = self.field(hi, 2, 3)?; + let table = self.sel(second, second_table, first_table)?; + let a_at = self.opk(BinOp::ShiftLeftLogical, table, 1)?; + let b_at = self.opk(BinOp::IAdd, a_at, 1)?; + let a = self.entry(self.modifiers, a_at)?; + let b = self.entry(self.modifiers, b_at)?; + let a = self.sel(opaque, a, self.zero)?; + let magnitude = self.sel(odd, b, a)?; + let negative = self.opk(BinOp::UGreaterThanEqual, index, 2)?; + let negated = self.negate(magnitude)?; + let modifier = self.sel(negative, negated, magnitude)?; + let mut normal = [self.zero; 3]; + for (ch, out) in normal.iter_mut().enumerate() { + let first = self.sel(differential, diff[0][ch], individual[0][ch])?; + let second_base = self.sel(differential, diff[1][ch], individual[1][ch])?; + let base = self.sel(second, second_base, first)?; + let sum = self.add(base, modifier)?; + *out = self.clamp(sum, 0, 255)?; + } + // The T mode: paint colors `c1`, `c2 + d`, `c2` and `c2 - d`. + let t_red_high = self.field(hi, 27, 2)?; + let t_red_low = self.field(hi, 24, 2)?; + let t_red = self.join(t_red_high, 2, t_red_low)?; + let t1 = [t_red, self.field(hi, 20, 4)?, self.field(hi, 16, 4)?]; + let t2 = [ + self.field(hi, 12, 4)?, + self.field(hi, 8, 4)?, + self.field(hi, 4, 4)?, + ]; + let t_high = self.field(hi, 2, 2)?; + let t_low = self.field(hi, 0, 1)?; + let t_distance = self.join(t_high, 1, t_low)?; + let t_distance = self.entry(self.distances, t_distance)?; + let first_paint = index_is(self, 0)?; + let plus = index_is(self, 1)?; + let minus = index_is(self, 3)?; + let t_negated = self.negate(t_distance)?; + let t_shift = self.sel(minus, t_negated, self.zero)?; + let t_shift = self.sel(plus, t_distance, t_shift)?; + let mut t_mode = [self.zero; 3]; + for (ch, out) in t_mode.iter_mut().enumerate() { + let c1 = self.widen(t1[ch], 4)?; + let c2 = self.widen(t2[ch], 4)?; + let color = self.sel(first_paint, c1, c2)?; + let sum = self.add(color, t_shift)?; + *out = self.clamp(sum, 0, 255)?; + } + // The H mode: paint colors `c1 + d`, `c1 - d`, `c2 + d` and `c2 - d`, the distance's low + // bit whether `c1`'s colors sort at or after `c2`'s. + let h_green_high = self.field(hi, 24, 3)?; + let h_green_low = self.field(hi, 20, 1)?; + let h_blue_high = self.field(hi, 19, 1)?; + let h_blue_low = self.field(hi, 15, 3)?; + let h1 = [ + self.field(hi, 27, 4)?, + self.join(h_green_high, 1, h_green_low)?, + self.join(h_blue_high, 3, h_blue_low)?, + ]; + let h2 = [ + self.field(hi, 11, 4)?, + self.field(hi, 7, 4)?, + self.field(hi, 3, 4)?, + ]; + let mut h1_wide = [self.zero; 3]; + let mut h2_wide = [self.zero; 3]; + for ch in 0..3 { + h1_wide[ch] = self.widen(h1[ch], 4)?; + h2_wide[ch] = self.widen(h2[ch], 4)?; + } + let key = |e: &mut Self, [r, g, b]: [Value; 3]| -> BResult { + let rg = e.join(r, 8, g)?; + e.join(rg, 8, b) + }; + let key1 = key(self, h1_wide)?; + let key2 = key(self, h2_wide)?; + let sorted = self.op(BinOp::UGreaterThanEqual, key1, key2)?; + let one = self.k(1)?; + let sorted = self.sel(sorted, one, self.zero)?; + let h_high = self.field(hi, 2, 1)?; + let h_mid = self.field(hi, 0, 1)?; + let h_distance = self.join(h_high, 1, h_mid)?; + let h_distance = self.join(h_distance, 1, sorted)?; + let h_distance = self.entry(self.distances, h_distance)?; + let h_negated = self.negate(h_distance)?; + let h_shift = self.sel(odd, h_negated, h_distance)?; + let first_pair = self.opk(BinOp::ULessThan, index, 2)?; + let mut h_mode = [self.zero; 3]; + for (ch, out) in h_mode.iter_mut().enumerate() { + let color = self.sel(first_pair, h1_wide[ch], h2_wide[ch])?; + let sum = self.add(color, h_shift)?; + *out = self.clamp(sum, 0, 255)?; + } + // The planar mode: `(x (H - O) + y (V - O) + 4 O + 2) >> 2`, always opaque. + let o_green_high = self.field(hi, 24, 1)?; + let o_green_low = self.field(hi, 17, 6)?; + let o_blue_high = self.field(hi, 16, 1)?; + let o_blue_mid = self.field(hi, 11, 2)?; + let o_blue_low = self.field(hi, 7, 3)?; + let o_blue = self.join(o_blue_high, 2, o_blue_mid)?; + let o_blue = self.join(o_blue, 3, o_blue_low)?; + let h_red_high = self.field(hi, 2, 5)?; + let h_red_low = self.field(hi, 0, 1)?; + let origin = [ + (self.field(hi, 25, 6)?, 6), + (self.join(o_green_high, 6, o_green_low)?, 7), + (o_blue, 6), + ]; + let horizontal = [ + (self.join(h_red_high, 1, h_red_low)?, 6), + (self.field(lo, 25, 7)?, 7), + (self.field(lo, 19, 6)?, 6), + ]; + let vertical = [ + (self.field(lo, 13, 6)?, 6), + (self.field(lo, 6, 7)?, 7), + (self.field(lo, 0, 6)?, 6), + ]; + let mut planar = [self.zero; 3]; + for (ch, out) in planar.iter_mut().enumerate() { + let o = self.widen(origin[ch].0, origin[ch].1)?; + let h = self.widen(horizontal[ch].0, horizontal[ch].1)?; + let v = self.widen(vertical[ch].0, vertical[ch].1)?; + let dh = self.op(BinOp::ISub, h, o)?; + let dh = self.op(BinOp::IMul, bx, dh)?; + let dv = self.op(BinOp::ISub, v, o)?; + let dv = self.op(BinOp::IMul, by, dv)?; + let four = self.opk(BinOp::ShiftLeftLogical, o, 2)?; + let sum = self.add(dh, dv)?; + let sum = self.add(sum, four)?; + let sum = self.opk(BinOp::IAdd, sum, 2)?; + let sum = self.opk(BinOp::ShiftRightArithmetic, sum, 2)?; + *out = self.clamp(sum, 0, 255)?; + } + // The block's mode: a differential block whose red sum leaves `[0, 31]` is T, else whose + // green does H, else whose blue does planar. + let not_red = self.not(outside[0])?; + let not_green = self.not(outside[1])?; + let is_t = self.and(differential, outside[0])?; + let is_h = self.and(differential, not_red)?; + let is_planar = self.and(is_h, not_green)?; + let is_h = self.and(is_h, outside[1])?; + let is_planar = self.and(is_planar, outside[2])?; + // Transparent black: index 2 of a block not opaque, but for the planar mode. + let translucent = self.not(opaque)?; + let two = index_is(self, 2)?; + let clear = self.and(translucent, two)?; + let solid = self.not(is_planar)?; + let clear = self.and(clear, solid)?; + let mut codes = [self.zero; 4]; + for ch in 0..3 { + let color = self.sel(is_planar, planar[ch], normal[ch])?; + let color = self.sel(is_h, h_mode[ch], color)?; + let color = self.sel(is_t, t_mode[ch], color)?; + codes[ch] = self.sel(clear, self.zero, color)?; + } + let full = self.k(255)?; + codes[3] = self.sel(clear, self.zero, full)?; + Ok(codes) + } + + /// The `float` bits of an 11-bit `channel`'s value `v`, correctly rounded + /// (`EtcDecode::metal_value`): `v / 2047`, or `v / 1023` signed. + fn value(&mut self, v: Value, channel: Channel) -> BResult { + let u = Form { + held: Held::Int { + bits: 32, + container: 32, + }, + lanes: 1, + }; + if channel != Channel::Signed { + let q = div_exact(self.f, u, v, channel.divisor() as u32)?; + return self.f.convert(ConvOp::Bitcast, q, self.u32_); + } + let negative = self.op(BinOp::SLessThan, v, self.zero)?; + let negated = self.negate(v)?; + let magnitude = self.sel(negative, negated, v)?; + let q = div_exact(self.f, u, magnitude, channel.divisor() as u32)?; + let q = self.f.convert(ConvOp::Bitcast, q, self.u32_)?; + let sign = self.opk(BinOp::BitwiseOr, q, 0x8000_0000)?; + self.sel(negative, sign, q) + } + + /// The 16-bit normalized code nearest an 11-bit `channel`'s value `v`, in the low half + /// (`EtcDecode::twin_texel`): `(2 |v| top + d) / 2d`, signed as `v` is. + fn code(&mut self, v: Value, channel: Channel) -> BResult { + let d = channel.divisor() as u32; + let top = match channel { + Channel::Signed => 32767, + _ => 65535, + }; + let negative = self.op(BinOp::SLessThan, v, self.zero)?; + let negated = self.negate(v)?; + let magnitude = self.sel(negative, negated, v)?; + let scaled = self.opk(BinOp::IMul, magnitude, 2 * top)?; + let scaled = self.opk(BinOp::IAdd, scaled, d)?; + let q = self.opk(BinOp::UDiv, scaled, 2 * d)?; + let negated = self.negate(q)?; + let code = self.sel(negative, negated, q)?; + self.opk(BinOp::BitwiseAnd, code, 0xffff) + } + + /// The words of the twin's texel at `at` of `decode`'s blocks in `texels` (an `R11` format's + /// compact texel, the code in the low half alone). + fn texel(&mut self, decode: EtcDecode, texels: EtcTexels, at: At) -> BResult> { + let (base, place) = self.place(at, decode.block_bytes() / 4)?; + let pack = |e: &mut Self, codes: [Value; 4]| -> BResult { + let mut packed = codes[0]; + for (k, &c) in (1u32..).zip(&codes[1..]) { + let placed = e.opk(BinOp::ShiftLeftLogical, c, 8 * k)?; + packed = e.op(BinOp::BitwiseOr, packed, placed)?; + } + Ok(packed) + }; + let channels = match decode { + EtcDecode::Rgb8 | EtcDecode::Rgb8A1 => { + let block = self.half(base, 0)?; + let codes = self.rgb(block, place, decode == EtcDecode::Rgb8A1)?; + return Ok(vec![pack(self, codes)?]); + } + EtcDecode::Rgba8 => { + let alpha = self.half(base, 0)?; + let alpha = self.eac(alpha, place[0], Channel::Alpha)?; + let color = self.half(base, 1)?; + let [r, g, b, _] = self.rgb(color, place, false)?; + return Ok(vec![pack(self, [r, g, b, alpha])?]); + } + EtcDecode::R11Unorm | EtcDecode::R11Snorm => { + let red = self.half(base, 0)?; + vec![self.eac(red, place[0], decode.channel())?] + } + EtcDecode::Rg11Unorm | EtcDecode::Rg11Snorm => { + let red = self.half(base, 0)?; + let red = self.eac(red, place[0], decode.channel())?; + let green = self.half(base, 1)?; + vec![red, self.eac(green, place[0], decode.channel())?] + } + }; + let channel = decode.channel(); + match texels { + EtcTexels::Float => (channels.into_iter()) + .map(|v| self.value(v, channel)) + .collect(), + EtcTexels::Compact => { + let mut codes = Vec::with_capacity(channels.len()); + for v in channels { + codes.push(self.code(v, channel)?); + } + match codes[..] { + [r, g] => Ok(vec![self.join(g, 16, r)?]), + _ => Ok(codes), + } + } + } + } +} + +/// The module of `decode`'s blocks into `texels` as a typed module, before serialization: the +/// module [`etc_decode_module`](super::etc_decode_module) serializes, which the CPU interpreter +/// runs. Its bindings are the block decode's (`BlockDecodeModule`), its shape +/// `BlockDecodeModule::shape`'s. +pub(super) fn typed_module(decode: EtcDecode, texels: EtcTexels) -> BResult { + let mut b = ModuleBuilder::new(); + let u32_ = b.ty(Type::Int { + width: 32, + signed: false, + })?; + let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; + let shape = words_buffer(&mut b, SHAPE, u32_)?; + let blocks = words_buffer(&mut b, BLOCKS, u32_)?; + let texel_words = words_buffer(&mut b, TEXELS, u32_)?; + let pairs: Vec = (MODIFIERS.iter()) + .flat_map(|&(a, b)| [a as u32, b as u32]) + .collect(); + let modifiers = table(&mut b, u32_, &pairs)?; + let distances = table(&mut b, u32_, &DISTANCES.map(|d| d as u32))?; + let eac: Vec = EAC_MODIFIERS.iter().flatten().map(|&m| m as u32).collect(); + let eac = table(&mut b, u32_, &eac)?; + let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?; + let void = b.ty(Type::Void)?; + let mut f = b.function(void)?; + let zero = scalar(&mut f, u32_, 0)?; + let invocation = f.module().global_value(invocation)?; + let invocation = f.load(invocation, MemAccess::default())?; + let x = f.composite_extract(invocation, &[0])?; + let y = f.composite_extract(invocation, &[1])?; + let z = f.composite_extract(invocation, &[2])?; + let shape = f.module().global_value(shape)?; + let field = |f: &mut FunctionBuilder<'_>, index: u32| -> BResult { + let index = scalar(f, u32_, u64::from(index))?; + let p = f.access_chain(shape, &[zero, index])?; + f.load(p, MemAccess::default()) + }; + let width = field(&mut f, 0)?; + let height = field(&mut f, 1)?; + let depth = field(&mut f, 2)?; + let across = field(&mut f, 3)?; + let down = field(&mut f, 4)?; + let in_x = f.binary(BinOp::ULessThan, x, width)?; + let in_y = f.binary(BinOp::ULessThan, y, height)?; + let in_z = f.binary(BinOp::ULessThan, z, depth)?; + let inside = f.binary(BinOp::LogicalAnd, in_x, in_y)?; + let inside = f.binary(BinOp::LogicalAnd, inside, in_z)?; + // The texel's index through the region, `(z · height + y) · width + x`. + let t = f.binary(BinOp::IMul, z, height)?; + let t = f.binary(BinOp::IAdd, t, y)?; + let t = f.binary(BinOp::IMul, t, width)?; + let t = f.binary(BinOp::IAdd, t, x)?; + // An `R11` format's compact texels pair up in words: the even texel's invocation writes both. + let paired = + texels == EtcTexels::Compact && matches!(decode, EtcDecode::R11Unorm | EtcDecode::R11Snorm); + let writes = match paired { + true => { + let one = scalar(&mut f, u32_, 1)?; + let parity = f.binary(BinOp::BitwiseAnd, t, one)?; + let even = f.binary(BinOp::IEqual, parity, zero)?; + f.binary(BinOp::LogicalAnd, inside, even)? + } + false => inside, + }; + let blocks = f.module().global_value(blocks)?; + let texel_words = f.module().global_value(texel_words)?; + let decoded: ArmFn<'_, ()> = Box::new(move |f, _| { + let mut e = E { + f, + u32_, + zero, + blocks, + across, + down, + modifiers, + distances, + eac, + }; + let here = At { x, y, z }; + let mut words = e.texel(decode, texels, here)?; + if paired { + // The next texel: along the row, else the next row's first, else the next image's. + let next_x = e.opk(BinOp::IAdd, x, 1)?; + let wraps_x = e.op(BinOp::IEqual, next_x, width)?; + let next_x = e.sel(wraps_x, zero, next_x)?; + let down_one = e.opk(BinOp::IAdd, y, 1)?; + let next_y = e.sel(wraps_x, down_one, y)?; + let wraps_y = e.op(BinOp::IEqual, next_y, height)?; + let next_y = e.sel(wraps_y, zero, next_y)?; + let deeper = e.opk(BinOp::IAdd, z, 1)?; + let next_z = e.sel(wraps_y, deeper, z)?; + let there = At { + x: next_x, + y: next_y, + z: next_z, + }; + // Past the region's last texel there is none: a block of the first image stands in, + // and its code is not written. + let exists = e.op(BinOp::ULessThan, next_z, depth)?; + let safe_z = e.sel(exists, next_z, zero)?; + let next = e.texel(decode, texels, At { z: safe_z, ..there })?; + let next = e.sel(exists, next[0], zero)?; + words[0] = e.join(next, 16, words[0])?; + } + let count = words.len() as u32; + let at = match paired { + true => e.opk(BinOp::ShiftRightLogical, t, 1)?, + false => e.opk(BinOp::IMul, t, count)?, + }; + for (k, word) in (0u32..).zip(words) { + let index = e.opk(BinOp::IAdd, at, k)?; + let ptr = e.f.access_chain(texel_words, &[zero, index])?; + e.f.store(ptr, word, MemAccess::default())?; + } + Ok(ArmEnd::FallThrough(Vec::new())) + }); + f.if_(&mut (), writes, decoded, None)?; + f.ret(None)?; + let id = f.finish()?; + b.entry( + ExecModel::GLCompute, + id, + vec![ExecMode::LocalSize { + x: BlockDecodeModule::LOCAL_SIZE, + y: BlockDecodeModule::LOCAL_SIZE, + z: 1, + }], + )?; + b.finalize() +} + +#[cfg(test)] +mod tests { + use super::typed_module; + use crate::bind::block_decode::{BlockDecodeModule, BLOCKS, SHAPE, TEXELS}; + use crate::bind::{EtcDecode, EtcTexels}; + use crate::spirv::interp::{run, Buffer, Config, Order, Resources}; + use crate::spirv::testing::{assert_valid, committed_profiles}; + + /// `n` bytes of the xorshift64* stream from `seed`. + fn stream(seed: u64, n: usize) -> Vec { + let mut x = seed; + let mut out = Vec::with_capacity(n + 8); + while out.len() < n { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + out.extend_from_slice(&x.wrapping_mul(0x2545_F491_4F6C_DD1D).to_le_bytes()); + } + out.truncate(n); + out + } + + #[test] + fn the_etc_decode_kernels_are_valid_on_every_committed_profile() { + let profiles = committed_profiles().expect("profiles"); + for decode in EtcDecode::ALL { + for texels in [EtcTexels::Compact, EtcTexels::Float] { + for (_, p) in &profiles { + assert_valid(typed_module(decode, texels).expect("module"), p); + } + } + } + } + + /// The kernel's texels of a region `size` of `decode`'s `blocks` in `texels`; the texel + /// buffer's bytes past the region's words stay unwritten. + fn kernel_texels( + decode: EtcDecode, + texels: EtcTexels, + blocks: &[u8], + size: [u32; 3], + ) -> Vec { + let m = typed_module(decode, texels).expect("module"); + let [w, h, d] = size; + let length = (w * h * d * decode.texel_bytes(texels)) as usize; + let words = length.next_multiple_of(4); + let res = Resources { + buffers: vec![ + Buffer { + slot: Some(SHAPE), + address: None, + bytes: BlockDecodeModule::shape(size).to_vec(), + }, + Buffer { + slot: Some(BLOCKS), + address: None, + bytes: blocks.to_vec(), + }, + Buffer { + slot: Some(TEXELS), + address: None, + bytes: vec![0xcd; words + 64], + }, + ], + push: Vec::new(), + spec: Default::default(), + }; + let groups = |n: u32| n.div_ceil(BlockDecodeModule::LOCAL_SIZE); + let cfg = Config { + order: Order::Forward, + workgroups: [groups(w) + 1, groups(h), d + 1], + step_limit: 1 << 28, + ..Config::default() + }; + let mut out = run(&m, &cfg, res).expect("run").buffers; + let written = out.swap_remove(2); + assert!( + written[words..].iter().all(|&b| b == 0xcd), + "{decode:?} {texels:?}" + ); + // An odd count of 2-byte texels leaves the last word's high half zero. + assert!( + written[length..words].iter().all(|&b| b == 0), + "{decode:?} {texels:?}" + ); + written[..length].to_vec() + } + + /// The kernel writes the CPU's decode (Metal's, `random_blocks_decode_as_metal_reads_them`) + /// on every decode in both texels: random blocks of whole and partial blocks, two images, and + /// regions smaller than a block, an odd count of texels among them. + #[test] + fn the_etc_kernel_is_the_decode_on_every_texel() { + for (k, decode) in EtcDecode::ALL.into_iter().enumerate() { + for texels in [EtcTexels::Compact, EtcTexels::Float] { + for size in [[16u32, 12, 2], [13, 9, 1], [7, 5, 2], [3, 3, 1], [1, 1, 1]] { + let [w, h, d] = size; + let n = (w.div_ceil(4) * h.div_ceil(4) * d * decode.block_bytes()) as usize; + let blocks = stream(0x51ED_270B_0000 + k as u64, n); + let cpu = decode.decode(texels, &blocks, size); + let gpu = kernel_texels(decode, texels, &blocks, size); + assert_eq!(gpu, cpu, "{decode:?} {texels:?} {size:?}"); + } + } + } + } +} diff --git a/crates/metal2vulkan/src/bind/etc_decode/tests.rs b/crates/metal2vulkan/src/bind/etc_decode/tests.rs new file mode 100644 index 000000000..19e9ff753 --- /dev/null +++ b/crates/metal2vulkan/src/bind/etc_decode/tests.rs @@ -0,0 +1,256 @@ +//! The ETC2 and EAC decode against the specification's rules and Metal's reads. + +use super::{EtcDecode, EtcTexels}; +use crate::metal::PixelFormat; +use crate::vk::Format; + +/// The ETC2 and EAC formats alone decode, each sRGB form to its unorm form's codes. +#[test] +fn the_etc2_and_eac_formats_alone_decode() { + use PixelFormat as P; + let decoded: Vec<(PixelFormat, EtcDecode)> = PixelFormat::ALL + .iter() + .filter_map(|&pf| EtcDecode::of(pf).map(|d| (pf, d))) + .collect(); + assert_eq!( + decoded, + [ + (P::EACR11Unorm, EtcDecode::R11Unorm), + (P::EACR11Snorm, EtcDecode::R11Snorm), + (P::EACRG11Unorm, EtcDecode::Rg11Unorm), + (P::EACRG11Snorm, EtcDecode::Rg11Snorm), + (P::EACRGBA8, EtcDecode::Rgba8), + (P::EACRGBA8SRGB, EtcDecode::Rgba8), + (P::ETC2RGB8, EtcDecode::Rgb8), + (P::ETC2RGB8SRGB, EtcDecode::Rgb8), + (P::ETC2RGB8A1, EtcDecode::Rgb8A1), + (P::ETC2RGB8A1SRGB, EtcDecode::Rgb8A1), + ] + ); + for decode in EtcDecode::ALL { + let (compact, float) = match decode { + EtcDecode::R11Unorm => (Format::R16_UNORM, Format::R32_SFLOAT), + EtcDecode::R11Snorm => (Format::R16_SNORM, Format::R32_SFLOAT), + EtcDecode::Rg11Unorm => (Format::R16G16_UNORM, Format::R32G32_SFLOAT), + EtcDecode::Rg11Snorm => (Format::R16G16_SNORM, Format::R32G32_SFLOAT), + _ => (Format::R8G8B8A8_UNORM, Format::R8G8B8A8_UNORM), + }; + assert_eq!( + decode.texel_format(EtcTexels::Compact), + compact, + "{decode:?}" + ); + assert_eq!(decode.texel_format(EtcTexels::Float), float, "{decode:?}"); + assert_eq!(decode.eleven_bit(), compact != float, "{decode:?}"); + for texels in [EtcTexels::Compact, EtcTexels::Float] { + let format = decode.texel_format(texels); + let pf = decode.texel_pixel_format(texels); + assert_eq!( + crate::metal::format::direct_format(pf), + Some(format), + "{decode:?} {texels:?}" + ); + let bytes = format.block().map(|b| b.size).expect("a block"); + assert_eq!(decode.texel_bytes(texels), bytes, "{decode:?} {texels:?}"); + } + } +} + +/// A block's 64 bits, most significant first, as its bytes. +fn block(v: u64) -> [u8; 8] { + v.to_be_bytes() +} + +/// The `float` Metal reads of an 11-bit block's texel's red. +fn value(decode: EtcDecode, values: [i32; 2]) -> f32 { + decode.metal_value(values[0]) +} + +/// The zero blocks (a new texture's) decode by the rules: an individual-mode block of black with +/// table 0's `+2` (alpha 0 in `EAC_RGBA8`, whose zero alpha block reads 0), RGB8A1's transparent +/// differential block whose index 0 is the modifier 0, and an 11-bit block whose multiplier of 0 +/// adds the modifier `-3` itself. +#[test] +fn the_zero_blocks_decode_by_the_rules() { + let zero = [0u8; 16]; + let codes = |v: [i32; 2]| v[0].to_le_bytes(); + assert_eq!( + codes(EtcDecode::Rgb8.block_values(&zero)[5]), + [2, 2, 2, 255] + ); + assert_eq!( + codes(EtcDecode::Rgb8A1.block_values(&zero)[5]), + [0, 0, 0, 255] + ); + assert_eq!(codes(EtcDecode::Rgba8.block_values(&zero)[5]), [2, 2, 2, 0]); + let r11 = EtcDecode::R11Unorm; + assert_eq!(value(r11, r11.block_values(&zero)[3]), 1.0 / 2047.0); + let s11 = EtcDecode::R11Snorm; + assert_eq!(value(s11, s11.block_values(&zero)[3]), -3.0 / 1023.0); + assert_eq!(EtcDecode::Rg11Unorm.block_values(&zero)[0], [1, 1]); +} + +/// Each mode of an RGB block, by its bits: the subblocks and their tables, the T, H and planar +/// modes, and punch-through's transparent index. +#[test] +fn each_mode_decodes_by_the_specification() { + let texel = |decode: EtcDecode, v: u64, x: usize, y: usize| { + decode.block_values(&block(v))[4 * y + x][0].to_le_bytes() + }; + // Individual mode, flipped: the top subblock red 0x8 (136) with table 0, the bottom one blue + // 0xf (255) with table 7. Texel (0, 0) index 0 (+2); texel (0, 3) index 3 (-183): its msb is + // bit 16 + 3 and its lsb bit 3. + let v: u64 = 0x80 << 56 | 0x0f << 40 | 0b000_111 << 34 | 1 << 32 | 1 << 19 | 1 << 3; + assert_eq!(texel(EtcDecode::Rgb8, v, 0, 0), [138, 2, 2, 255]); + assert_eq!(texel(EtcDecode::Rgb8, v, 0, 3), [0, 0, 72, 255]); + // Differential mode: red 16 with delta -1, so the right subblock's red is 15; unflipped. + let v: u64 = 16 << 59 | 0b111 << 56 | 1 << 33; + assert_eq!(texel(EtcDecode::Rgb8, v, 0, 0), [134, 2, 2, 255]); + assert_eq!(texel(EtcDecode::Rgb8, v, 3, 0), [125, 2, 2, 255]); + // T mode: red 31 + delta 1 overflows. c1 = (0xf, 0, 0), c2 = (0, 0xf, 0), distance index 7 + // (64): index 0 paints c1, index 1 c2 + 64, index 3 c2 - 64. + let t: u64 = + 31 << 59 | 1 << 56 | 0b11 << 59 | 0b11 << 56 | 0xf << 40 | 0b11 << 34 | 1 << 33 | 1 << 32; + // Texel 0: index 0; texel 1 (0, 1): index 1 (lsb bit 1); texel 2 (0, 2): index 3. + let t = t | 1 << 1 | 1 << 18 | 1 << 2; + assert_eq!(texel(EtcDecode::Rgb8, t, 0, 0), [255, 0, 0, 255]); + assert_eq!(texel(EtcDecode::Rgb8, t, 0, 1), [64, 255, 64, 255]); + assert_eq!(texel(EtcDecode::Rgb8, t, 0, 2), [0, 191, 0, 255]); + // Without the opaque flag, RGB8A1 reads T mode's index 2 as transparent black: texel (1, 0) + // is texel number 4, msb bit 20. + let t_clear = (t & !(1 << 33)) | 1 << 20; + assert_eq!(texel(EtcDecode::Rgb8A1, t_clear, 1, 0), [0, 0, 0, 0]); + assert_eq!(texel(EtcDecode::Rgb8, t | 1 << 20, 1, 0), [0, 255, 0, 255]); + // H mode: red 15 + delta 0 fits, green 0 + delta -4 overflows (bit 50, which H mode does + // not read). c1 = (0xf, 0, 0) and c2 = 0, so c1 >= c2 sets the distance index's low bit: + // index 1, distance 6, and index 0 paints c1 + 6. + let h: u64 = 0xf << 59 | 0b100 << 48 | 1 << 33; + assert_eq!(texel(EtcDecode::Rgb8, h, 0, 0), [255, 6, 6, 255]); + // Planar mode: blue 31 + delta 1 overflows. O = (0, 0, 0) where its bits are clear; H's red + // 63 (255) and V's 0: red climbs by (x (255 - O) + 2) >> 2 across. The overflow bits (blue + // 31 at bits 47..43 and delta 1 at 40) carry no color in this mode. + let p: u64 = 31 << 43 | 1 << 40 | 1 << 33 | 0b11111 << 34 | 1 << 32; + let reds: Vec = (0..4).map(|x| texel(EtcDecode::Rgb8, p, x, 0)[0]).collect(); + assert_eq!(reds, [0, 64, 128, 191]); +} + +/// EAC's modifiers and multipliers: alpha clamps to a byte, an 11-bit value of a nonzero +/// multiplier steps by `8 m`, a signed base of -128 reads as -127. +#[test] +fn eac_blocks_decode_by_the_specification() { + // Base 200, multiplier 15, table 0: index 7 (+14) clamps alpha to 255, index 3 (-15) + // reads 200 - 225, clamped to 0. + let v: u64 = 200 << 56 | 15 << 52 | 7 << 45 | 3 << 42; + let alpha = + |p: usize| EtcDecode::Rgba8.block_values(&[block(v), [0; 8]].concat())[p][0] as u32 >> 24; + assert_eq!(alpha(0), 255); + assert_eq!(alpha(4), 0); + // Unsigned: base 100, multiplier 2, table 13, index 6 (+2): 804 + 32 = 836. + let v: u64 = 100 << 56 | 2 << 52 | 13 << 48 | 6 << 45; + assert_eq!(EtcDecode::R11Unorm.block_values(&block(v))[0], [836, 0]); + // Signed: base -128 reads -127, multiplier 1, table 0, index 3 (-15): -1016 - 120 clamps + // to -1023. + let v: u64 = 0x80 << 56 | 1 << 52 | 3 << 45; + assert_eq!(EtcDecode::R11Snorm.block_values(&block(v))[0], [-1023, 0]); + // Index 4 (+2): -1016 + 16 = -1000. + let v: u64 = 0x80 << 56 | 1 << 52 | 4 << 45; + assert_eq!(EtcDecode::R11Snorm.block_values(&block(v))[0], [-1000, 0]); +} + +/// `n` bytes of the xorshift64* stream from `seed`, each word little-endian. +fn stream(seed: u64, n: usize) -> Vec { + let mut x = seed; + let mut out = Vec::with_capacity(n + 8); + while out.len() < n { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + out.extend_from_slice(&x.wrapping_mul(0x2545_F491_4F6C_DD1D).to_le_bytes()); + } + out.truncate(n); + out +} + +/// FNV-1a, 64 bits. +fn fnv(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| { + (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3) + }) +} + +/// A 256 x 256 texture of 4096 random blocks of each format, every texel decoded: the digest of +/// the exact twin's texels is that of the texels an Apple M3 Max under macOS 27.0.1 reads from the +/// same blocks (each 8-bit channel `c / 255` as its code `c`, each 11-bit channel's `float` bits). +#[test] +fn random_blocks_decode_as_metal_reads_them() { + let eight = stream(0x9E37_79B9_7F4A_7C15, 32768); + let sixteen = stream(0xD1B5_4A32_D192_ED03, 65536); + let cases = [ + (EtcDecode::Rgb8, &eight, 0x8782_0f87_1ba3_b4ad_u64), + (EtcDecode::Rgb8A1, &eight, 0x03a5_c438_f97c_d615), + (EtcDecode::Rgba8, &sixteen, 0xca13_5c88_829c_cc4a), + (EtcDecode::R11Unorm, &eight, 0xcfab_277c_ac91_845d), + (EtcDecode::R11Snorm, &eight, 0x035f_1fa4_f6d2_5985), + (EtcDecode::Rg11Unorm, &sixteen, 0x85f3_0ebd_d7f4_627d), + (EtcDecode::Rg11Snorm, &sixteen, 0x0926_22a9_720a_4150), + ]; + for (decode, blocks, metal) in cases { + let texels = decode.decode(EtcTexels::Float, blocks, [256, 256, 1]); + assert_eq!(fnv(&texels), metal, "{decode:?}"); + } +} + +/// A region's texels lie as a copy into the twin reads them: an edge block's texels past the +/// region are not written, and each layer's follow the last. +#[test] +fn a_region_decodes_its_own_texels() { + let blocks = stream(7, 8 * 4); + // 6 x 3 texels of 2 layers: 2 x 1 blocks a layer. + let texels = EtcDecode::Rgb8.decode(EtcTexels::Compact, &blocks, [6, 3, 2]); + assert_eq!(texels.len(), 6 * 3 * 2 * 4); + for z in 0..2 { + for y in 0..3 { + for x in 0..6 { + let b = z * 2 + x / 4; + let want = EtcDecode::Rgb8.block_values(&blocks[b * 8..b * 8 + 8])[4 * y + x % 4] + [0] + .to_le_bytes(); + let at = ((z * 3 + y) * 6 + x) * 4; + assert_eq!(texels[at..at + 4], want, "({x}, {y}, {z})"); + } + } + } +} + +/// The compact twin's 16-bit code of every 11-bit value is the one nearest Metal's value: within +/// half a step of it, `1/131070` unsigned and `1/65534` signed. +#[test] +fn the_compact_codes_are_the_nearest() { + for (decode, values, top) in [ + (EtcDecode::R11Unorm, 0..=2047, 65535.0), + (EtcDecode::R11Snorm, -1023..=1023, 32767.0), + ] { + for c in values { + let mut out = [0u8; 2]; + decode.twin_texel(EtcTexels::Compact, [c, 0], &mut out); + let code = i16::from_le_bytes(out); + let read = match decode { + EtcDecode::R11Snorm => f64::from(code) / top, + _ => f64::from(code as u16) / top, + }; + let metal = f64::from(c) + / match decode { + EtcDecode::R11Snorm => 1023.0, + _ => 2047.0, + }; + assert!( + (read - metal).abs() <= 0.5 / top + 1e-12, + "{decode:?} {c}: {read} against {metal}" + ); + } + } + // The ends are exact. + let mut out = [0u8; 4]; + EtcDecode::Rg11Snorm.twin_texel(EtcTexels::Compact, [-1023, 1023], &mut out); + assert_eq!(out, [0x01, 0x80, 0xff, 0x7f]); +} diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index eb7c4b8bf..0b9435349 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -2364,7 +2364,7 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result Fit { false => Fit::No, }; } - // A resident texture of a format the table holds no representation of (PVRTC blocks held for - // copies) fits no class: its element is the neutral, and nothing is refused, since the heap + // A resident texture of a format the table holds no representation of (ASTC's 4x2 and 8x4 + // footprints) fits no class: its element is the neutral, and nothing is refused, since the heap // does not know which of its textures the function reads. match sampled_type(pixel_format) { _ if !shaped => Fit::No, diff --git a/crates/metal2vulkan/src/bind/heap/tests.rs b/crates/metal2vulkan/src/bind/heap/tests.rs index 8d7b08368..d54721ba6 100644 --- a/crates/metal2vulkan/src/bind/heap/tests.rs +++ b/crates/metal2vulkan/src/bind/heap/tests.rs @@ -132,11 +132,11 @@ fn fit_is_shape_samples_numeric_type_usage_and_aspect() { // A format the table holds no representation of fits no class: the heap does not know which // of its textures the function reads, so a resident one it cannot view is the neutral, and // nothing is refused. - let pvrtc = PixelFormat::PVRTCRGB4BPP; - assert_eq!(fit(&shape(T::Type2D, pvrtc, 1, READ), &f2d), Fit::No); + let unheld = PixelFormat::ASTC4x2HDR; + assert_eq!(fit(&shape(T::Type2D, unheld, 1, READ), &f2d), Fit::No); assert_eq!( fit( - &shape(T::Type2D, pvrtc, 1, READ), + &shape(T::Type2D, unheld, 1, READ), &class(ImageDim::D2, false, false, Uint, Sampled) ), Fit::No diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index f6376ea3f..de9617427 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -93,7 +93,14 @@ //! leaves of the formats whose bytes it changes ([`CompressedBlit`]), which //! [`compressed_blit_module`] of the rule rewrites after the copy. A BC1 to BC5 texture a device //! decodes otherwise than Metal is read through a twin of its texels as Metal decodes them -//! ([`BlockDecode`]), which [`block_decode_module`] writes from the blocks each write left. +//! ([`BlockDecode`]), which [`block_decode_module`] writes from the blocks each write left; an +//! ASTC LDR texture on a device without its block through a twin of Metal's decode of its blocks +//! ([`AstcDecode`], in the texels [`AstcTexels`] names), which [`astc_decode_module`] writes; a +//! PVRTC texture on a device without its format through a twin of its texels' codes +//! ([`PvrtcDecode`]), which [`pvrtc_decode_module`] writes; an ETC2 or EAC texture on a device +//! without the formats through a twin of its codes or an 11-bit format's values ([`EtcDecode`], in +//! the texels [`EtcTexels`] names), which [`etc_decode_module`] writes; a 4:2:2 texture through a +//! twin of its texels' codes ([`ChromaDecode`]), which [`chroma_decode_module`] writes. //! [`sampler_desc`] gives the Vulkan sampler a plan's sampler write needs, [`heap_classes`] the //! classes of the handle heap's arrays on a profile, [`FunctionTableWords`] the words of a //! visible-function table's buffer, and [`FunctionTableSnapshot`] the one buffer of a command's @@ -114,14 +121,17 @@ pub(crate) mod acceleration; pub(crate) mod argument_buffer; +pub(crate) mod astc_decode; pub(crate) mod block_decode; pub(crate) mod capture_assembly; +pub(crate) mod chroma_decode; pub(crate) mod color_resolve; pub(crate) mod compressed_blit; pub(crate) mod depth_magnitude; pub(crate) mod depth_stencil_copy; pub(crate) mod depth_stencil_resolve; pub(crate) mod dispatch; +pub(crate) mod etc_decode; pub(crate) mod extended_shadow; pub(crate) mod graphics; pub(crate) mod heap; @@ -137,6 +147,7 @@ pub(crate) mod plan; pub(crate) mod plane_bytes_copy; pub(crate) mod plane_copy; pub(crate) mod plane_words; +pub(crate) mod pvrtc_decode; pub(crate) mod rate_map; pub(crate) mod replay; pub(crate) mod resident; @@ -167,15 +178,18 @@ pub use argument_buffer::{ ArgumentBufferLayout, ArgumentDescriptor, ArgumentLayoutError, ArgumentMember, ArgumentPlace, ArgumentType, ARGUMENT_HANDLE_BYTES, }; +pub use astc_decode::{astc_decode_module, AstcDecode, AstcTexels}; pub use block_decode::{block_decode_module, BlockDecode, BlockDecodeModule}; pub use capture_assembly::{ capture_assembly_module, capture_settle_module, CaptureAssemblyModule, CaptureSettleModule, }; +pub use chroma_decode::{chroma_decode_module, ChromaDecode}; pub use color_resolve::{ color_resolve_modules, ColorResolveFormat, ColorResolveModules, ResolveChannel, ResolveRule, ResolveSource, SRGB_RESOLVE_LINEAR, SRGB_RESOLVE_THRESHOLDS, }; pub use compressed_blit::{compressed_blit_module, CompressedBlit, CompressedBlitModule}; +pub use etc_decode::{etc_decode_module, EtcDecode, EtcTexels}; // The bytes of `WriteSource::ColorWriteTable`'s buffer. pub use crate::lower::arith::srgb::color_write_table; pub use depth_magnitude::{depth_magnitude_module, DepthMagnitudeModule}; @@ -255,6 +269,7 @@ pub use plane_bytes_copy::{ }; pub use plane_copy::{plane_copy_module, PlaneCopyModule, PlaneRows}; pub use plane_words::{plane_words_module, PlaneWordsModule}; +pub use pvrtc_decode::{pvrtc_decode_module, PvrtcDecode}; pub use rotate_texels::{rotate_texels_module, RotateTexelsModule}; pub use sample_interleave::{ interleave_merge_modules, interleave_split_module, InterleaveMergeModules, diff --git a/crates/metal2vulkan/src/bind/plan/compute.rs b/crates/metal2vulkan/src/bind/plan/compute.rs index 5024f95fe..7f2c88147 100644 --- a/crates/metal2vulkan/src/bind/plan/compute.rs +++ b/crates/metal2vulkan/src/bind/plan/compute.rs @@ -780,7 +780,12 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result bool { /// Metal's numeric type of a texture of `pf` bound at a slot: the format table's /// (`sampled_type`), and `Float` for a color format the table holds no representation of (the -/// PVRTC RGB formats, whose blocks the runtime holds raw for copies, and the 4:2:2 formats). +/// 4:2:2 formats, whose texels the runtime holds raw for copies, and ASTC's 4x2 and 8x4 +/// footprints). /// Metal reads each as floats, so a slot of that type holds such a texture, and its binding is /// the format's own refusal (it has no sampled view), not a mismatch a neutral stands in for. /// A slot has an interface only where the function uses it, so a texture bound at an index the @@ -1259,6 +1259,17 @@ impl ResourcePlanner<'_> { } } + /// 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. + crosses && self.has_fact(RuntimeFact::SrgbTexture { slot }) && srgb_raw_on(pf, self.profile) + } + + /// Whether the device decodes the texels of `pf` itself, though Metal decodes them from raw + /// codes (`srgb_raw`, not `srgb_raw_on`): an ASTC sRGB format the device samples, whose + /// image's every view decodes its blocks. Its texels take no family there + /// ([`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 @@ -1755,7 +1766,8 @@ impl ResourcePlanner<'_> { /// incompatibly, or bound in an extended-range format, whose texels the slot's variant this /// plan asks for samples itself, `VariantKey::extended_range`) takes `BicubicTexels::NEUTRAL`; /// another compatible format of no measured family is refused - /// `NotImplemented(SamplerBicubicFilter)`. + /// `NotImplemented(SamplerBicubicFilter)`, and so is an ASTC sRGB format the device decodes + /// itself (`metal::texel_format::srgb_raw_on`). pub fn bicubic_texels(&self, slot: SlotRef) -> Result { let t = *self.texture_slot(slot)?; let class = declared( @@ -1769,6 +1781,7 @@ impl ResourcePlanner<'_> { _ if self.variant.extended_range.contains_key(&slot) => BicubicTexels::NEUTRAL, Some(s @ TextureShape::Texture { pixel_format, .. }) if compatible(s, &t, &class) => { bicubic_texels(*pixel_format) + .filter(|_| !self.decodes_srgb_itself(*pixel_format)) .ok_or(BindError::Unsupported(Unsupported::not_implemented( Feature::SamplerBicubicFilter, )))? @@ -1804,9 +1817,12 @@ impl ResourcePlanner<'_> { /// function swizzles the converted texel (`VariantKey::swizzled_storage`: a storage slot's; an /// extended-range sampled one's; a packed normalized sampled one's on a device without Metal's /// own sampler, whose border texels are then the unswizzled texture's). A slot bound to nothing - /// takes [`TexelFormat::OTHER`]: a neutral reads zero, which every class converts alike. + /// takes [`TexelFormat::OTHER`]: a neutral reads zero, which every class converts alike. So + /// does one bound to a format the device decodes itself where Metal decodes raw codes (an ASTC + /// sRGB format the device samples, `metal::texel_format::srgb_raw_on`). pub fn texel_format(&self, slot: SlotRef) -> u64 { let class = match self.texture_shape(slot) { + Some(shape) if self.decodes_srgb_itself(shape.pixel_format()) => TexelFormat::OTHER.0, Some(shape) => { let class = match texel_format(shape.pixel_format()) { class if !class.has_channels() => class.0, diff --git a/crates/metal2vulkan/src/bind/plan/resources/tests.rs b/crates/metal2vulkan/src/bind/plan/resources/tests.rs index 62d1ebb6e..99ab0317a 100644 --- a/crates/metal2vulkan/src/bind/plan/resources/tests.rs +++ b/crates/metal2vulkan/src/bind/plan/resources/tests.rs @@ -1210,7 +1210,7 @@ fn texel_format_follows_the_bound_format() { assert_eq!(plan(texture2d(pf)), u64::from(want.0), "{pf:?}"); } assert_eq!( - plan(texture2d(PixelFormat::ETC2RGB8SRGB)), + plan(texture2d(PixelFormat::BGRA10XRSRGB)), u64::from(C::OTHER.0) ); // A cube gather's corner alone: its field, without border texels; and a packed format's family, diff --git a/crates/metal2vulkan/src/bind/plan/slots.rs b/crates/metal2vulkan/src/bind/plan/slots.rs index 7eff6b3bf..cb8c6d90f 100644 --- a/crates/metal2vulkan/src/bind/plan/slots.rs +++ b/crates/metal2vulkan/src/bind/plan/slots.rs @@ -247,13 +247,15 @@ fn offset_base_axes(shape: &BindShape, slot: SlotRef) -> u64 { } /// The texture slots whose function decodes an 8-bit sRGB texel from its raw code -/// (`RuntimeFact::SrgbTexture`) at which `shape` binds a texture of such a format -/// (`metal::texel_format::srgb_raw`): the plan's `VariantKey::srgb_textures`. So is each slot of -/// `cross` that the variant reads in the float class (an integer slot), whose accesses there take -/// `float` results, which the raw code serves as a float slot's: the variant's compile states -/// `SrgbTexture` there. The variant's compile states the same facts, so its plan for the same shape -/// states the same key. +/// (`RuntimeFact::SrgbTexture`) at which `shape` binds a texture of such a format whose codes +/// `profile`'s device holds (`metal::texel_format::srgb_raw_on`: not an ASTC sRGB format it +/// decodes itself): the plan's `VariantKey::srgb_textures`. So is each slot of `cross` that the +/// variant reads in the float class (an integer slot), whose accesses there take `float` results, +/// which the raw code serves as a float slot's: the variant's compile states `SrgbTexture` there. +/// The variant's compile states the same facts, so its plan for the same shape states the same +/// key. pub(crate) fn srgb_variant( + profile: &DeviceProfile, dependencies: &[RuntimeDependency], shape: &BindShape, cross: &BTreeMap, @@ -271,7 +273,7 @@ pub(crate) fn srgb_variant( .chain(read_float) .filter(|slot| { matches!(bound_texture(shape, *slot), Some(TextureShape::Texture { pixel_format, .. }) - if metal::texel_format::srgb_raw(*pixel_format)) + if metal::texel_format::srgb_raw_on(*pixel_format, profile)) }) .collect() } diff --git a/crates/metal2vulkan/src/bind/pvrtc_decode.rs b/crates/metal2vulkan/src/bind/pvrtc_decode.rs new file mode 100644 index 000000000..0b38b78fe --- /dev/null +++ b/crates/metal2vulkan/src/bind/pvrtc_decode.rs @@ -0,0 +1,370 @@ +//! A PVRTC texture's texels as Metal decodes them, from its blocks: the texels a decoded twin of +//! the texture holds on a device without the format (every device but Apple's and PowerVR's). +//! +//! **The decode** (PVRTC1, fitted on an Apple M3 Max under macOS 27.0.1, our own probe: every +//! texel of a 256 x 256 texture of seeded random blocks of each of the eight formats read as +//! `float`, equal to this decode's in every channel). A block is a 64-bit little-endian word of +//! 4 x 4 texels (4 bits a pixel) or 8 x 4 (2 bits); the blocks lie row-major and wrap at the +//! level's edges, a level of fewer texels than a block holding one. +//! +//! - **Colors.** Color B is bits 48 to 63: RGB555 where its bit 15 is set, else A3R4G4B4; color A +//! is bits 32 to 47, its bit 0 the block's mode bit: RGB554 (blue's 4 bits at bits 1 to 4) where +//! its bit 15 is set, else A3R4G4B3. Each widens to 5-bit channels (a 4-bit one `c << 1 | c >> 3`, +//! a 3-bit one `c << 2 | c >> 1`) and a 4-bit alpha (`a << 1`, an opaque color's 15). +//! - **Upscale.** Each texel's colors A and B are the bilinear upscale of the four blocks whose +//! centres (`(w/2, h/2)` in a block of `w` x `h`) surround it: the integer sum `V` of each +//! channel times the weights, at a scale of `w h`, widened to 8 bits: 4 bits a pixel, RGB +//! `(V >> 1) + (V >> 6)` and alpha `V + (V >> 4)`; 2 bits, RGB `(V >> 2) + (V >> 7)` and alpha +//! `(V >> 1) + (V >> 5)`. +//! - **4 bits a pixel.** Each texel's 2-bit index (bits 0 to 31, 2 a texel, row-major) weighs B: +//! 0, 3, 5 or 8 eighths; in mode 1 (punch-through) 0, 4, 4 or 8, index 2 also making alpha 0. +//! - **2 bits a pixel.** In mode 0 each texel has one bit (bits 0 to 31): 0 or 8 eighths. In mode +//! 1 the texels of even `x + y` hold 2-bit values (0, 3, 5 or 8 eighths) on the checkerboard, +//! row-major; the others take the four neighbours' average `(s + 2) / 4`, or where bit 0 is set +//! the two horizontal neighbours' `(a + b + 1) / 2` (the vertical ones' where bit 20 is set). +//! Before the values are read, bit 21 is copied into bit 20 where bit 0 is set, then bit 1 into +//! bit 0. Neighbours come from the adjacent blocks, wrapping. +//! - **The texel.** Each channel is `(A (8 - w) + B w) / 8`, an 8-bit code; an RGB format's alpha +//! is 255. Metal reads a code `c / 255`, an sRGB format's color channel through its twelve-bit +//! table (`k / 4095` for `lower::arith::srgb`'s step `k`). +//! +//! **The twin's texels** are the codes, in `R8G8B8A8_UNORM` ([`PvrtcDecode::texel_format`]), +//! exact: a linear format's read is the code's `c / 255`, and an sRGB format's slot reads them raw +//! through that view and decodes its color through Metal's table +//! (`metal::texel_format::srgb_raw`), as for `RGBA8Unorm_sRGB`. A format's linear and sRGB forms +//! decode to the same codes, so one twin serves the views of both. +//! +//! **The module** ([`pvrtc_decode_module`], one per device and block shape: 2 or 4 bits a pixel, +//! RGB or RGBA). `BlockDecodeModule`'s entry point, local size and bindings: the shape +//! ([`PvrtcDecode::shape`]: a band of a level's rows of some of its images), every block of +//! those images (row-major, each image's after the last, read whole, since each texel's colors +//! come from the blocks around it, wrapping), and the band's texels, written as a copy into the +//! twin reads them. Invocation `(x, y, z)` inside the band's width, rows and images writes texel +//! `(x, first + y)` of image `z`; one outside writes nothing. A write into some blocks changes the +//! texels around them, wrapping at the level's edges: the consumer decodes whole levels. + +use crate::bind::block_decode::{decode_module, BlockDecodeModule}; +use crate::device::Device; +use crate::error::Error; +use crate::lower::arith::srgb::SRGB_DECODE_STEPS; +use crate::metal::PixelFormat; +use crate::vk::Format; + +mod kernel; + +/// How a PVRTC format's blocks decode (the module docs). +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct PvrtcDecode { + /// 2 bits a pixel (8 x 4 blocks), else 4 (4 x 4 blocks). + pub two_bits: bool, + /// An RGBA format, whose alpha is decoded; an RGB format's is 255. + pub alpha: bool, + /// An sRGB format, whose color channels Metal reads through its twelve-bit table. + pub srgb: bool, +} + +/// The weights of B, in eighths, of a 2-bit index. +const WEIGHTS: [u32; 4] = [0, 3, 5, 8]; + +/// The weights of B of a 4-bit-a-pixel block's punch-through mode. +const PUNCH_WEIGHTS: [u32; 4] = [0, 4, 4, 8]; + +impl PvrtcDecode { + /// The bytes of every block. + pub const BLOCK_BYTES: u32 = 8; + + /// The decode of `pf`'s blocks: the eight PVRTC formats; `None` for every other format. + pub fn of(pf: PixelFormat) -> Option { + use PixelFormat as P; + let (two_bits, alpha, srgb) = match pf { + P::PVRTCRGB2BPP => (true, false, false), + P::PVRTCRGB2BPPSRGB => (true, false, true), + P::PVRTCRGB4BPP => (false, false, false), + P::PVRTCRGB4BPPSRGB => (false, false, true), + P::PVRTCRGBA2BPP => (true, true, false), + P::PVRTCRGBA2BPPSRGB => (true, true, true), + P::PVRTCRGBA4BPP => (false, true, false), + P::PVRTCRGBA4BPPSRGB => (false, true, true), + _ => return None, + }; + Some(PvrtcDecode { + two_bits, + alpha, + srgb, + }) + } + + /// The texels across and down of a block: 8 x 4 or 4 x 4. + pub fn block_extent(self) -> [u32; 2] { + match self.two_bits { + true => [8, 4], + false => [4, 4], + } + } + + /// The bytes of a twin's texel: its four codes. + pub const TEXEL_BYTES: u32 = 4; + + /// The decode of the format's linear form, whose blocks decode to the same codes. + pub fn linear(self) -> PvrtcDecode { + PvrtcDecode { + srgb: false, + ..self + } + } + + /// The Vulkan format of a twin's texels: `R8G8B8A8_UNORM`, its codes. + pub fn texel_format(self) -> Format { + Format::R8G8B8A8_UNORM + } + + /// The Metal pixel format whose texels a twin's are: `RGBA8Unorm`. + pub fn texel_pixel_format(self) -> PixelFormat { + PixelFormat::RGBA8Unorm + } + + /// The `float` Metal reads of channel `ch` (red, green, blue, alpha) of code `c`. + pub fn metal_value(self, ch: usize, c: u8) -> f32 { + match self.srgb && ch < 3 { + true => (f64::from(SRGB_DECODE_STEPS[usize::from(c)]) / 4095.0) as f32, + false => (f64::from(c) / 255.0) as f32, + } + } + + /// The twin's texels (each its four codes, red in the low byte) of the `depth` images of a + /// whole level `width` x `height` whose `blocks` lie row-major (each image's after the last, a + /// level of fewer texels than a block holding one), laid out as a copy into the twin reads + /// them: the module docs' decode, wrapping at each image's blocks. + /// + /// # Panics + /// + /// Where `blocks` holds fewer blocks than the level. + pub fn decode(self, blocks: &[u8], [width, height, depth]: [u32; 3]) -> Vec { + let image = self.level_bytes([width, height]); + let texels = (width * height) as usize * Self::TEXEL_BYTES as usize; + let mut out = vec![0; texels * depth as usize]; + for (i, out) in out.chunks_exact_mut(texels.max(1)).enumerate() { + let blocks = &blocks[i * image..(i + 1) * image]; + self.decode_rows(blocks, [width, height], [0, height], out); + } + out + } + + /// The bytes of the blocks of one image of a level `width` x `height`. + pub fn level_bytes(self, [width, height]: [u32; 2]) -> usize { + let [bw, bh] = self.block_extent(); + (width.div_ceil(bw) * height.div_ceil(bh) * Self::BLOCK_BYTES) as usize + } + + /// The shape's bytes ([`BlockDecodeModule::SHAPE_WORDS`] words) of a band of rows `first` to + /// `first + rows` of `images` images of a level `width` x `height`, whose blocks the module + /// reads whole: `width`, `rows`, `images`, `first` and `height`. + pub fn shape( + [width, height]: [u32; 2], + [first, rows]: [u32; 2], + images: u32, + ) -> [u8; BlockDecodeModule::SHAPE_WORDS as usize * 4] { + let words = [width, rows, images, first, height]; + let mut bytes = [0; BlockDecodeModule::SHAPE_WORDS as usize * 4]; + for (chunk, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) { + chunk.copy_from_slice(&word.to_le_bytes()); + } + bytes + } + + /// The twin's texels of rows `first` to `first + rows` of one image of a level `width` x + /// `height` whose `blocks` (all of the image's, row-major) wrap, into `out` (exactly their + /// bytes), laid out as a copy into the twin reads them. + /// + /// # Panics + /// + /// Where `blocks` holds fewer blocks than the image, or `out` another size than the rows'. + pub fn decode_rows( + self, + blocks: &[u8], + [width, height]: [u32; 2], + [first, rows]: [u32; 2], + out: &mut [u8], + ) { + let [bw, bh] = self.block_extent(); + let (across, down) = (width.div_ceil(bw), height.div_ceil(bh)); + let words: Vec = blocks[..self.level_bytes([width, height])] + .as_chunks::<8>() + .0 + .iter() + .map(|bytes| u64::from_le_bytes(*bytes)) + .collect(); + let level = Level { + decode: self, + words: &words, + across, + down, + }; + assert_eq!(out.len(), (width * rows * Self::TEXEL_BYTES) as usize); + let mut texels = out.as_chunks_mut::<4>().0.iter_mut(); + for y in first..first + rows { + for x in 0..width { + if let Some(texel) = texels.next() { + *texel = level.texel(x, y); + } + } + } + } +} + +/// The PVRTC decode module of `device` for `decode` (the module docs; an sRGB format's is its +/// linear form's): built with the typed builder, checked by the owned verifier against the +/// device's profile (requirements included), serialized, and numbered with the fixed bindings of +/// [`BlockDecodeModule`]. +pub fn pvrtc_decode_module( + device: &Device, + decode: PvrtcDecode, +) -> Result { + let m = kernel::typed_module(decode.linear())?; + decode_module(device, m, "PVRTC decode") +} + +/// Colors A and B of the block `word`, each red, green and blue of 5 bits and alpha of 4. +fn colors(word: u64) -> [[u32; 4]; 2] { + let high = (word >> 32) as u32; + let (a, b) = (high & 0xffff, high >> 16); + let four = |c: u32| c << 1 | c >> 3; + let b = match b & 0x8000 != 0 { + true => [(b >> 10) & 31, (b >> 5) & 31, b & 31, 15], + false => [ + four((b >> 8) & 15), + four((b >> 4) & 15), + four(b & 15), + ((b >> 12) & 7) << 1, + ], + }; + let a = match a & 0x8000 != 0 { + true => [(a >> 10) & 31, (a >> 5) & 31, four((a >> 1) & 15), 15], + false => { + let blue = (a >> 1) & 7; + [ + four((a >> 8) & 15), + four((a >> 4) & 15), + blue << 2 | blue >> 1, + ((a >> 12) & 7) << 1, + ] + } + }; + [a, b] +} + +/// One image of a level's blocks. +struct Level<'a> { + decode: PvrtcDecode, + words: &'a [u64], + across: u32, + down: u32, +} + +impl Level<'_> { + /// The block `(bx, by)`, wrapping. + fn word(&self, bx: i64, by: i64) -> u64 { + let bx = bx.rem_euclid(i64::from(self.across)) as usize; + let by = by.rem_euclid(i64::from(self.down)) as usize; + self.words[by * self.across as usize + bx] + } + + /// The weight of B, in eighths, a 2-bit-a-pixel block stores at texel `(x, y)` of the level + /// (wrapping), of even `x + y` in mode 1 or any in mode 0. + fn stored(&self, x: i64, y: i64) -> u32 { + let [bw, bh] = self.decode.block_extent().map(i64::from); + let word = self.word(x.div_euclid(bw), y.div_euclid(bh)); + let (x, y) = (x.rem_euclid(bw) as u32, y.rem_euclid(bh) as u32); + let mut m = word as u32; + if (word >> 32) & 1 == 0 { + return WEIGHTS[3 * ((m >> (8 * y + x)) & 1) as usize]; + } + // Bit 21 into bit 20 where bit 0 is set, then bit 1 into bit 0. + if m & 1 != 0 { + m = (m & !(1 << 20)) | ((m >> 21) & 1) << 20; + } + m = (m & !1) | ((m >> 1) & 1); + // The checkerboard's texels, row-major, hold 2-bit values in turn. + let k = (8 * y + x) / 2; + WEIGHTS[((m >> (2 * k)) & 3) as usize] + } + + /// The weight of B, in eighths, of texel `(x, y)` of a 2-bit-a-pixel level. + fn weight_two_bits(&self, x: i64, y: i64) -> u32 { + let [bw, bh] = self.decode.block_extent().map(i64::from); + let word = self.word(x.div_euclid(bw), y.div_euclid(bh)); + let (bx, by) = (x.rem_euclid(bw), y.rem_euclid(bh)); + if (word >> 32) & 1 == 0 || (bx ^ by) & 1 == 0 { + return self.stored(x, y); + } + let m = word as u32; + if m & 1 == 0 { + let sum = self.stored(x, y - 1) + + self.stored(x, y + 1) + + self.stored(x - 1, y) + + self.stored(x + 1, y); + return (sum + 2) / 4; + } + // Bit 20 as stored chooses the vertical neighbours. + match (m >> 20) & 1 != 0 { + true => (self.stored(x, y - 1) + self.stored(x, y + 1)).div_ceil(2), + false => (self.stored(x - 1, y) + self.stored(x + 1, y)).div_ceil(2), + } + } + + /// The codes of texel `(x, y)`. + fn texel(&self, x: u32, y: u32) -> [u8; 4] { + let decode = self.decode; + let [bw, bh] = decode.block_extent().map(i64::from); + let (x, y) = (i64::from(x), i64::from(y)); + let (px, py) = (x - bw / 2, y - bh / 2); + let (bx, by) = (px.div_euclid(bw), py.div_euclid(bh)); + let (u, v) = (px - bx * bw, py - by * bh); + let corners = [ + (colors(self.word(bx, by)), (bw - u) * (bh - v)), + (colors(self.word(bx + 1, by)), u * (bh - v)), + (colors(self.word(bx, by + 1)), (bw - u) * v), + (colors(self.word(bx + 1, by + 1)), u * v), + ]; + let up = |which: usize, ch: usize| -> u32 { + let sum: i64 = corners + .iter() + .map(|(c, weight)| i64::from(c[which][ch]) * weight) + .sum(); + let v = sum as u32; + match (decode.two_bits, ch < 3) { + (false, true) => (v >> 1) + (v >> 6), + (false, false) => v + (v >> 4), + (true, true) => (v >> 2) + (v >> 7), + (true, false) => (v >> 1) + (v >> 5), + } + }; + let word = self.word(x.div_euclid(bw), y.div_euclid(bh)); + let (weight, punch) = match decode.two_bits { + true => (self.weight_two_bits(x, y), false), + false => { + let index = (word >> (2 * (4 * y.rem_euclid(4) + x.rem_euclid(4)))) & 3; + match (word >> 32) & 1 != 0 { + true => (PUNCH_WEIGHTS[index as usize], index == 2), + false => (WEIGHTS[index as usize], false), + } + } + }; + let mut texel = [0u8; 4]; + for (ch, code) in texel.iter_mut().enumerate() { + *code = ((up(0, ch) * (8 - weight) + up(1, ch) * weight) / 8) as u8; + } + if punch { + texel[3] = 0; + } + if !decode.alpha { + texel[3] = 255; + } + texel + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/metal2vulkan/src/bind/pvrtc_decode/kernel.rs b/crates/metal2vulkan/src/bind/pvrtc_decode/kernel.rs new file mode 100644 index 000000000..64cb589e0 --- /dev/null +++ b/crates/metal2vulkan/src/bind/pvrtc_decode/kernel.rs @@ -0,0 +1,442 @@ +//! The GPU's decode of PVRTC blocks into a decoded twin's texels: the module +//! [`pvrtc_decode_module`](super::pvrtc_decode_module) serializes, the same decode as the CPU's +//! ([`PvrtcDecode::decode_rows`]) in integer operations alone. +//! +//! One invocation per texel of a band of the level's rows reads the four blocks whose centres +//! surround it, upscales colors A and B, reads its own weight (a 2-bit-a-pixel texel of mode 1 +//! off the checkerboard its four neighbours' stored weights, from the blocks they lie in) and +//! writes the blend, straight-line; every block index wraps at the image's blocks. + +use super::{PvrtcDecode, PUNCH_WEIGHTS, WEIGHTS}; +use crate::bind::block_decode::{table, BlockDecodeModule, BLOCKS, SHAPE, TEXELS}; +use crate::bind::ycbcr_convert::{scalar, words_buffer}; +use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; +use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; +use crate::spirv::error::BResult; +use crate::spirv::ids::{GlobalId, TypeId, Value}; +use crate::spirv::ir::{ + BinOp, ConstBits, Constant, ExecMode, ExecModel, IoDir, MemAccess, Type, TypedModule, +}; + +/// The decode of one texel: the function it builds in, and what every step reads. +struct P<'a, 'b> { + f: &'a mut FunctionBuilder<'b>, + u32_: TypeId, + zero: Value, + /// The blocks' words. + blocks: Value, + /// The weights of B of a 2-bit index, then of a punch-through one (`WEIGHTS`, + /// `PUNCH_WEIGHTS`). + weights: GlobalId, +} + +impl P<'_, '_> { + fn k(&mut self, v: u32) -> BResult { + scalar(self.f, self.u32_, u64::from(v)) + } + + /// The `bool` constant `v`. + fn boolean(&mut self, v: bool) -> BResult { + let ty = self.f.module().ty(Type::Bool)?; + let c = self.f.module().constant(Constant::Scalar { + ty, + bits: ConstBits(u64::from(v)), + })?; + self.f.module().const_value(c) + } + + fn op(&mut self, op: BinOp, a: Value, b: Value) -> BResult { + self.f.binary(op, a, b) + } + + fn opk(&mut self, op: BinOp, a: Value, b: u32) -> BResult { + let b = self.k(b)?; + self.f.binary(op, a, b) + } + + fn add(&mut self, a: Value, b: Value) -> BResult { + self.op(BinOp::IAdd, a, b) + } + + fn mul(&mut self, a: Value, b: Value) -> BResult { + self.op(BinOp::IMul, a, b) + } + + fn sel(&mut self, c: Value, a: Value, b: Value) -> BResult { + self.f.select(c, a, b) + } + + /// Whether bit `at` of `v` is set. + fn bit(&mut self, v: Value, at: u32) -> BResult { + let field = self.field(v, at, 1)?; + self.opk(BinOp::INotEqual, field, 0) + } + + /// `(v >> at) & (2^n - 1)` for a constant field. + fn field(&mut self, v: Value, at: u32, n: u32) -> BResult { + let shifted = self.opk(BinOp::ShiftRightLogical, v, at)?; + self.opk(BinOp::BitwiseAnd, shifted, (1 << n) - 1) + } + + /// Entry `index` of the `Private` table `table`. + fn entry(&mut self, table: GlobalId, index: Value) -> BResult { + let table = self.f.module().global_value(table)?; + let p = self.f.access_chain(table, &[index])?; + self.f.load(p, MemAccess::default()) + } + + /// Word `index` of the blocks. + fn word(&mut self, index: Value) -> BResult { + let p = self.f.access_chain(self.blocks, &[self.zero, index])?; + self.f.load(p, MemAccess::default()) + } + + /// The low and high words of block `index`. + fn block(&mut self, index: Value) -> BResult<[Value; 2]> { + let low = self.opk(BinOp::ShiftLeftLogical, index, 1)?; + let high = self.opk(BinOp::IAdd, low, 1)?; + Ok([self.word(low)?, self.word(high)?]) + } + + /// A 4-bit channel widened to 5 bits, `c << 1 | c >> 3`. + fn four(&mut self, c: Value) -> BResult { + let up = self.opk(BinOp::ShiftLeftLogical, c, 1)?; + let down = self.opk(BinOp::ShiftRightLogical, c, 3)?; + self.op(BinOp::BitwiseOr, up, down) + } + + /// Colors A and B of a block whose high word is `high`, each red, green and blue of 5 bits + /// and alpha of 4 (`super::colors`). + fn colors(&mut self, high: Value) -> BResult<[[Value; 4]; 2]> { + let a = self.opk(BinOp::BitwiseAnd, high, 0xffff)?; + let b = self.opk(BinOp::ShiftRightLogical, high, 16)?; + let fifteen = self.k(15)?; + let translucent_alpha = |p: &mut Self, c: Value| -> BResult { + let alpha = p.field(c, 12, 3)?; + p.opk(BinOp::ShiftLeftLogical, alpha, 1) + }; + // B: RGB555 where opaque, else A3R4G4B4. + let b_opaque = self.bit(b, 15)?; + let b_red = self.field(b, 10, 5)?; + let b_green = self.field(b, 5, 5)?; + let b_blue = self.field(b, 0, 5)?; + let tr = self.field(b, 8, 4)?; + let tr = self.four(tr)?; + let tg = self.field(b, 4, 4)?; + let tg = self.four(tg)?; + let tb = self.field(b, 0, 4)?; + let tb = self.four(tb)?; + let ta = translucent_alpha(self, b)?; + let color_b = [ + self.sel(b_opaque, b_red, tr)?, + self.sel(b_opaque, b_green, tg)?, + self.sel(b_opaque, b_blue, tb)?, + self.sel(b_opaque, fifteen, ta)?, + ]; + // A: RGB554 where opaque, else A3R4G4B3 (bit 0 is the mode bit). + let a_opaque = self.bit(a, 15)?; + let a_red = self.field(a, 10, 5)?; + let a_green = self.field(a, 5, 5)?; + let a_blue = self.field(a, 1, 4)?; + let a_blue = self.four(a_blue)?; + let tr = self.field(a, 8, 4)?; + let tr = self.four(tr)?; + let tg = self.field(a, 4, 4)?; + let tg = self.four(tg)?; + let blue3 = self.field(a, 1, 3)?; + let up = self.opk(BinOp::ShiftLeftLogical, blue3, 2)?; + let down = self.opk(BinOp::ShiftRightLogical, blue3, 1)?; + let tb = self.op(BinOp::BitwiseOr, up, down)?; + let ta = translucent_alpha(self, a)?; + let color_a = [ + self.sel(a_opaque, a_red, tr)?, + self.sel(a_opaque, a_green, tg)?, + self.sel(a_opaque, a_blue, tb)?, + self.sel(a_opaque, fifteen, ta)?, + ]; + Ok([color_a, color_b]) + } +} + +/// Where a texel's blocks lie: the image's first block, and its blocks across and down. +#[derive(Clone, Copy)] +struct Grid { + base: Value, + across: Value, + down: Value, +} + +impl Grid { + /// The index of block `(bx, by)` of the image (each inside the grid). + fn index(self, p: &mut P<'_, '_>, bx: Value, by: Value) -> BResult { + let row = p.mul(by, self.across)?; + let at = p.add(row, bx)?; + p.add(self.base, at) + } +} + +/// The weight of B, in eighths, a 2-bit-a-pixel block stores at texel `(x, y)` of the image's +/// blocks (inside them; `super::Level::stored`). +fn stored(p: &mut P<'_, '_>, grid: Grid, x: Value, y: Value) -> BResult { + let bx = p.opk(BinOp::UDiv, x, 8)?; + let by = p.opk(BinOp::UDiv, y, 4)?; + let index = grid.index(p, bx, by)?; + let [low, high] = p.block(index)?; + let lx = p.opk(BinOp::BitwiseAnd, x, 7)?; + let ly = p.opk(BinOp::BitwiseAnd, y, 3)?; + let ly8 = p.opk(BinOp::ShiftLeftLogical, ly, 3)?; + let at = p.add(ly8, lx)?; + // Mode 0: one bit a texel, 0 or 8 eighths. + let one = p.op(BinOp::ShiftRightLogical, low, at)?; + let one = p.opk(BinOp::BitwiseAnd, one, 1)?; + let one = p.opk(BinOp::ShiftLeftLogical, one, 3)?; + // Mode 1: bit 21 into bit 20 where bit 0 is set, then bit 1 into bit 0; the checkerboard's + // texels hold 2-bit values in turn. + let flagged = p.bit(low, 0)?; + let cleared = p.opk(BinOp::BitwiseAnd, low, !(1 << 20))?; + let b21 = p.field(low, 21, 1)?; + let b21 = p.opk(BinOp::ShiftLeftLogical, b21, 20)?; + let moved = p.op(BinOp::BitwiseOr, cleared, b21)?; + let m = p.sel(flagged, moved, low)?; + let cleared = p.opk(BinOp::BitwiseAnd, m, !1)?; + let b1 = p.field(m, 1, 1)?; + let m = p.op(BinOp::BitwiseOr, cleared, b1)?; + let k = p.opk(BinOp::ShiftRightLogical, at, 1)?; + let k2 = p.opk(BinOp::ShiftLeftLogical, k, 1)?; + let index = p.op(BinOp::ShiftRightLogical, m, k2)?; + let index = p.opk(BinOp::BitwiseAnd, index, 3)?; + let two = p.entry(p.weights, index)?; + let mode = p.bit(high, 0)?; + p.sel(mode, two, one) +} + +/// `(v + span - 1) mod span` and `(v + 1) mod span`: the coordinates before and after `v`, +/// wrapping inside `span`. +fn neighbours(p: &mut P<'_, '_>, v: Value, span: Value) -> BResult<[Value; 2]> { + let before = p.add(v, span)?; + let before = p.opk(BinOp::ISub, before, 1)?; + let before = p.op(BinOp::UMod, before, span)?; + let after = p.opk(BinOp::IAdd, v, 1)?; + let after = p.op(BinOp::UMod, after, span)?; + Ok([before, after]) +} + +/// The codes of texel `(x, y)` of an image of `decode` on `grid` (`super::Level::texel`). +fn texel( + p: &mut P<'_, '_>, + decode: PvrtcDecode, + grid: Grid, + x: Value, + y: Value, +) -> BResult<[Value; 4]> { + let [bw, bh] = decode.block_extent(); + // The four blocks whose centres surround the texel: `(x + bw / 2) / bw` and the one before, + // wrapping, with the texel's place `u` past the first's centre. + let corner = |p: &mut P<'_, '_>, v: Value, b: u32, count: Value| -> BResult<[Value; 3]> { + let shifted = p.opk(BinOp::IAdd, v, b / 2)?; + let q = p.opk(BinOp::UDiv, shifted, b)?; + let u = p.opk(BinOp::UMod, shifted, b)?; + let first = p.add(q, count)?; + let first = p.opk(BinOp::ISub, first, 1)?; + let first = p.op(BinOp::UMod, first, count)?; + let second = p.op(BinOp::UMod, q, count)?; + Ok([first, second, u]) + }; + let [x0, x1, u] = corner(p, x, bw, grid.across)?; + let [y0, y1, v] = corner(p, y, bh, grid.down)?; + let bwk = p.k(bw)?; + let bhk = p.k(bh)?; + let ru = p.op(BinOp::ISub, bwk, u)?; + let rv = p.op(BinOp::ISub, bhk, v)?; + let mut sums = [[p.zero; 4]; 2]; + for (bx, by, wx, wy) in [ + (x0, y0, ru, rv), + (x1, y0, u, rv), + (x0, y1, ru, v), + (x1, y1, u, v), + ] { + let index = grid.index(p, bx, by)?; + let [_, high] = p.block(index)?; + let colors = p.colors(high)?; + let weight = p.mul(wx, wy)?; + for (sum, color) in sums.iter_mut().zip(colors) { + for (s, c) in sum.iter_mut().zip(color) { + let term = p.mul(c, weight)?; + *s = p.add(*s, term)?; + } + } + } + // Each sum widened to 8 bits. + let mut up = [[p.zero; 4]; 2]; + for (out, sum) in up.iter_mut().zip(sums) { + for (ch, (o, s)) in out.iter_mut().zip(sum).enumerate() { + let (a, b) = match (decode.two_bits, ch < 3) { + (false, true) => (1, 6), + (false, false) => (0, 4), + (true, true) => (2, 7), + (true, false) => (1, 5), + }; + let first = p.opk(BinOp::ShiftRightLogical, s, a)?; + let second = p.opk(BinOp::ShiftRightLogical, s, b)?; + *o = p.add(first, second)?; + } + } + // The texel's own block. + let bx = p.opk(BinOp::UDiv, x, bw)?; + let by = p.opk(BinOp::UDiv, y, bh)?; + let own = grid.index(p, bx, by)?; + let [low, high] = p.block(own)?; + let mode = p.bit(high, 0)?; + let no = p.boolean(false)?; + let (weight, punch) = match decode.two_bits { + false => { + let lx = p.opk(BinOp::BitwiseAnd, x, 3)?; + let ly = p.opk(BinOp::BitwiseAnd, y, 3)?; + let ly4 = p.opk(BinOp::ShiftLeftLogical, ly, 2)?; + let at = p.add(ly4, lx)?; + let at = p.opk(BinOp::ShiftLeftLogical, at, 1)?; + let index = p.op(BinOp::ShiftRightLogical, low, at)?; + let index = p.opk(BinOp::BitwiseAnd, index, 3)?; + let punch_index = p.opk(BinOp::IAdd, index, 4)?; + let entry = p.sel(mode, punch_index, index)?; + let weight = p.entry(p.weights, entry)?; + let two = p.opk(BinOp::IEqual, index, 2)?; + (weight, p.op(BinOp::LogicalAnd, mode, two)?) + } + true => { + let width = p.opk(BinOp::IMul, grid.across, bw)?; + let height = p.opk(BinOp::IMul, grid.down, bh)?; + let [left, right] = neighbours(p, x, width)?; + let [above, below] = neighbours(p, y, height)?; + let centre = stored(p, grid, x, y)?; + let s_above = stored(p, grid, x, above)?; + let s_below = stored(p, grid, x, below)?; + let s_left = stored(p, grid, left, y)?; + let s_right = stored(p, grid, right, y)?; + // The four neighbours' average, `(s + 2) / 4`. + let four = p.add(s_above, s_below)?; + let four = p.add(four, s_left)?; + let four = p.add(four, s_right)?; + let four = p.opk(BinOp::IAdd, four, 2)?; + let four = p.opk(BinOp::ShiftRightLogical, four, 2)?; + // The vertical or horizontal pair's, `(a + b + 1) / 2`, by bit 20 as stored. + let vertical = p.add(s_above, s_below)?; + let vertical = p.opk(BinOp::IAdd, vertical, 1)?; + let vertical = p.opk(BinOp::ShiftRightLogical, vertical, 1)?; + let horizontal = p.add(s_left, s_right)?; + let horizontal = p.opk(BinOp::IAdd, horizontal, 1)?; + let horizontal = p.opk(BinOp::ShiftRightLogical, horizontal, 1)?; + let up_down = p.bit(low, 20)?; + let pair = p.sel(up_down, vertical, horizontal)?; + let flagged = p.bit(low, 0)?; + let between = p.sel(flagged, pair, four)?; + let parity = p.op(BinOp::BitwiseXor, x, y)?; + let odd = p.bit(parity, 0)?; + let interpolated = p.op(BinOp::LogicalAnd, mode, odd)?; + (p.sel(interpolated, between, centre)?, no) + } + }; + let eight = p.k(8)?; + let rest = p.op(BinOp::ISub, eight, weight)?; + let mut codes = [p.zero; 4]; + for (ch, code) in codes.iter_mut().enumerate() { + let a = p.mul(up[0][ch], rest)?; + let b = p.mul(up[1][ch], weight)?; + let sum = p.add(a, b)?; + *code = p.opk(BinOp::ShiftRightLogical, sum, 3)?; + } + codes[3] = match decode.alpha { + true => p.sel(punch, p.zero, codes[3])?, + false => p.k(255)?, + }; + Ok(codes) +} + +/// The module of `decode` as a typed module, before serialization: the module +/// [`pvrtc_decode_module`](super::pvrtc_decode_module) serializes, which the CPU interpreter +/// runs. Its bindings are the block decode's (`BlockDecodeModule`), its shape +/// [`PvrtcDecode::shape`]'s. +pub(super) fn typed_module(decode: PvrtcDecode) -> BResult { + let mut b = ModuleBuilder::new(); + let u32_ = b.ty(Type::Int { + width: 32, + signed: false, + })?; + let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; + let shape = words_buffer(&mut b, SHAPE, u32_)?; + let blocks = words_buffer(&mut b, BLOCKS, u32_)?; + let texel_words = words_buffer(&mut b, TEXELS, u32_)?; + let weights = table(&mut b, u32_, &[WEIGHTS, PUNCH_WEIGHTS].concat())?; + let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?; + let void = b.ty(Type::Void)?; + let mut f = b.function(void)?; + let zero = scalar(&mut f, u32_, 0)?; + let invocation = f.module().global_value(invocation)?; + let invocation = f.load(invocation, MemAccess::default())?; + let x = f.composite_extract(invocation, &[0])?; + let y = f.composite_extract(invocation, &[1])?; + let z = f.composite_extract(invocation, &[2])?; + let shape = f.module().global_value(shape)?; + let field = |f: &mut FunctionBuilder<'_>, index: u32| -> BResult { + let index = scalar(f, u32_, u64::from(index))?; + let p = f.access_chain(shape, &[zero, index])?; + f.load(p, MemAccess::default()) + }; + let width = field(&mut f, 0)?; + let rows = field(&mut f, 1)?; + let images = field(&mut f, 2)?; + let first = field(&mut f, 3)?; + let height = field(&mut f, 4)?; + let in_x = f.binary(BinOp::ULessThan, x, width)?; + let in_y = f.binary(BinOp::ULessThan, y, rows)?; + let in_z = f.binary(BinOp::ULessThan, z, images)?; + let inside = f.binary(BinOp::LogicalAnd, in_x, in_y)?; + let inside = f.binary(BinOp::LogicalAnd, inside, in_z)?; + let blocks = f.module().global_value(blocks)?; + let texel_words = f.module().global_value(texel_words)?; + let decoded: ArmFn<'_, ()> = Box::new(move |f, _| { + let mut p = P { + f, + u32_, + zero, + blocks, + weights, + }; + let [bw, bh] = decode.block_extent(); + let across = p.opk(BinOp::IAdd, width, bw - 1)?; + let across = p.opk(BinOp::UDiv, across, bw)?; + let down = p.opk(BinOp::IAdd, height, bh - 1)?; + let down = p.opk(BinOp::UDiv, down, bh)?; + let per_image = p.mul(across, down)?; + let base = p.mul(z, per_image)?; + let grid = Grid { base, across, down }; + let level_y = p.add(first, y)?; + let codes = texel(&mut p, decode, grid, x, level_y)?; + let mut packed = zero; + for (ch, code) in (0u32..).zip(codes) { + let placed = p.opk(BinOp::ShiftLeftLogical, code, 8 * ch)?; + packed = p.op(BinOp::BitwiseOr, packed, placed)?; + } + // The texel's word, `(z · rows + y) · width + x`. + let at = p.mul(z, rows)?; + let at = p.add(at, y)?; + let at = p.mul(at, width)?; + let at = p.add(at, x)?; + let ptr = p.f.access_chain(texel_words, &[zero, at])?; + p.f.store(ptr, packed, MemAccess::default())?; + Ok(ArmEnd::FallThrough(Vec::new())) + }); + f.if_(&mut (), inside, decoded, None)?; + f.ret(None)?; + let id = f.finish()?; + b.entry( + ExecModel::GLCompute, + id, + vec![ExecMode::LocalSize { + x: BlockDecodeModule::LOCAL_SIZE, + y: BlockDecodeModule::LOCAL_SIZE, + z: 1, + }], + )?; + b.finalize() +} diff --git a/crates/metal2vulkan/src/bind/pvrtc_decode/tests.rs b/crates/metal2vulkan/src/bind/pvrtc_decode/tests.rs new file mode 100644 index 000000000..7e8459cc1 --- /dev/null +++ b/crates/metal2vulkan/src/bind/pvrtc_decode/tests.rs @@ -0,0 +1,210 @@ +//! The PVRTC decode against Metal's reads of seeded random blocks on an Apple M3 Max (macOS +//! 27.0.1). + +use super::kernel::typed_module; +use super::PvrtcDecode; +use crate::bind::block_decode::{BlockDecodeModule, BLOCKS, SHAPE, TEXELS}; +use crate::metal::PixelFormat; +use crate::spirv::interp::{run, Buffer, Config, Order, Resources}; +use crate::spirv::testing::{assert_valid, committed_profiles}; + +/// The eight PVRTC formats decode, and no other format does. +#[test] +fn the_pvrtc_formats_alone_decode() { + use PixelFormat as P; + let decoded: Vec = PixelFormat::ALL + .iter() + .copied() + .filter(|&pf| PvrtcDecode::of(pf).is_some()) + .collect(); + assert_eq!( + decoded, + [ + P::PVRTCRGB2BPP, + P::PVRTCRGB2BPPSRGB, + P::PVRTCRGB4BPP, + P::PVRTCRGB4BPPSRGB, + P::PVRTCRGBA2BPP, + P::PVRTCRGBA2BPPSRGB, + P::PVRTCRGBA4BPP, + P::PVRTCRGBA4BPPSRGB, + ] + ); +} + +/// `n` bytes of the xorshift64* stream from `seed`, each word little-endian. +pub(crate) fn stream(seed: u64, n: usize) -> Vec { + let mut x = seed; + let mut out = Vec::with_capacity(n + 8); + while out.len() < n { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + out.extend_from_slice(&x.wrapping_mul(0x2545_F491_4F6C_DD1D).to_le_bytes()); + } + out.truncate(n); + out +} + +fn fnv1a(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| { + (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3) + }) +} + +/// The seeded blocks of a 256 x 256 level of `decode`: the stream of seed `0x9E3779B97F4A7C15` +/// (64 x 64 blocks of 4 bits a pixel) or `0x94D049BB133111EB` (32 x 64 of 2 bits). +pub(crate) fn seeded_level(decode: PvrtcDecode) -> Vec { + match decode.two_bits { + true => stream(0x94D0_49BB_1331_11EB, 16384), + false => stream(0x9E37_79B9_7F4A_7C15, 32768), + } +} + +/// Every texel of a 256 x 256 level of seeded blocks of each format is Metal's read: the `float` +/// texels' FNV-1a digest equals the digest of an Apple M3 Max's `texture.read` of the same blocks +/// into `float4` (macOS 27.0.1, our probe, blocks copied in row by row). +#[test] +fn seeded_levels_read_as_metal_read_them() { + use PixelFormat as P; + const DIGESTS: [(PixelFormat, u64); 8] = [ + (P::PVRTCRGB2BPP, 0x1dcf_129a_314f_4a74), + (P::PVRTCRGB2BPPSRGB, 0xf537_90ff_99cb_07a6), + (P::PVRTCRGB4BPP, 0x6ff3_effe_37da_4b93), + (P::PVRTCRGB4BPPSRGB, 0x3c5d_1352_5f6e_557d), + (P::PVRTCRGBA2BPP, 0x2fc4_4e77_57f6_25b8), + (P::PVRTCRGBA2BPPSRGB, 0xd579_d21f_5b64_7af2), + (P::PVRTCRGBA4BPP, 0x990f_73ea_8038_c524), + (P::PVRTCRGBA4BPPSRGB, 0xac54_5407_88bb_89b2), + ]; + for (pf, digest) in DIGESTS { + let decode = PvrtcDecode::of(pf).expect("a decode"); + let blocks = seeded_level(decode); + let codes = decode.decode(&blocks, [256, 256, 1]); + let values: Vec = (codes.iter().enumerate()) + .flat_map(|(i, &c)| decode.metal_value(i % 4, c).to_le_bytes()) + .collect(); + assert_eq!(fnv1a(&values), digest, "{pf:?}"); + } +} + +/// An sRGB format's blocks decode to its linear form's codes, which Metal reads through its +/// table: one twin serves both forms' views. +#[test] +fn an_srgb_format_decodes_to_its_linear_form_s_codes() { + for (srgb, linear) in [ + (PixelFormat::PVRTCRGBA4BPPSRGB, PixelFormat::PVRTCRGBA4BPP), + (PixelFormat::PVRTCRGB2BPPSRGB, PixelFormat::PVRTCRGB2BPP), + ] { + let (srgb, linear) = (PvrtcDecode::of(srgb), PvrtcDecode::of(linear)); + let (srgb, linear) = (srgb.expect("a decode"), linear.expect("a decode")); + assert_eq!(srgb.linear(), linear); + let blocks = seeded_level(srgb); + let size = [64, 64, 1]; + assert_eq!(srgb.decode(&blocks, size), linear.decode(&blocks, size)); + assert_ne!(srgb.metal_value(0, 128), linear.metal_value(0, 128)); + assert_eq!(srgb.metal_value(3, 128), linear.metal_value(3, 128)); + } +} + +/// Two images of a level decode apart, each wrapping at its own blocks; a level smaller than a +/// block decodes its one block's texels; a band of rows reads what the whole image's decode holds +/// there. +#[test] +fn images_small_levels_and_bands_decode_apart() { + let decode = PvrtcDecode::of(PixelFormat::PVRTCRGBA2BPP).expect("a decode"); + let blocks = seeded_level(decode); + // A 32 x 16 level of 8 x 4 blocks: 4 x 4 of them, 128 bytes an image. + let image = decode.level_bytes([32, 16]); + assert_eq!(image, 128); + let two = decode.decode(&blocks[..2 * image], [32, 16, 2]); + let first = decode.decode(&blocks[..image], [32, 16, 1]); + let second = decode.decode(&blocks[image..2 * image], [32, 16, 1]); + assert_eq!(two, [first.clone(), second].concat()); + assert_eq!(decode.decode(&blocks[..8], [4, 4, 1]).len(), 64); + let mut band = vec![0; 32 * 5 * 4]; + decode.decode_rows(&blocks[..image], [32, 16], [7, 5], &mut band); + assert_eq!(band, first[32 * 7 * 4..32 * 12 * 4]); +} + +#[test] +fn the_pvrtc_decode_kernels_are_valid_on_every_committed_profile() { + let profiles = committed_profiles().expect("profiles"); + for pf in [PixelFormat::PVRTCRGBA2BPPSRGB, PixelFormat::PVRTCRGB4BPP] { + let decode = PvrtcDecode::of(pf).expect("a decode"); + for (_, p) in &profiles { + assert_valid(typed_module(decode).expect("module"), p); + } + } +} + +/// The kernel's texels of rows `first` to `first + rows` of `images` images of a level `level` +/// of `decode` whose `blocks` lie row-major; the texel buffer's words past the band's stay +/// unwritten. +fn kernel_texels( + decode: PvrtcDecode, + blocks: &[u8], + level: [u32; 2], + band: [u32; 2], + images: u32, +) -> Vec { + let m = typed_module(decode).expect("module"); + let (w, rows) = (level[0], band[1]); + let length = (w * rows * images * PvrtcDecode::TEXEL_BYTES) as usize; + let res = Resources { + buffers: vec![ + Buffer { + slot: Some(SHAPE), + address: None, + bytes: PvrtcDecode::shape(level, band, images).to_vec(), + }, + Buffer { + slot: Some(BLOCKS), + address: None, + bytes: blocks.to_vec(), + }, + Buffer { + slot: Some(TEXELS), + address: None, + bytes: vec![0xcd; length + 64], + }, + ], + push: Vec::new(), + spec: Default::default(), + }; + let groups = |n: u32| n.div_ceil(BlockDecodeModule::LOCAL_SIZE); + let cfg = Config { + order: Order::Forward, + workgroups: [groups(w) + 1, groups(rows), images + 1], + step_limit: 1 << 26, + ..Config::default() + }; + let mut out = run(&m, &cfg, res).expect("run").buffers; + let written = out.swap_remove(2); + assert!(written[length..].iter().all(|&b| b == 0xcd), "{decode:?}"); + written[..length].to_vec() +} + +/// The kernel writes the CPU's decode (Metal's, `seeded_levels_read_as_metal_read_them`) on every +/// format: a level of seeded blocks whole, a band of its rows, two images, and levels no larger +/// than a block. +#[test] +fn the_pvrtc_kernel_is_the_decode_on_every_texel() { + for &pf in PixelFormat::ALL { + let Some(decode) = PvrtcDecode::of(pf) else { + continue; + }; + let blocks = seeded_level(decode); + for level in [[32, 32], [16, 8], [8, 8], [4, 4], [2, 2], [1, 1]] { + let image = decode.level_bytes(level); + let cpu = decode.decode(&blocks[..2 * image], [level[0], level[1], 2]); + let gpu = kernel_texels(decode, &blocks, level, [0, level[1]], 2); + assert_eq!(gpu, cpu, "{pf:?} {level:?}"); + } + let level = [32, 32]; + let mut cpu = vec![0; 32 * 9 * 4]; + decode.decode_rows(&blocks, level, [13, 9], &mut cpu); + let gpu = kernel_texels(decode, &blocks, level, [13, 9], 1); + assert_eq!(gpu, cpu, "{pf:?} band"); + } +} diff --git a/crates/metal2vulkan/src/device/policy.rs b/crates/metal2vulkan/src/device/policy.rs index 913fce288..655a3758d 100644 --- a/crates/metal2vulkan/src/device/policy.rs +++ b/crates/metal2vulkan/src/device/policy.rs @@ -58,10 +58,10 @@ pub struct DevicePolicy { /// attachment in the device's blend (the default) or in Metal's `half` arithmetic, which the /// function computes in the shader. pub half_blend: HalfBlendPolicy, - /// Whether a texture over a buffer whose rows (or slices) lie with bytes between them, and - /// which only reads (its usage holds no `RenderTarget`, `ShaderWrite`, `ShaderAtomic` or block - /// writes), is an image over the buffer's bytes at Metal's row pitch (the default) or the - /// runtime's shadow of them, copied in before each use. The runtime's choice alone: no + /// Whether a texture whose format the device lacks, held in a carrier (an ASTC LDR texture, + /// or an EAC 11-bit one), samples a decoded twin of compact codes (the default) or of Metal's + /// values exactly. The runtime's choice alone: no emitted code changes. + pub decoded_texels: DecodedTexelsPolicy, /// emitted code changes. pub padded_reads: PaddedReadsPolicy, } @@ -89,7 +89,7 @@ impl DevicePolicy { nan_and_min_max: NanMinMaxPolicy::Native, rounding_order: RoundingOrderPolicy::Native, half_blend: HalfBlendPolicy::Device, - padded_reads: PaddedReadsPolicy::Alias, + decoded_texels: DecodedTexelsPolicy::Compact, }; /// This policy with Metal's answer wherever the choices offer it: its maths functions, @@ -110,7 +110,7 @@ impl DevicePolicy { nan_and_min_max: NanMinMaxPolicy::Exact, rounding_order: RoundingOrderPolicy::Exact, half_blend: HalfBlendPolicy::Exact, - padded_reads: PaddedReadsPolicy::Shadow, + decoded_texels: DecodedTexelsPolicy::Exact, ..self } } @@ -387,31 +387,29 @@ pub enum HalfBlendPolicy { Exact, } -/// How the runtime makes a texture over a buffer whose rows (or an array's slices) lie with bytes -/// between them that are not its texels (a guest browser's padded surfaces), and which only reads: -/// its usage, as Metal reports it (`Unknown` reads as `ShaderRead | ShaderWrite | RenderTarget | -/// PixelFormatView`), holds no `RenderTarget`, `ShaderWrite`, `ShaderAtomic` or block writes. -/// Metal never writes those bytes. A render target, or a texture a shader writes, is a shadow -/// under either value: a render pass's load and store operations may write back any byte of an -/// attachment's subresource. +/// What texels the runtime holds in the decoded twin of a texture whose blocks it holds in a +/// carrier on a device without the format (the runtime's `texture/decoded_twin.rs`), which the +/// texture's samples, reads and gathers read: an ASTC LDR texture's (`bind::AstcDecode`), and an +/// EAC 11-bit texture's (`bind::EtcDecode`). Metal reads an ASTC LDR channel as a 12-bit value, +/// `(C >> 4) / 4095` of the decode's 16-bit result, which no 8- or 16-bit texel holds; it reads +/// an EAC 11-bit channel as `c / 2047` (signed `c / 1023`), which no 16-bit normalized code +/// holds. (An ASTC sRGB texture's twin holds the 8-bit codes `C >> 8` under either, which its +/// slots read raw and decode through Metal's table, exact; so does a PVRTC texture's twin, and an +/// 8-bit ETC2 or EAC texture's.) The runtime's choice alone: no emitted code changes. #[non_exhaustive] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum PaddedReadsPolicy { - /// An image over the buffer's bytes at Metal's row pitch, as a texture whose rows lie one - /// after another has (the default): the device's own linear image, a `DRM_FORMAT_MOD_LINEAR` - /// image at that pitch, or one over a dma-buf of the pages, holding the bytes between the - /// rows in its subresource. After its first move every command uses it in `GENERAL`, and - /// copies and shader reads touch its texels alone; the first move, a layout transition, "may - /// perform read and write accesses on all memory bound to the image subresource range" - /// (Vulkan's Image Layout Transitions), and from `UNDEFINED` may discard it. So the runtime - /// keeps the bytes the image is bound to, the bytes between the rows among them, on the host - /// across that move; a CPU write to them meanwhile is undone (docs/FAST-PATHS.md, its known - /// gaps). +pub enum DecodedTexelsPolicy { + /// Compact texels (the default): an ASTC LDR texture's `R8G8B8A8_UNORM` codes, 4 bytes a + /// texel, each channel the code nearest Metal's value, at most `1/510` off it. An EAC 11-bit + /// texture's 16-bit normalized codes (`R16_UNORM`, `R16_SNORM` and their two-channel forms), + /// 2 bytes a channel, each nearest Metal's value, at most half a 16-bit step off it. + /// Announced `decoded-texel-precision` where such a texture is made. #[default] - Alias, - /// The runtime's shadow image of the texels, copied in from the buffer before each use: the - /// copies address the texels alone, so no byte between the rows is ever read or written - /// through an image. - Shadow, + Compact, + /// Metal's values exactly, an ASTC LDR texture's in `R32G32B32A32_SFLOAT`, 16 bytes a texel + /// (an EAC 11-bit texture's in `R32_SFLOAT` or `R32G32_SFLOAT`, 4 bytes a channel), where the + /// device samples, filters and copies into the format (else the compact texels, announced). + Exact, +} } diff --git a/crates/metal2vulkan/src/metal/bicubic.rs b/crates/metal2vulkan/src/metal/bicubic.rs index e01e2c2a8..869f5e05e 100644 --- a/crates/metal2vulkan/src/metal/bicubic.rs +++ b/crates/metal2vulkan/src/metal/bicubic.rs @@ -247,8 +247,38 @@ pub fn texels(pf: PixelFormat) -> Option { P::RGBX8UnormSRGB => (T::UNORM, RGB), P::RGBX8Snorm => (exact8s, RGB), P::RGBX16Float => (T::HALF, RGB), - // A BC sRGB form reads its codes through its unorm view, as an 8-bit sRGB format does. - P::BC1RGBASRGB | P::BC2RGBASRGB | P::BC3RGBASRGB | P::BC7RGBAUnormSRGB => (T::UNORM, RGBA), + // A 4:2:2 format reads as an `RGBA8Unorm` texture of its decoded codes, alpha 1 (our probe + // on an Apple M3 Max under macOS 27.0.1: reads, nearest, linear and bicubic samples and + // gathers bit for bit, `bind::ChromaDecode`): `RGBX8Unorm`'s treatment. + P::GBGR422 | P::BGRG422 => (exact8u, RGB), + // A BC sRGB form reads its codes through its unorm view, as an 8-bit sRGB format does; + // so does a PVRTC, ETC2 or EAC sRGB form (its linear form's codes, `bind::PvrtcDecode`, + // `bind::EtcDecode`), an RGB one's alpha 1, and an ASTC sRGB form its decoded twin's + // (`bind::AstcDecode`; a device with the format decodes it itself, and the binder takes + // this treatment there for none, `metal::texel_format::srgb_raw_on`). + P::BC1RGBASRGB + | P::BC2RGBASRGB + | P::BC3RGBASRGB + | P::BC7RGBAUnormSRGB + | P::PVRTCRGBA2BPPSRGB + | P::PVRTCRGBA4BPPSRGB + | P::ETC2RGB8A1SRGB + | P::EACRGBA8SRGB + | P::ASTC4x4SRGB + | P::ASTC5x4SRGB + | P::ASTC5x5SRGB + | P::ASTC6x5SRGB + | P::ASTC6x6SRGB + | P::ASTC8x5SRGB + | P::ASTC8x6SRGB + | P::ASTC8x8SRGB + | P::ASTC10x5SRGB + | P::ASTC10x6SRGB + | P::ASTC10x8SRGB + | P::ASTC10x10SRGB + | P::ASTC12x10SRGB + | P::ASTC12x12SRGB => (T::UNORM, RGBA), + P::PVRTCRGB2BPPSRGB | P::PVRTCRGB4BPPSRGB | P::ETC2RGB8SRGB => (T::UNORM, RGB), _ => return None, }; Some(T::new(flags, channels).with_border(pf, TextureSwizzleChannels::DEFAULT)) @@ -336,12 +366,14 @@ mod tests { for pf in [ PixelFormat::BGR10XR, PixelFormat::BC1RGBA, - PixelFormat::GBGR422, + PixelFormat::ETC2RGB8, PixelFormat::RGBA8Uint, PixelFormat::Stencil8, ] { assert_eq!(texels(pf), None, "{pf:?}"); } + // A 4:2:2 format takes `RGBX8Unorm`'s treatment. + assert_eq!(t(PixelFormat::GBGR422).0, t(PixelFormat::RGBX8Unorm).0); } /// Metal's weights at every fraction `k`, four per `k` in units of `2^-16`, read from the /// impulse responses of authored case `628c2f53` (both axes answered alike). `k = 75` and diff --git a/crates/metal2vulkan/src/metal/format/mod.rs b/crates/metal2vulkan/src/metal/format/mod.rs index 17f2117be..15be43fdc 100644 --- a/crates/metal2vulkan/src/metal/format/mod.rs +++ b/crates/metal2vulkan/src/metal/format/mod.rs @@ -161,6 +161,23 @@ pub enum FormatEmulation { /// reads the nearest texel) and blends none (its validation asserts), so a filter and a blend /// are not admitted. Bfloat, + /// A compressed format the device has no format for, today an ASTC LDR, a PVRTC, an ETC2 or + /// an EAC one (or its `_sRGB` form), or a 4:2:2 one (`GBGR422`, `BGRG422`, whose Vulkan + /// formats reconstruct chroma by the implementation's rules): the texture's blocks are held + /// for copies alone, and its sampled views present a decoded twin, an image of Metal's decode + /// of them ([`AstcDecode`](crate::bind::AstcDecode), [`PvrtcDecode`](crate::bind::PvrtcDecode), + /// [`EtcDecode`](crate::bind::EtcDecode), [`ChromaDecode`](crate::bind::ChromaDecode)), which + /// the consumer decodes after each write. The candidate's format is the twin's view of compact + /// texels, `R8G8B8A8_UNORM` (an `_sRGB` form's `R8G8B8A8_SRGB`), whose texels are 8-bit codes + /// of Metal's values (a PVRTC, ETC2, EAC or 4:2:2 format's own codes, an sRGB one's read raw, + /// `texel_format::srgb_raw`), or an EAC 11-bit + /// format's 16-bit normalized codes nearest Metal's values (`R16_UNORM`, `R16_SNORM` and their + /// two-channel forms); for an ASTC or an EAC 11-bit format the consumer may hold Metal's values + /// exactly as `float`s instead ([`AstcTexels`](crate::bind::AstcTexels), + /// [`EtcTexels`](crate::bind::EtcTexels)), whose views it presents for the candidate's. + /// Admitted for sampling only: Metal's functions do not write a compressed texture, and no + /// pass renders into one. + Decoded, } impl FormatEmulation { @@ -206,6 +223,10 @@ impl FormatEmulation { U::SampledImage | U::StorageImage | U::ColorAttachment ) } + FormatEmulation::Decoded => matches!( + usage, + U::SampledImage | U::SampledImageFilterLinear | U::SampledImageFilterMinmax + ), FormatEmulation::StencilInCombined | FormatEmulation::DepthInCombined | FormatEmulation::DepthWidened => matches!( @@ -985,6 +1006,15 @@ fn ycbcr_repr(pf: PixelFormat) -> Repr { } } +/// The candidates of a compressed format whose block is `block`: the block, then the decoded twin +/// whose view is `twin` ([`FormatEmulation::Decoded`]). +fn decoded(block: vk::Format, twin: vk::Format) -> Repr { + color(vec![ + direct(block), + combined(twin, FormatEmulation::Decoded), + ]) +} + /// The pattern of ASTC's 4x2 and 8x4 formats, LDR, sRGB and HDR: Metal makes a 2D texture of /// each from a descriptor alone (an Apple M4 under macOS 27.0.1, EV GSM2-fmt0-m4), and no Vulkan /// ASTC block has either footprint, so this crate holds none of them (`repr`'s `NotImplemented`). @@ -1347,54 +1377,62 @@ fn make_repr(pf: PixelFormat) -> Repr { P::BC6HRGBUfloat => one(F::BC6H_UFLOAT_BLOCK), P::BC7RGBAUnorm => one(F::BC7_UNORM_BLOCK), P::BC7RGBAUnormSRGB => one(F::BC7_SRGB_BLOCK), - // PVRTC1 blocks behind `VK_IMG_format_pvrtc` (never promoted). Vulkan has only the RGBA - // formats; reading Metal's RGB formats through them needs the alpha a decoder returns for - // RGB data, which is not established (a swizzle to one would assume it). - P::PVRTCRGBA2BPP => one(F::PVRTC1_2BPP_UNORM_BLOCK_IMG), - P::PVRTCRGBA2BPPSRGB => one(F::PVRTC1_2BPP_SRGB_BLOCK_IMG), - P::PVRTCRGBA4BPP => one(F::PVRTC1_4BPP_UNORM_BLOCK_IMG), - P::PVRTCRGBA4BPPSRGB => one(F::PVRTC1_4BPP_SRGB_BLOCK_IMG), - P::PVRTCRGB2BPP | P::PVRTCRGB2BPPSRGB | P::PVRTCRGB4BPP | P::PVRTCRGB4BPPSRGB => { - Repr::NotImplemented + // PVRTC1 blocks behind `VK_IMG_format_pvrtc` (never promoted), else the decoded twin's + // view of their codes (`FormatEmulation::Decoded`). Vulkan has only the RGBA formats; + // reading Metal's RGB formats through them needs the alpha a decoder returns for RGB + // data, which is not established (a swizzle to one would assume it), so those take the + // twin alone. + P::PVRTCRGBA2BPP => decoded(F::PVRTC1_2BPP_UNORM_BLOCK_IMG, F::R8G8B8A8_UNORM), + P::PVRTCRGBA2BPPSRGB => decoded(F::PVRTC1_2BPP_SRGB_BLOCK_IMG, F::R8G8B8A8_SRGB), + P::PVRTCRGBA4BPP => decoded(F::PVRTC1_4BPP_UNORM_BLOCK_IMG, F::R8G8B8A8_UNORM), + P::PVRTCRGBA4BPPSRGB => decoded(F::PVRTC1_4BPP_SRGB_BLOCK_IMG, F::R8G8B8A8_SRGB), + P::PVRTCRGB2BPP | P::PVRTCRGB4BPP => { + color(vec![combined(F::R8G8B8A8_UNORM, FormatEmulation::Decoded)]) } - P::EACR11Unorm => one(F::EAC_R11_UNORM_BLOCK), - P::EACR11Snorm => one(F::EAC_R11_SNORM_BLOCK), - P::EACRG11Unorm => one(F::EAC_R11G11_UNORM_BLOCK), - P::EACRG11Snorm => one(F::EAC_R11G11_SNORM_BLOCK), - P::EACRGBA8 => one(F::ETC2_R8G8B8A8_UNORM_BLOCK), - P::EACRGBA8SRGB => one(F::ETC2_R8G8B8A8_SRGB_BLOCK), - P::ETC2RGB8 => one(F::ETC2_R8G8B8_UNORM_BLOCK), - P::ETC2RGB8SRGB => one(F::ETC2_R8G8B8_SRGB_BLOCK), - P::ETC2RGB8A1 => one(F::ETC2_R8G8B8A1_UNORM_BLOCK), - P::ETC2RGB8A1SRGB => one(F::ETC2_R8G8B8A1_SRGB_BLOCK), - P::ASTC4x4SRGB => one(F::ASTC_4X4_SRGB_BLOCK), - P::ASTC5x4SRGB => one(F::ASTC_5X4_SRGB_BLOCK), - P::ASTC5x5SRGB => one(F::ASTC_5X5_SRGB_BLOCK), - P::ASTC6x5SRGB => one(F::ASTC_6X5_SRGB_BLOCK), - P::ASTC6x6SRGB => one(F::ASTC_6X6_SRGB_BLOCK), - P::ASTC8x5SRGB => one(F::ASTC_8X5_SRGB_BLOCK), - P::ASTC8x6SRGB => one(F::ASTC_8X6_SRGB_BLOCK), - P::ASTC8x8SRGB => one(F::ASTC_8X8_SRGB_BLOCK), - P::ASTC10x5SRGB => one(F::ASTC_10X5_SRGB_BLOCK), - P::ASTC10x6SRGB => one(F::ASTC_10X6_SRGB_BLOCK), - P::ASTC10x8SRGB => one(F::ASTC_10X8_SRGB_BLOCK), - P::ASTC10x10SRGB => one(F::ASTC_10X10_SRGB_BLOCK), - P::ASTC12x10SRGB => one(F::ASTC_12X10_SRGB_BLOCK), - P::ASTC12x12SRGB => one(F::ASTC_12X12_SRGB_BLOCK), - P::ASTC4x4LDR => one(F::ASTC_4X4_UNORM_BLOCK), - P::ASTC5x4LDR => one(F::ASTC_5X4_UNORM_BLOCK), - P::ASTC5x5LDR => one(F::ASTC_5X5_UNORM_BLOCK), - P::ASTC6x5LDR => one(F::ASTC_6X5_UNORM_BLOCK), - P::ASTC6x6LDR => one(F::ASTC_6X6_UNORM_BLOCK), - P::ASTC8x5LDR => one(F::ASTC_8X5_UNORM_BLOCK), - P::ASTC8x6LDR => one(F::ASTC_8X6_UNORM_BLOCK), - P::ASTC8x8LDR => one(F::ASTC_8X8_UNORM_BLOCK), - P::ASTC10x5LDR => one(F::ASTC_10X5_UNORM_BLOCK), - P::ASTC10x6LDR => one(F::ASTC_10X6_UNORM_BLOCK), - P::ASTC10x8LDR => one(F::ASTC_10X8_UNORM_BLOCK), - P::ASTC10x10LDR => one(F::ASTC_10X10_UNORM_BLOCK), - P::ASTC12x10LDR => one(F::ASTC_12X10_UNORM_BLOCK), - P::ASTC12x12LDR => one(F::ASTC_12X12_UNORM_BLOCK), + P::PVRTCRGB2BPPSRGB | P::PVRTCRGB4BPPSRGB => { + color(vec![combined(F::R8G8B8A8_SRGB, FormatEmulation::Decoded)]) + } + // ETC2 and EAC: the block, else the decoded twin's view (`FormatEmulation::Decoded`) of + // its codes, or an 11-bit format's compact texels (`bind::EtcTexels`). + P::EACR11Unorm => decoded(F::EAC_R11_UNORM_BLOCK, F::R16_UNORM), + P::EACR11Snorm => decoded(F::EAC_R11_SNORM_BLOCK, F::R16_SNORM), + P::EACRG11Unorm => decoded(F::EAC_R11G11_UNORM_BLOCK, F::R16G16_UNORM), + P::EACRG11Snorm => decoded(F::EAC_R11G11_SNORM_BLOCK, F::R16G16_SNORM), + P::EACRGBA8 => decoded(F::ETC2_R8G8B8A8_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::EACRGBA8SRGB => decoded(F::ETC2_R8G8B8A8_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ETC2RGB8 => decoded(F::ETC2_R8G8B8_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::ETC2RGB8SRGB => decoded(F::ETC2_R8G8B8_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ETC2RGB8A1 => decoded(F::ETC2_R8G8B8A1_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::ETC2RGB8A1SRGB => decoded(F::ETC2_R8G8B8A1_SRGB_BLOCK, F::R8G8B8A8_SRGB), + // ASTC LDR: the block, else the decoded twin's view (`FormatEmulation::Decoded`). + P::ASTC4x4SRGB => decoded(F::ASTC_4X4_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ASTC5x4SRGB => decoded(F::ASTC_5X4_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ASTC5x5SRGB => decoded(F::ASTC_5X5_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ASTC6x5SRGB => decoded(F::ASTC_6X5_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ASTC6x6SRGB => decoded(F::ASTC_6X6_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ASTC8x5SRGB => decoded(F::ASTC_8X5_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ASTC8x6SRGB => decoded(F::ASTC_8X6_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ASTC8x8SRGB => decoded(F::ASTC_8X8_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ASTC10x5SRGB => decoded(F::ASTC_10X5_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ASTC10x6SRGB => decoded(F::ASTC_10X6_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ASTC10x8SRGB => decoded(F::ASTC_10X8_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ASTC10x10SRGB => decoded(F::ASTC_10X10_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ASTC12x10SRGB => decoded(F::ASTC_12X10_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ASTC12x12SRGB => decoded(F::ASTC_12X12_SRGB_BLOCK, F::R8G8B8A8_SRGB), + P::ASTC4x4LDR => decoded(F::ASTC_4X4_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::ASTC5x4LDR => decoded(F::ASTC_5X4_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::ASTC5x5LDR => decoded(F::ASTC_5X5_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::ASTC6x5LDR => decoded(F::ASTC_6X5_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::ASTC6x6LDR => decoded(F::ASTC_6X6_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::ASTC8x5LDR => decoded(F::ASTC_8X5_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::ASTC8x6LDR => decoded(F::ASTC_8X6_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::ASTC8x8LDR => decoded(F::ASTC_8X8_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::ASTC10x5LDR => decoded(F::ASTC_10X5_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::ASTC10x6LDR => decoded(F::ASTC_10X6_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::ASTC10x8LDR => decoded(F::ASTC_10X8_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::ASTC10x10LDR => decoded(F::ASTC_10X10_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::ASTC12x10LDR => decoded(F::ASTC_12X10_UNORM_BLOCK, F::R8G8B8A8_UNORM), + P::ASTC12x12LDR => decoded(F::ASTC_12X12_UNORM_BLOCK, F::R8G8B8A8_UNORM), // The ASTC HDR profile: the `SFLOAT` blocks (core 1.3 or // `VK_EXT_texture_compression_astc_hdr`). Like every compressed format they are usable // where the format properties say so; `textureCompressionASTC_HDR` only guarantees that. @@ -1412,10 +1450,13 @@ fn make_repr(pf: PixelFormat) -> Repr { P::ASTC10x10HDR => one(F::ASTC_10X10_SFLOAT_BLOCK), P::ASTC12x10HDR => one(F::ASTC_12X10_SFLOAT_BLOCK), P::ASTC12x12HDR => one(F::ASTC_12X12_SFLOAT_BLOCK), - // `G8B8G8R8_422_UNORM`/`B8G8R8G8_422_UNORM` exist (core 1.1), but a view of them needs a - // sampler Y′CbCr conversion (VUID-VkImageViewCreateInfo-format-06415), which neither the - // binder nor lowering models. - P::GBGR422 | P::BGRG422 => Repr::NotImplemented, + // 4:2:2: `G8B8G8R8_422_UNORM`/`B8G8R8G8_422_UNORM` exist (core 1.1), but a view of them + // needs a sampler Y′CbCr conversion (VUID-VkImageViewCreateInfo-format-06415), whose + // chroma reconstruction is the implementation's. The decoded twin's view + // (`FormatEmulation::Decoded`) holds Metal's texels instead (`bind::ChromaDecode`). + P::GBGR422 | P::BGRG422 => { + color(vec![combined(F::R8G8B8A8_UNORM, FormatEmulation::Decoded)]) + } two_plane_ycbcr!() => ycbcr_repr(pf), // Formats Metal makes no texture of from a descriptor alone (EV XRR2-ycc1-m4); one over // an IOSurface plane is not modelled. @@ -1659,8 +1700,8 @@ fn candidates(pf: PixelFormat) -> Result<(vk::ImageAspectFlags, &'static [Candid } /// The UNORM format of an 8-bit sRGB format whose texels Metal decodes from their raw codes -/// (`R8Unorm_sRGB`, `RG8Unorm_sRGB`, `RGBA8Unorm_sRGB`, `BGRA8Unorm_sRGB`; a BC sRGB format's -/// unorm form, the same blocks): the same channels and bits, its texels the sRGB format's codes +/// (`R8Unorm_sRGB`, `RG8Unorm_sRGB`, `RGBA8Unorm_sRGB`, `BGRA8Unorm_sRGB`; a BC, PVRTC, ETC2 or +/// EAC sRGB format's unorm form, the same blocks): the same channels and bits, its texels the sRGB format's codes /// read as `c / 255`. A device that cannot sample the sRGB format holds a sampled texture of it in /// this format, and a pipeline reads the raw codes through its view and decodes them as Metal does. /// `None` for any other format. @@ -1676,6 +1717,13 @@ pub fn srgb_raw_twin(pf: PixelFormat) -> Option { P::BC2RGBASRGB => P::BC2RGBA, P::BC3RGBASRGB => P::BC3RGBA, P::BC7RGBAUnormSRGB => P::BC7RGBAUnorm, + P::PVRTCRGB2BPPSRGB => P::PVRTCRGB2BPP, + P::PVRTCRGB4BPPSRGB => P::PVRTCRGB4BPP, + P::PVRTCRGBA2BPPSRGB => P::PVRTCRGBA2BPP, + P::PVRTCRGBA4BPPSRGB => P::PVRTCRGBA4BPP, + P::ETC2RGB8SRGB => P::ETC2RGB8, + P::ETC2RGB8A1SRGB => P::ETC2RGB8A1, + P::EACRGBA8SRGB => P::EACRGBA8, _ => return None, }) } @@ -1736,10 +1784,15 @@ pub fn bound_texel_format(pf: PixelFormat) -> u32 { crate::metal::texel_format::texel_format(pf).0 } -/// The direct Vulkan format of `pf` (its first candidate), independent of any device. +/// The direct Vulkan format of `pf` (its first candidate), independent of any device: `None` for +/// a format held only through its decoded twin's view ([`FormatEmulation::Decoded`], the PVRTC +/// RGB formats), whose blocks no Vulkan format holds. pub fn direct_format(pf: PixelFormat) -> Option { match repr(pf) { - Repr::Candidates(_, c) => c.first().map(|c| c.format), + Repr::Candidates(_, c) => c + .first() + .filter(|c| c.emulation != FormatEmulation::Decoded) + .map(|c| c.format), _ => None, } } diff --git a/crates/metal2vulkan/src/metal/format/tests.rs b/crates/metal2vulkan/src/metal/format/tests.rs index 226d44936..bc9914a01 100644 --- a/crates/metal2vulkan/src/metal/format/tests.rs +++ b/crates/metal2vulkan/src/metal/format/tests.rs @@ -72,9 +72,8 @@ fn refused_formats_are_exactly_the_documented_set() { } let count = |class: &str| refused.get(class).map_or(0, Vec::len); assert_eq!(refused["placeholder"], [P::Invalid, P::Unspecialized]); - // 4 PVRTC RGB (Vulkan's PVRTC1 formats are RGBA) + 2 Y′CbCr 4:2:2. The two-plane extended-range - // pair is held raw. - // + the 68 two-plane YCbCr formats but `YCBCR8_420_2P`, and the 3 others Metal makes no + // The two-plane extended-range pair is held raw, the 4:2:2 pair through its decoded twin. + // The 68 two-plane YCbCr formats but `YCBCR8_420_2P`, and the 3 others Metal makes no // texture of from a descriptor alone. // + ASTC's 6 formats of a 4x2 or 8x4 footprint, which no Vulkan block has. // - `YCBCR10_420_2P`, `RGB10_420_2P` and the `_sRGB` twins of the 4:2:0 converted pair, made @@ -88,11 +87,9 @@ fn refused_formats_are_exactly_the_documented_set() { // - their `_sRGB` twins, held raw. // - the eleven RGBX formats, held in their RGBA twins. // - the three bfloat formats, held raw. - assert_eq!(count("not_implemented"), 6 + 45 + 3 + 6 + 62, "{refused:?}"); + assert_eq!(count("not_implemented"), 45 + 3 + 6 + 62, "{refused:?}"); assert!(refused["not_implemented"].iter().all(|&pf| { - pf.name().contains("PVRTC_RGB_") - || matches!(pf, P::GBGR422 | P::BGRG422) - || (ycbcr_format(pf).is_some() && !ycbcr(pf)) + (ycbcr_format(pf).is_some() && !ycbcr(pf)) || matches!(pf, P::RGBA16FloatXR | P::AnyDepth | P::AnyStencil) || matches!(pf, astc_without_a_vulkan_block!()) || matches!(pf, formats_named_not_held!()) @@ -100,7 +97,8 @@ fn refused_formats_are_exactly_the_documented_set() { } /// Every candidate is a named, non-`UNDEFINED` registry format, and the direct formats are -/// one-to-one: two Metal formats share one only when one is a stencil view of the other. +/// one-to-one: two Metal formats share one only when one is a stencil view of the other. A format +/// held only through its decoded twin's view has none. #[test] fn direct_formats_round_trip() { let mut back: BTreeMap> = BTreeMap::new(); @@ -114,6 +112,17 @@ fn direct_formats_round_trip() { assert!(c.format.is_known(), "{pf:?} -> {:?}", c.format); assert_ne!(c.format, vk::Format::UNDEFINED, "{pf:?}"); } + // A PVRTC RGB or 4:2:2 format, held through its decoded twin's view alone, has no + // direct format: no Vulkan format holds its blocks as Metal reads them. + if candidates[0].emulation == FormatEmulation::Decoded { + assert_eq!(direct_format(pf), None, "{pf:?}"); + let pvrtc = crate::bind::PvrtcDecode::of(pf).is_some(); + assert!( + pvrtc || crate::bind::ChromaDecode::of(pf).is_some(), + "{pf:?}" + ); + continue; + } assert_eq!(direct_format(pf), Some(candidates[0].format)); // `storage_image_choice` relies on it: a storage image ignores the view's mapping. The // first candidate is direct but for an extended-range format's raw bytes and @@ -397,8 +406,7 @@ fn placeholders_and_refusals_are_typed() { } other => panic!("{pf:?}: {other:?}"), }; - assert_eq!(needs(PixelFormat::PVRTCRGB4BPP), Needs::NotImplemented); - assert_eq!(needs(PixelFormat::GBGR422), Needs::NotImplemented); + assert_eq!(needs(PixelFormat::RGBA16FloatXR), Needs::NotImplemented); } /// On every committed profile, a mapping is only ever returned for supported usages, a swizzled @@ -771,7 +779,8 @@ fn a_swizzled_candidate_needs_the_subset_s_view_swizzle() { /// The ASTC HDR and PVRTC RGBA formats are their `SFLOAT` and PVRTC1 blocks where the profile /// exposes them: on `moltenvk-m3` (a 1.4 device with `VK_IMG_format_pvrtc`) they map directly; /// on the 1.2 floor listing the same blocks without the extensions, the refusal names the -/// extension. +/// extension, and for a PVRTC format the format of its decoded twin's codes, which that floor does +/// not list either. #[test] fn compressed_extension_formats_follow_exposure() { use FormatUsage as U; @@ -807,19 +816,27 @@ fn compressed_extension_formats_follow_exposure() { let m = vk_format(pf, &sampled, moltenvk.profile()).unwrap_or_else(|e| panic!("{pf:?}: {e}")); assert_eq!((m.format, m.emulation), (format, FormatEmulation::Direct)); + let mut needs = vec![vec![ + Capability::Extension(extension), + Capability::Format { + format, + usage: U::SampledImage, + }, + ]]; + // A PVRTC format's decoded twin, whose codes' format this floor does not list. + if crate::bind::PvrtcDecode::of(pf).is_some() { + let codes = match crate::metal::texel_format::srgb_raw(pf) { + true => vk::Format::R8G8B8A8_SRGB, + false => vk::Format::R8G8B8A8_UNORM, + }; + needs.push(vec![Capability::Format { + format: codes, + usage: U::SampledImage, + }]); + } assert_eq!( vk_format(pf, &sampled, floor.profile()), - Err(Unsupported::needs_any_of( - Feature::Format, - vec![vec![ - Capability::Extension(extension), - Capability::Format { - format, - usage: U::SampledImage - } - ]] - ) - .into()), + Err(Unsupported::needs_any_of(Feature::Format, needs).into()), "{pf:?}" ); } diff --git a/crates/metal2vulkan/src/metal/texel_format.rs b/crates/metal2vulkan/src/metal/texel_format.rs index 7aeec5e65..f4babcdcf 100644 --- a/crates/metal2vulkan/src/metal/texel_format.rs +++ b/crates/metal2vulkan/src/metal/texel_format.rs @@ -78,8 +78,10 @@ //! `ARGB8Unorm` takes a field too ([`PackedTexels::Argb8`]): Metal reads its one texel as `c / 255` //! correctly rounded, its bytes rotated in the view; its cube gathers and its linear filter are not //! measured, so it has no corner and no family. The unorm forms of BC1 to BC3 take the same field -//! beside their cube corner: Metal reads their decoded 8-bit codes so (EV SID2-bcd2-m4), and a -//! device's view of a decoded twin's codes may not (lavapipe's is an ulp high). A texture buffer's +//! device's view of a decoded twin's codes may not (lavapipe's is an ulp high). So do the 8-bit +//! linear ETC2 and EAC formats (`RGB8`, `RGB8A1`, `RGBA8`), beside their corner, and the linear +//! PVRTC formats, alone: Metal reads their decoded 8-bit codes as `c / 255` correctly rounded too +//! (an Apple M3 Max, `bind::EtcDecode`, `bind::PvrtcDecode`), their filters unmeasured. A texture buffer's //! texels convert as a texture's of the same format (`RGBA32Float`, `RGBA16Float`, `RGBA8Unorm`, //! and `RGBA8Snorm` read: the P2a probe). //! @@ -119,8 +121,13 @@ //! 8-bit code, alpha `c / 255`), read through their unorm views: exact where the device decodes the //! unorm form's codes as Metal does (BC7's on every venue measured, as Direct3D specifies its //! decode bit for bit; BC1 to BC3's where the driver has `DriverFact::ColorBlockDecodeIsMetals`, -//! and elsewhere announced as `compressed-texel-decode`). The other compressed and the wide sRGB -//! formats are not measured and keep the device's decode. +//! and elsewhere announced as `compressed-texel-decode`). So do the ASTC sRGB formats, whose +//! colour Metal reads as the table's step of the top byte of each channel's decode (`bind::AstcDecode`, +//! an Apple M3 Max): read through the unorm view of their decoded twin's codes on a device without +//! the format, exact; a device with it decodes them itself, as its unorm view would decode the +//! blocks the LDR way, so they take the rule only where the device holds the codes +//! ([`srgb_raw_on`]). The other compressed and the wide sRGB formats are not measured and keep the +//! device's decode. //! //! **Depth formats**. A depth texture has no `half` result, and no linear filter is emulated on //! one, so its class is read by a read, plain gather or sample of one texel with a `float` result @@ -382,13 +389,10 @@ pub enum PackedTexels { /// NaN reads `0x7fc00000` (Metal's, every NaN code of `RG11B10Float`'s rows). SmallFloat = 5, /// Every channel of 8 bits, held in its bytes' rotation: `ARGB8Unorm`, whose reads Metal - /// answers `c / 255` correctly rounded (EVs TXN-xrprobe-m3 and -m4, and its plane views over a - /// buffer, EVs TXN-xr6probe-m3 and -m4), where lavapipe's are an ulp high. Its class has no - /// family, as its border passes through the rotation. Also the unorm forms of BC1 to BC3, whose - /// blocks Metal decodes to 8-bit codes it reads as `c / 255` correctly rounded (EV - /// SID2-bcd2-m4), where lavapipe's view of a decoded twin's codes (`R8G8B8A8_UNORM`) is an ulp - /// high: beside their cube corner, with no family, Metal's linear filter of them not being - /// measured. + /// filter of them not being measured. And the 8-bit linear ETC2 and EAC formats (beside their + /// corner) and the linear PVRTC formats (alone), whose decoded 8-bit codes Metal reads so too + /// (an Apple M3 Max, `bind::EtcDecode`, `bind::PvrtcDecode`), and which a twin holds as + /// `R8G8B8A8_UNORM` codes on a device without them. Argb8 = 6, /// The 8- and 10-bit two-plane YCbCr formats' channels as their view holds them: Metal reads a /// texel as its converted color, each channel a step `k / 2048` of `[0, 1]`, and alpha as 1, @@ -440,6 +444,13 @@ impl PackedTexels { P::RG11B10Float | P::RGB9E5Float => PackedTexels::SmallFloat, P::ARGB8Unorm => PackedTexels::Argb8, P::BC1RGBA | P::BC2RGBA | P::BC3RGBA => PackedTexels::Argb8, + P::PVRTCRGB2BPP + | P::PVRTCRGB4BPP + | P::PVRTCRGBA2BPP + | P::PVRTCRGBA4BPP + | P::ETC2RGB8 + | P::ETC2RGB8A1 + | P::EACRGBA8 => PackedTexels::Argb8, _ => return None, }) } @@ -580,6 +591,10 @@ pub fn texel_format(pf: PixelFormat) -> TexelFormat { | P::RGBX16Float | P::RGBX8Unorm | P::RGBX8Snorm + // Read, sampled (nearest, linear and bicubic, `float` and `half`) and gathered as an + // `RGBX8Unorm` texture of their decoded codes (an Apple M3 Max, `bind::ChromaDecode`). + | P::GBGR422 + | P::BGRG422 ); // A depth format's cube gather: its one channel's family (module docs). match pf { @@ -923,7 +938,11 @@ pub fn heap_class_index(pf: PixelFormat, swizzle: TextureSwizzleChannels) -> u32 /// Whether Metal decodes `pf`'s texels from their raw 8-bit codes through its twelve-bit table /// (module docs): the 8-bit sRGB formats whose raw code a UNORM view of the same image reads, -/// and the sRGB forms of BC1 to BC3 and BC7, whose codes their unorm views decode. +/// the sRGB forms of BC1 to BC3 and BC7, whose codes their unorm views decode, the PVRTC, +/// ETC2 and EAC sRGB formats, whose codes their linear forms decode (`bind::PvrtcDecode`, +/// `bind::EtcDecode`; a decoded twin's codes on a device without them), and the ASTC sRGB +/// formats, whose codes their decoded twin holds (`bind::AstcDecode`), which a device takes only +/// where it holds the twin ([`srgb_raw_on`]). pub fn srgb_raw(pf: PixelFormat) -> bool { use PixelFormat as P; matches!( @@ -937,13 +956,50 @@ pub fn srgb_raw(pf: PixelFormat) -> bool { | P::BC2RGBASRGB | P::BC3RGBASRGB | P::BC7RGBAUnormSRGB + | P::PVRTCRGB2BPPSRGB + | P::PVRTCRGB4BPPSRGB + | P::PVRTCRGBA2BPPSRGB + | P::PVRTCRGBA4BPPSRGB + | P::ETC2RGB8SRGB + | P::ETC2RGB8A1SRGB + | P::EACRGBA8SRGB + | P::ASTC4x4SRGB + | P::ASTC5x4SRGB + | P::ASTC5x5SRGB + | P::ASTC6x5SRGB + | P::ASTC6x6SRGB + | P::ASTC8x5SRGB + | P::ASTC8x6SRGB + | P::ASTC8x8SRGB + | P::ASTC10x5SRGB + | P::ASTC10x6SRGB + | P::ASTC10x8SRGB + | P::ASTC10x10SRGB + | P::ASTC12x10SRGB + | P::ASTC12x12SRGB ) } +/// Whether `profile`'s device reads a texture of `pf` from its raw codes as Metal decodes them +/// ([`srgb_raw`]): where the format it samples `pf` in has a raw view ([`srgb_raw_view`]), or where +/// it samples no format of `pf`'s, which the binder holds as its UNORM twin +/// (`metal::format::srgb_raw_twin`) or refuses. An ASTC sRGB format a device samples itself has +/// none: its unorm form widens the blocks' endpoints the LDR way (`bind::AstcDecode`), so no view +/// of its image reads Metal's codes, and the device's own sRGB decode answers. +pub fn srgb_raw_on(pf: PixelFormat, profile: &crate::device::profile::DeviceProfile) -> bool { + use crate::device::requirements::FormatUsage; + let usages = [FormatUsage::SampledImage].into(); + srgb_raw(pf) + && match crate::metal::format::vk_format(pf, &usages, profile) { + Ok(m) => srgb_raw_view(m.format).is_some(), + Err(_) => true, + } +} + /// The raw view's format of an image of Vulkan format `format`, the sampled view of an -/// [`srgb_raw`] format: the UNORM format of the same channels and bits (a BC format's of the same -/// blocks), which views the image's texels as their codes (`c / 255`). `None` for any other -/// format. +/// [`srgb_raw`] format: the UNORM format of the same channels and bits (a BC, PVRTC, ETC2 or EAC +/// format's of the same blocks), which views the image's texels as their codes (`c / 255`). `None` for any +/// other format. pub fn srgb_raw_view(format: vk::Format) -> Option { use vk::Format as F; Some(match format { @@ -955,6 +1011,11 @@ pub fn srgb_raw_view(format: vk::Format) -> Option { F::BC2_SRGB_BLOCK => F::BC2_UNORM_BLOCK, F::BC3_SRGB_BLOCK => F::BC3_UNORM_BLOCK, F::BC7_SRGB_BLOCK => F::BC7_UNORM_BLOCK, + F::PVRTC1_2BPP_SRGB_BLOCK_IMG => F::PVRTC1_2BPP_UNORM_BLOCK_IMG, + F::PVRTC1_4BPP_SRGB_BLOCK_IMG => F::PVRTC1_4BPP_UNORM_BLOCK_IMG, + F::ETC2_R8G8B8_SRGB_BLOCK => F::ETC2_R8G8B8_UNORM_BLOCK, + F::ETC2_R8G8B8A1_SRGB_BLOCK => F::ETC2_R8G8B8A1_UNORM_BLOCK, + F::ETC2_R8G8B8A8_SRGB_BLOCK => F::ETC2_R8G8B8A8_UNORM_BLOCK, _ => return None, }) } @@ -964,18 +1025,20 @@ mod tests { use super::*; use BicubicTexels as T; - /// The raw view is the UNORM twin of each candidate image format of an [`srgb_raw`] format, - /// and nothing else has one. + /// The raw view is the UNORM twin of each candidate image format of an [`srgb_raw`] format (a + /// PVRTC, ETC2, EAC or ASTC sRGB format's decoded twin's among them), but an ASTC sRGB + /// format's own block, whose unorm form decodes the blocks the LDR way; nothing else has one. #[test] fn an_srgb_format_has_a_raw_view_of_its_own_channels() { for &pf in PixelFormat::ALL { - let candidates = crate::metal::format::candidate_formats(pf); - let raw: Vec> = - candidates.iter().map(|f| srgb_raw_view(*f)).collect(); - if srgb_raw(pf) { - assert!(raw.iter().all(Option::is_some), "{pf:?}: {candidates:?}"); - } else { - assert!(raw.iter().all(Option::is_none), "{pf:?}: {candidates:?}"); + let astc = crate::bind::AstcDecode::of(pf).is_some(); + for format in crate::metal::format::candidate_formats(pf) { + let own_block = astc && crate::metal::format::direct_format(pf) == Some(format); + assert_eq!( + srgb_raw_view(format).is_some(), + srgb_raw(pf) && !own_block, + "{pf:?}: {format:?}" + ); } } assert_eq!( @@ -986,7 +1049,7 @@ mod tests { /// An [`srgb_raw`] format's twin (`metal::format::srgb_raw_twin`) is a format whose direct /// image format is the raw view of the sRGB format's: the same channels and bits, read as - /// their codes; nothing else has one. + /// their codes; nothing else has one, nor an ASTC sRGB format. #[test] fn an_srgb_format_s_twin_holds_its_raw_view() { for &pf in PixelFormat::ALL { @@ -996,12 +1059,29 @@ mod tests { let own = crate::metal::format::direct_format(pf).and_then(srgb_raw_view); assert_eq!(own, crate::metal::format::direct_format(twin), "{pf:?}"); } - None => assert!(!srgb_raw(pf), "{pf:?}"), + // An ASTC sRGB format has none: its unorm form decodes the blocks otherwise. + None => assert!( + !srgb_raw(pf) || crate::bind::AstcDecode::of(pf).is_some(), + "{pf:?}" + ), } } } - /// An RGBX format converts as its RGBA twin with red, green and blue (EV FPV-pf6-m4: every + /// A 4:2:2 format reads, samples and gathers as an `RGBA8Unorm` texture of its decoded codes + /// with alpha 1 (our probe on an Apple M3 Max under macOS 27.0.1, `bind::ChromaDecode`): + /// `RGBX8Unorm`'s class, its border texels too. + #[test] + fn four_two_two_formats_convert_as_rgbx8_unorm() { + for pf in [PixelFormat::GBGR422, PixelFormat::BGRG422] { + assert_eq!( + texel_format(pf), + texel_format(PixelFormat::RGBX8Unorm), + "{pf:?}" + ); + } + } + /// read, sample, gather and bicubic sample equals the twin's but for alpha 1): its family, /// an `_sRGB` one's raw codes through the twin's raw view. #[test] @@ -1061,6 +1141,13 @@ mod tests { (PixelFormat::R8UnormSRGB, 0x1), (PixelFormat::BC1RGBASRGB, 0xF), (PixelFormat::BC7RGBAUnormSRGB, 0xF), + (PixelFormat::PVRTCRGBA2BPPSRGB, 0xF), + (PixelFormat::PVRTCRGB4BPPSRGB, 0x7), + (PixelFormat::ETC2RGB8SRGB, 0x7), + (PixelFormat::ETC2RGB8A1SRGB, 0xF), + (PixelFormat::EACRGBA8SRGB, 0xF), + (PixelFormat::ASTC4x4SRGB, 0xF), + (PixelFormat::ASTC12x12SRGB, 0xF), ] { assert_eq!( texel_format(pf).0 & !(0xfff << T::BORDER), @@ -1069,10 +1156,9 @@ mod tests { ); } for pf in [ - PixelFormat::ETC2RGB8SRGB, PixelFormat::BGRA10XRSRGB, PixelFormat::RGBA8Uint, - PixelFormat::ASTC4x4SRGB, + PixelFormat::ASTC4x4LDR, ] { assert_eq!(texel_format(pf), TexelFormat::OTHER, "{pf:?}"); } @@ -1136,8 +1222,9 @@ mod tests { /// Each packed format takes its field beside its corner, and nothing else does: the field fits /// its four bits, each value has a format, each code scale suits `texel_round::grid_value` (`1 /// <= S < 2^16`), and the field touches no other field's bit. `ARGB8Unorm`'s cube gathers and - /// linear filter are not measured: its field stands alone; BC1 to BC3's unorm forms take it - /// beside their corner. No cube gather of a two-plane YCbCr format is measured: its field has + /// linear filter are not measured: its field stands alone, as the linear PVRTC formats' does; + /// BC1 to BC3's unorm forms and the 8-bit linear ETC2 and EAC formats take it beside their + /// corner. No cube gather of a two-plane YCbCr format is measured: its field has /// no corner. A packed normalized format's class is its normalized family's with `EXACT`, a /// small float's the half-float family's, each with its channels and border texels, and a /// two-plane format's the normalized family's with `EXACT` (signed where its field's steps are) @@ -1154,7 +1241,12 @@ mod tests { let two_plane = crate::metal::format::ycbcr_format(pf).is_some(); let blocks = matches!( pf, - PixelFormat::BC1RGBA | PixelFormat::BC2RGBA | PixelFormat::BC3RGBA + PixelFormat::BC1RGBA + | PixelFormat::BC2RGBA + | PixelFormat::BC3RGBA + | PixelFormat::ETC2RGB8 + | PixelFormat::ETC2RGB8A1 + | PixelFormat::EACRGBA8 ); assert_eq!( CubeCorner::of(pf).is_some(), diff --git a/crates/metal2vulkan/src/tests/engine_graphics_binder.rs b/crates/metal2vulkan/src/tests/engine_graphics_binder.rs index 0ccc11bca..c7065bc74 100644 --- a/crates/metal2vulkan/src/tests/engine_graphics_binder.rs +++ b/crates/metal2vulkan/src/tests/engine_graphics_binder.rs @@ -1680,8 +1680,8 @@ fn sampled_textures_and_runtime_samplers() { assert!(planned >= 3, "sample_level planned on {planned} profiles"); } -/// A texture of a format the table holds no representation of (`PVRTC_RGB_4BPP`, whose blocks the -/// runtime holds for copies alone) is refused with the format's refusal only at a slot its +/// A texture of a format the table holds no representation of (`ASTC_4x2_HDR`, whose footprint no +/// Vulkan block has) is refused with the format's refusal only at a slot its /// function uses: at a sampled slot the plan is `Unsupported(Format)`, and bound at an index the /// function does not declare, or at an argument the function declares and never reads /// (`reflection/textures`'s `unused_tex`, `air.arg_unused`), the plan is the one without it. @@ -1704,7 +1704,7 @@ fn a_texture_without_a_representation_is_refused_only_where_its_function_reads_i ) else { return; }; - let pvrtc = || texture(TextureType::Type2D, PixelFormat::PVRTCRGB4BPP); + let unheld = || texture(TextureType::Type2D, PixelFormat::ASTC4x2HDR); let rgba = || texture(TextureType::Type2D, PixelFormat::RGBA8Unorm); let linear = || sampler(true, SamplerReductionMode::WeightedAverage); let refused = |r: &Result| matches!(r, Err(BindError::Unsupported(u)) if u.feature == Feature::Format); @@ -1713,9 +1713,9 @@ fn a_texture_without_a_representation_is_refused_only_where_its_function_reads_i if let Ok(p) = kernel(&dev, &sampling, "sample_level") { let r = p.plan( &dev, - &kernel_state(&[(0, pvrtc())], &[(0, linear())], true).shape(), + &kernel_state(&[(0, unheld())], &[(0, linear())], true).shape(), ); - assert!(refused(&r), "{stem}: a sampled PVRTC texture: {r:?}"); + assert!(refused(&r), "{stem}: a sampled unheld texture: {r:?}"); let plain = p .plan( &dev, @@ -1725,9 +1725,11 @@ fn a_texture_without_a_representation_is_refused_only_where_its_function_reads_i let beside = p .plan( &dev, - &kernel_state(&[(0, rgba()), (5, pvrtc())], &[(0, linear())], true).shape(), + &kernel_state(&[(0, rgba()), (5, unheld())], &[(0, linear())], true).shape(), ) - .unwrap_or_else(|e| panic!("{stem}: a PVRTC texture at an undeclared index: {e}")); + .unwrap_or_else(|e| { + panic!("{stem}: an unheld texture at an undeclared index: {e}") + }); assert_eq!(beside.descriptors, plain.descriptors, "{stem}"); assert!(beside.diagnostics.is_empty(), "{stem}"); sampled += 1; @@ -1736,9 +1738,11 @@ fn a_texture_without_a_representation_is_refused_only_where_its_function_reads_i let unused = p .plan( &dev, - &kernel_state(&[(16, pvrtc())], &[(0, linear())], true).shape(), + &kernel_state(&[(16, unheld())], &[(0, linear())], true).shape(), ) - .unwrap_or_else(|e| panic!("{stem}: a PVRTC texture at the unread argument: {e}")); + .unwrap_or_else(|e| { + panic!("{stem}: an unheld texture at the unread argument: {e}") + }); let none = p .plan(&dev, &kernel_state(&[], &[(0, linear())], true).shape()) .unwrap_or_else(|e| panic!("{stem}: {e}")); @@ -1746,11 +1750,11 @@ fn a_texture_without_a_representation_is_refused_only_where_its_function_reads_i assert!(unused.diagnostics.is_empty(), "{stem}"); let read = p.plan( &dev, - &kernel_state(&[(3, pvrtc())], &[(0, linear())], true).shape(), + &kernel_state(&[(3, unheld())], &[(0, linear())], true).shape(), ); assert!( refused(&read), - "{stem}: a PVRTC texture at a sampled argument: {read:?}" + "{stem}: an unheld texture at a sampled argument: {read:?}" ); declared += 1; } @@ -2544,9 +2548,8 @@ fn a_written_sparse_texture_binds() { /// A 4:2:2 texture (`GBGR422`, `BGRG422`) at a storage slot its function only writes /// (`storage_texture_write`) binds the slot's neutral with an `IncompatibleBinding` note: plain -/// Metal completes the writes and stores nothing (EVs CFR-probe8-m4, RRP-probe11-m4). At a slot -/// that samples it (`sampling`'s `sample_level`) the plan is the format's refusal, -/// `Unsupported(Format)` (Metal decodes the pairs). +/// `sample_level`) the plan samples the decoded twin's view of Metal's texels, `R8G8B8A8_UNORM` +/// (`FormatEmulation::Decoded`). #[test] fn a_four_two_two_texture_a_function_only_writes_binds_the_neutral() { let (Some(write), Some(sampling)) = (fixture("storage_texture_write"), fixture("sampling")) @@ -2554,7 +2557,17 @@ fn a_four_two_two_texture_a_function_only_writes_binds_the_neutral() { return; }; let linear = || sampler(true, SamplerReductionMode::WeightedAverage); - let refused = |r: &Result| matches!(r, Err(BindError::Unsupported(u)) if u.feature == Feature::Format); + let twin_view = |plan: &BindingPlan| { + plan.descriptors.iter().any(|d| { + matches!( + &d.source, + WriteSource::CombinedImageSampler { + image: ImageSource::Texture { view, .. }, + .. + } if view.format == vk::Format::R8G8B8A8_UNORM + ) + }) + }; let (mut written, mut sampled) = (0, 0); for (stem, dev) in devices() { for pf in [PixelFormat::GBGR422, PixelFormat::BGRG422] { @@ -2589,11 +2602,13 @@ fn a_four_two_two_texture_a_function_only_writes_binds_the_neutral() { written += 1; } if let Ok(p) = kernel(&dev, &sampling, "sample_level") { - let r = p.plan( - &dev, - &kernel_state(&[(0, pairs())], &[(0, linear())], true).shape(), - ); - assert!(refused(&r), "{stem} {pf:?}: a sampled 4:2:2 texture: {r:?}"); + let plan = p + .plan( + &dev, + &kernel_state(&[(0, pairs())], &[(0, linear())], true).shape(), + ) + .unwrap_or_else(|e| panic!("{stem} {pf:?}: a sampled 4:2:2 texture: {e}")); + assert!(twin_view(&plan), "{stem} {pf:?}: {:?}", plan.descriptors); sampled += 1; } } diff --git a/crates/metal2vulkan/src/tests/engine_srgb_raw.rs b/crates/metal2vulkan/src/tests/engine_srgb_raw.rs index 8e25025d8..160879bea 100644 --- a/crates/metal2vulkan/src/tests/engine_srgb_raw.rs +++ b/crates/metal2vulkan/src/tests/engine_srgb_raw.rs @@ -1496,6 +1496,69 @@ fn a_slot_bound_in_srgb_joins_the_variant_and_binds_its_raw_view() { ); } +/// A slot bound in an ASTC sRGB format joins the variant exactly where the device holds the +/// format's decoded twin (no ASTC block, `metal::texel_format::srgb_raw_on`): its raw binding +/// views the twin's codes as `R8G8B8A8_UNORM`, its own binding as `R8G8B8A8_SRGB`. A device with +/// the block (ANV, MoltenVK) decodes the texture itself: no variant, and its own view the block's. +#[test] +fn an_astc_srgb_slot_reads_raw_codes_only_where_its_twin_holds_them() { + let Some(bc) = assemble("astc read", &kernel(Access::Read, true)) else { + return; + }; + let (mut twinned, mut native) = (0, 0); + for (stem, dev) in devices() { + let plain = pipeline(&dev, &bc, &inputs(false)); + for pf in [PixelFormat::ASTC4x4SRGB, PixelFormat::ASTC12x10SRGB] { + let what = format!("{stem} {pf:?}"); + let sampled = crate::metal::format::vk_format( + pf, + &[FormatUsage::SampledImage].into(), + dev.profile(), + ) + .unwrap_or_else(|e| panic!("{what}: {e}")); + let shape = state(Some(pf)).shape(); + let plan = plain.plan(&dev, &shape).expect(&what); + let decoded = sampled.emulation == crate::metal::format::FormatEmulation::Decoded; + assert_eq!( + crate::metal::texel_format::srgb_raw_on(pf, dev.profile()), + decoded, + "{what}" + ); + if !decoded { + assert!(plan.variant.srgb_textures.is_empty(), "{what}"); + let (_, own) = views(&plain, &plan); + for o in own.iter().filter_map(view_of) { + assert_eq!(o.format, sampled.format, "{what}"); + } + native += 1; + continue; + } + assert_eq!( + plan.variant.srgb_textures, + BTreeSet::from([TEXTURE]), + "{what}" + ); + let key = plan.variant.lowering_inputs(Stage::Kernel); + let variant = pipeline(&dev, &bc, &key); + let again = variant.plan(&dev, &shape).expect("variant plan"); + assert_eq!(again.variant, plan.variant, "{what}"); + let (raw, own) = views(&variant, &again); + let raw: Vec<_> = raw.iter().filter_map(view_of).collect(); + assert_eq!(raw.len(), 1, "{what}: {raw:?}"); + assert_eq!(raw[0].format, crate::vk::Format::R8G8B8A8_UNORM, "{what}"); + for o in own.iter().filter_map(view_of) { + assert_eq!(o.format, crate::vk::Format::R8G8B8A8_SRGB, "{what}"); + } + twinned += 1; + } + } + assert!(twinned > 0, "no committed profile holds an ASTC sRGB twin"); + assert!( + native > 0, + "no committed profile samples an ASTC sRGB block" + ); +} + /// A `half` sample the device decodes and filters under the variant (a linear one with a linear /// mip filter, which the raw view does not serve) converts the device's `f32` texel by the bound /// format's class, the conversion's `OTHER` arm for an 8-bit sRGB format. On MoltenVK, whose diff --git a/crates/metal2vulkan/src/tests/fast_paths.rs b/crates/metal2vulkan/src/tests/fast_paths.rs index a854d9241..e11929abe 100644 --- a/crates/metal2vulkan/src/tests/fast_paths.rs +++ b/crates/metal2vulkan/src/tests/fast_paths.rs @@ -69,8 +69,7 @@ fn choices() -> Vec { nan_and_min_max: _, rounding_order: _, half_blend: _, - // The runtime's: whether a texture over padded rows that only reads aliases them. - padded_reads: _, + decoded_texels: _, } = p; vec![ choice!(p.framebuffer_fetch: FramebufferFetchPolicy { RequireOrdered, AcceptUnordered }), @@ -83,7 +82,7 @@ fn choices() -> Vec { choice!(p.nan_and_min_max: NanMinMaxPolicy { Native, Exact }), choice!(p.rounding_order: RoundingOrderPolicy { Native, Exact }), choice!(p.half_blend: HalfBlendPolicy { Device, Exact }), - choice!(p.padded_reads: PaddedReadsPolicy { Alias, Shadow }), + choice!(p.decoded_texels: DecodedTexelsPolicy { Compact, Exact }), ] } @@ -395,6 +394,20 @@ fn the_runtime_s_padded_reads_choice_keys_no_profile() { assert_eq!(alias.len(), shadow.len()); for ((stem, a), (other, s)) in alias.iter().zip(&shadow) { assert_eq!(stem, other); - assert_eq!(a.fingerprint(), s.fingerprint(), "{stem}"); +/// The runtime's choice of a carried texture's decoded twin (`decoded_texels`) moves no committed +/// profile's fingerprint: no profile carries it, so no translation follows it. +#[test] +fn the_runtime_s_decoded_texels_choice_keys_no_profile() { + use crate::spirv::testing::committed_profiles_with; + let codes = committed_profiles_with(DevicePolicy::UNTRUSTED).expect("profiles"); + let exact = committed_profiles_with(DevicePolicy { + decoded_texels: DecodedTexelsPolicy::Exact, + ..DevicePolicy::UNTRUSTED + }) + .expect("profiles"); + assert_eq!(codes.len(), exact.len()); + for ((stem, a), (other, e)) in codes.iter().zip(&exact) { + assert_eq!(stem, other); + assert_eq!(a.fingerprint(), e.fingerprint(), "{stem}"); } } diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index fe4ad2a08..171aa3d0c 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -229,7 +229,7 @@ surface! { enum NanMinMaxPolicy N; enum RoundingOrderPolicy N; enum HalfBlendPolicy N; - enum PaddedReadsPolicy N; + enum DecodedTexelsPolicy N; struct DeviceProfile O; struct SpirvValidation N; struct EnabledCaps N; @@ -628,6 +628,16 @@ surface! { fn block_decode_module; enum BlockDecode N; struct BlockDecodeModule N; + fn astc_decode_module; + struct AstcDecode N; + enum AstcTexels N; + fn pvrtc_decode_module; + struct PvrtcDecode N; + fn etc_decode_module; + enum EtcDecode N; + enum EtcTexels N; + fn chroma_decode_module; + enum ChromaDecode N; fn mesh_scan_module; struct MeshScanModule N; fn tessellation_scan_module; diff --git a/docs/API.md b/docs/API.md index 8690f8c3e..756207658 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1797,6 +1797,39 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. the decoded twin on the host or the staging queue: the first command buffer that may read the texture waits at its submission for that, and the call waits for it where a command buffer that may read the texture is submitted and not yet complete, or the texture is untracked. +- `metal2vulkan-degrade-carried-decoded-twin` (performance). `CarriedDecodedTwin`: A texture of an ASTC + LDR format (`ASTC_4x4_LDR` to `ASTC_12x12_LDR`, the sRGB forms too) made on a device without that + ASTC format, of a PVRTC format on a device without it (every device but MoltenVK's, and there + the four RGB formats), or of an ETC2 or EAC format on a device without them (desktop GPUs and + lavapipe): its blocks lie in an image of a carrier format whose blocks are also 16 (ASTC, + `EAC_RGBA8`, `RG11`) or 8 (PVRTC, the other ETC2 and EAC formats) bytes, which copies and + `get_bytes` move unchanged, and its samples read a decoded twin, Metal's decode of the blocks in + the texels `DecodedTexelsPolicy` names (a PVRTC texture's, and an 8-bit ETC2 or EAC texture's, + 8-bit codes, exact under either: its sRGB form's slots decode them through Metal's table, and one + twin serves the views of the linear and sRGB forms; an ASTC sRGB texture's, its own 8-bit codes, + read the same way), decoded after each write into it as a BC + texture's twin is (`decoded-block-twin`; a PVRTC texture's whole levels, since each texel's + colors come from the blocks around it). An ASTC texture's first view in its other colour + space (its sRGB form as LDR, or the other way) gives it a second twin of that form's decode, kept + in step by GPU passes its command buffers' submissions record. Also a texture of a 4:2:2 format + (`GBGR422`, `BGRG422`) on every device, whose Vulkan formats reconstruct chroma by the + implementation's rules: its texels' bytes lie in an `R8G8_UNORM` carrier, and its twin holds + Metal's texels as 8-bit codes, exact (each texel's own green, its red and blue interpolated with + the pair beside it), decoded in whole rows. Cost: a carrier image of its + blocks, at most about 1 byte a texel (a 4:2:2 texture's 2), and a decoded twin of 4 bytes a texel (R8G8B8A8, + `DecodedTexelsPolicy::Compact`; an EAC 11-bit texture's 16-bit codes, 2 bytes a channel) or 16 + (R32G32B32A32_SFLOAT, `DecodedTexelsPolicy::Exact`; an EAC 11-bit texture's floats, 4 bytes a + channel), two for an ASTC texture viewed in both colour spaces, and a decode after each write into it: a pass on + the GPU for a blit, a copy from a texture or a CPU copy through a submission; on the CPU, on the + device's decode thread, where its CPU copies go on the host or the staging queue. +- `metal2vulkan-degrade-decoded-texel-precision` (precision). `DecodedTexelPrecision`: A texture with an + ASTC LDR decoded twin of 8-bit codes, or an EAC 11-bit one (`R11`, `RG11`) of 16-bit normalized + codes, under `DecodedTexelsPolicy::Compact`. Cost: a read, sample or gather of its texels answers + the nearest 8-bit code to Metal's 12-bit value, at most 1/510 off it; an EAC 11-bit texture's, + the nearest 16-bit normalized code to Metal's `c / 2047` (signed `c / 1023`), at most half a + 16-bit step off it. `DecodedTexelsPolicy::Exact` holds Metal's values instead. An ASTC sRGB + texture's twin holds Metal's own 8-bit codes, which its slots decode through Metal's table: + exact, under either. - `metal2vulkan-degrade-shared-present-queue` (performance). `SharedPresentQueue`: A command queue made for presenting (`Device::new_command_queue_for_presenting`) on a device that reserved no `VkQueue` for presenting: its queue family has no queue past the ones the round robin takes diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index ec1102e10..c61f6ed06 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -45,6 +45,7 @@ a cell that names another source took its numbers there. | A computed `half` or `float` color blended into an extended-range attachment (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`) rounds the blend's source as a loaded one; Metal's compiler rounds it by how it computed it. Every device. | The in-shader blend's loaded rounding (no switch) | **Not built yet:** Metal's rounding per shape is probed, not modelled | One code. `ExtendedRangeBlendSource` (`extended-range-blend-source`), `ExtendedRangeFloatBlendSource` (`extended-range-float-blend-source`) | Not measured | | A bicubic sample of an 8- or 16-bit normalized texture sums its taps exactly and rounds half up; Metal truncates its row terms, row sums and column terms first. Every device. | The exact sum (no switch) | **Not built yet:** Metal's datapath is pinned (17.75M lanes measured, no miss); its emitter is not written | One grid step (1/4080 at 8 bits) within about 2^-21 of a tie. `BicubicFilterArithmetic` (`bicubic-filter-arithmetic`) | Not measured (Metal's form is expected no larger) | | A bicubic sample of an extended-range texture (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10` and their sRGB twins) sums its taps' steps exactly, rounds half up and clamps into the format's decoded endpoints; within 0.014 of a grid step of a rounding tie Metal may round the other way. Every device. | The exact sum (no switch) | **None known:** no model of Metal's datapath tried fits; 3,317,760 lanes measured on the M3 Max (macOS 26.7) | One grid step (1/8160 a color lane, 1/8192 an sRGB color lane, 1/4080 alpha), 4,050 of the lanes measured, each within 0.014 of a step of a tie. `BicubicFilterArithmetic` (`bicubic-filter-arithmetic`) | No accurate form | +| A texture of an ASTC LDR format on a device without that ASTC format reads a decoded twin of 8-bit codes, each channel the code nearest Metal's 12-bit value (`C >> 4` over 4095). (An sRGB form's twin holds Metal's own 8-bit codes under either value, which its slots decode through Metal's table: exact.) A texture of an EAC 11-bit format (`R11`, `RG11`, unsigned and signed) on a device without ETC2 reads one of 16-bit normalized codes, each nearest Metal's value (`c / 2047`, signed `c / 1023`). The runtime's choice: no pipeline differs. | `decoded_texels = DecodedTexelsPolicy::Compact` | `decoded_texels = DecodedTexelsPolicy::Exact`: Metal's values in an `R32G32B32A32_SFLOAT` twin (an EAC 11-bit one's in `R32_SFLOAT` or `R32G32_SFLOAT`) | Within 1/510 of Metal's value. An EAC 11-bit channel within half a 16-bit step (1/131070, signed 1/65534). `decoded-texel-precision`, announced where such a texture is made; `runtime_lane::astc_textures`, `runtime_lane::etc_textures` | The twin's memory, 16 bytes a texel against 4 (a 2048 x 2048 texture's chain: 85 MiB against 21 MiB), and as much again for a second twin once the texture is viewed in its other colour space; an EAC 11-bit twin's 4 bytes a channel against 2. The CPU decode of that chain of 8 x 8 blocks on one core of the Iris Xe host: 79 ms against 68 ms. Sampling not measured | All at once: `DevicePolicy::exact_answers()` sets every switch above but sampling's (validation adds `sampling = SamplingPolicy::Exact`). Against master 1ee783c77 it cost A2X 0.99-1.04 → 17.5 s, @@ -177,9 +178,16 @@ recorded here. Open differences from Metal that no note announces yet, and runtime costs still above the driver's. Each is open work. -- **A mesh or tile render pipeline past ANV's compiler word bound.** Its stages are not fitted to - the bound as a vertex and fragment pipeline's are, so under the exact forms ANV's compiler can - fault on it. +- **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 + heap's over the caller's host pages or laid out apart from its bytes) holds its blocks for copies + alone: a command that reads it is refused. +- **ETC2 and EAC textures on a device without them.** A sparse heap's such texture + (`RuntimeGap::DecodedHeapTexture`) and a view of another decode (an EAC 11-bit format's other + signedness) are refused; one without a decoded twin (a heap's over the caller's host pages or + laid out apart from its bytes) holds its blocks for copies alone, and a command that reads it is + refused. - **A level the device's arithmetic chooses.** Off MoltenVK under exact sampling, a fragment's implicit-level sample (its bias Metal's `B` within the device's limit), a sample with explicit gradients and a fragment's LOD query take the device's level of detail, where Metal's is not diff --git a/scripts/refusal-surface/reach.tsv b/scripts/refusal-surface/reach.tsv index 5b635855b..8db067d2f 100644 --- a/scripts/refusal-surface/reach.tsv +++ b/scripts/refusal-surface/reach.tsv @@ -174,6 +174,7 @@ gap DetachedTexelAccess none CPU texel access while a runtime extension detached gap TextureBufferLevels rare a texture buffer of more than one level (public, unusual) gap WriteSwizzle none Apple-private writeSwizzleEnabled with a swizzle that writes gap PvrtcBlockOrder rare PVRTC regions off whole levels +gap DecodedHeapTexture app an ASTC texture in a heap on a device without ASTC gap VertexFetchPast4GiB rare vertex fetch past 4 GiB of a bind offset gap StageInFetchPast4GiB rare stage-in fetch past 4 GiB of a bind offset apple ProtectedContent none Apple-private (no public header)