A read through a sampler (MSL 4.1's read(sampler, coord)) of a texture buffer took the texture's own view alone, and where the device held the bound format as words the runtime refused the draw or dispatch (Gap::TexelBufferOwnView). The words now build it: the site reads the sampler's state (through::state), addresses the index against the words' width the way the own view's read addresses it against its size (through::buffer_index, which address() now calls for a texture buffer: the first texel outside, the nearest where a runtime slot sampler's s mode is clamp_to_edge, the border where the t mode is clamp_to_zero or clamp_to_border), calls the read routine at the addressed index, and where it reads the border hands back the border texel of the format the word's code names (words::border_texels), the alpha 1 of a format without alpha included. Such a read no longer records RuntimeFact::TexelBufferOwnView; the remaining own-view accesses are a read that observes residency, a read or write of another numeric class, a read of an sRGB texture's codes and a write of fewer than four lanes. The site's word estimate adds the sampler's addressing again and THROUGH_WORDS (the view's size, the width, the border texels by code). Tests: engine_identity's read-through test now asserts no own-view fact and a words routine where the profile holds formats as words. The runtime test reads rt_buffer (mirrored_repeat), rt_buffer_ow (clamp_to_border, opaque white) and rt_arg_buffer through three runtime sampler states (clamp_to_edge; t clamp_to_zero; t clamp_to_border opaque black) over six formats in either form, against Metal's texel in bounds and outside. Docs: words.rs module docs, the fact's and the gap's docs and Display, the runtime README's known gap, RESOURCE-ID.md; REFUSALS.md regenerated. Verified at the hand-over tip 355c902082, with (b), on development8a2acc84fb: clippy in the three configurations and the translator's tests (gate m3-max-82186; the read-through and words tests 120 passed, m3-max-82186's focused step); on lavapipe the runtime's texture buffer tests 13 passed and the stream test passed, and the runtime's whole suite 972 passed, 4 skipped; the read-through test over the three sampler states and six formats on an Iris Xe (m3-max-82187), an RTX 3090 (m3-max-82193) and an RX 7900 XTX and a 780M (RADV, m3-max-82282), each format in its form there (B5G6R5Unorm as words on the 3090, the XTX and the 780M); the read-through-buffer conformance replay on lavapipe, base8a2acc84fbagainst the tip, 0 of 1 cases differ (m3-max-82188).
1269 lines
56 KiB
Rust
1269 lines
56 KiB
Rust
//! Texture buffers of formats a device may hold as words, under a device cfg on every device of
|
|
//! the cfg's kind: `A8Unorm`, the four 8-bit sRGB formats, `RGB9E5Float`, the four packed 16-bit
|
|
//! formats, `BGR10A2Unorm` and the four extended-range formats. Metal makes a texture buffer of
|
|
//! each, for reading, writing and both (an Apple M3 Max under macOS 27.0.1, jobs m3-max-79872 and
|
|
//! m3-max-79879). Each device holds each as words or as its own view
|
|
//! (`metal::format::texel_buffer_form`), which each format's line names.
|
|
//!
|
|
//! The owned fixture `tb_word_formats` reads, writes, and reads then writes (`access::read_write`)
|
|
//! texture buffers of five texels, one format at a time, with eight threads: thread `t` reads
|
|
//! texel `t`, writes the value whose code is texel `t`'s, and asks the widths. Each answer is
|
|
//! checked against the CPU's decode of the texels' bytes, and each written texture buffer's bytes
|
|
//! against the codes:
|
|
//!
|
|
//! - in bounds, a read is the texel's value: exact where the format's decode is exact in `f32`,
|
|
//! within one `f32` ulp for an extended-range format's (`PrecisionNote::DevicePackConversion`),
|
|
//! within the stated tolerance for the sRGB transfer, a normalized format held as its own view
|
|
//! within `PrecisionNote::DeviceTexelConversion`'s recorded bound (the device's conversion:
|
|
//! ANV widens a 5- or 6-bit field by replicating its bits), and a write stores the code whose
|
|
//! value it was given; neighbouring threads write neighbouring texels, which share a word where a
|
|
//! texel is smaller than one, and every one keeps its code;
|
|
//! - past the width (threads 5 to 7), a read is Metal's out-of-bounds texel (zero, with alpha 1
|
|
//! where the format has none) and a write changes nothing: the bytes after the fifth texel, the
|
|
//! rest of its word among them, keep theirs;
|
|
//! - each texture buffer's width is five.
|
|
//!
|
|
//! Its `tb_word_formats_args` then reads the read one and writes the written one again, through an
|
|
//! argument buffer's handles, under the same checks. The dispatch through slots runs the kernel's
|
|
//! words twin (`pipeline::Twins`) exactly where the device holds the format as words; the one
|
|
//! through handles runs it there too.
|
|
//!
|
|
//! A draw whose fragment function `tb_word_fragment` reads a texture buffer, of `R8Unorm` and of
|
|
//! `B5G6R5Unorm`, colours each pixel with the texel the CPU decodes, and runs the render content's
|
|
//! words twin exactly where the device holds the format as words. On a device with indirect
|
|
//! command buffers, that content's plain pipeline and its twin each size an execution's shape of
|
|
//! their own, and so do those of a content of patch draws (`icb_merged_patch_vertex` with
|
|
//! `tb_word_fragment`) where the device's executions run tessellation stages.
|
|
//!
|
|
//! `llvm-as` assembles the fixture; without it the test skips visibly.
|
|
|
|
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
|
|
mod on_device {
|
|
use crate::tests::command::on_device::{each_device, finished};
|
|
use crate::{
|
|
Buffer, ComputePipelineDescriptor, ComputePipelineState, Device, DispatchType,
|
|
FunctionDescriptor, IndexClass, Library, MemoryClass, PixelFormat, SamplerAddressMode,
|
|
SamplerBorderColor, SamplerDescriptor, SamplerState, StageSource, Texture,
|
|
TextureDescriptor, TextureType, TextureUsage,
|
|
};
|
|
use metal2vulkan::device::FormatUsage;
|
|
use metal2vulkan::metal::format as formats;
|
|
use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError};
|
|
|
|
/// The texels of each texture buffer.
|
|
const WIDTH: usize = 5;
|
|
/// The threads of the dispatch: the texels and three past them.
|
|
const THREADS: usize = 8;
|
|
/// What every byte outside the texture buffers' texels holds, before and after.
|
|
const SENTINEL: u8 = 0x5a;
|
|
/// Where the read, the written and the read-written texture buffers lie in the data buffer.
|
|
const PLACES: [u64; 3] = [1024, 2048, 3072];
|
|
/// The data buffer's bytes.
|
|
const DATA: u64 = 4096;
|
|
|
|
/// How a format's channels decode.
|
|
#[derive(Clone, Copy, Debug)]
|
|
enum Decode {
|
|
/// Exact in `f32`: the CPU's value is the device's, bit for bit.
|
|
Exact,
|
|
/// An extended-range code's value by the device's arithmetic
|
|
/// (`PrecisionNote::DevicePackConversion`): within one `f32` ulp of the CPU's.
|
|
Ulp,
|
|
/// Through the sRGB transfer: within `SRGB_TOLERANCE` of the CPU's value.
|
|
Srgb,
|
|
/// The device's own conversion of each normalized code, where it holds the format as its
|
|
/// own view (`PrecisionNote::DeviceTexelConversion`), of the red, green, blue and alpha
|
|
/// fields of these widths in bits: within that note's recorded bound of the CPU's value
|
|
/// (docs/API.md, the precision-note catalogue): one `f32` ulp, or, where the device widens
|
|
/// a field by replicating its bits, 0.18 of a code of a 5- or 6-bit field and 0.015 of a
|
|
/// code of a 10-bit one.
|
|
Device([u8; 4]),
|
|
}
|
|
|
|
/// The largest difference taken from the CPU's decode of an sRGB transfer.
|
|
const SRGB_TOLERANCE: f32 = 1.0 / 4096.0;
|
|
|
|
/// One format under test: its texel's bytes, its five texels' bytes, whether it has alpha
|
|
/// (else alpha reads 1 out of bounds), and its CPU decode.
|
|
struct Case {
|
|
format: PixelFormat,
|
|
bytes: usize,
|
|
texels: Vec<u8>,
|
|
alpha: bool,
|
|
decode: Decode,
|
|
value: fn(&[u8]) -> [f64; 4],
|
|
}
|
|
|
|
/// The sRGB transfer's decode of `c` in `[0, 1]`, extended past 1 and mirrored below 0.
|
|
fn srgb(c: f64) -> f64 {
|
|
let m = c.abs();
|
|
let linear = if m <= 0.04045 {
|
|
m / 12.92
|
|
} else {
|
|
((m + 0.055) / 1.055).powf(2.4)
|
|
};
|
|
linear.copysign(c)
|
|
}
|
|
|
|
/// The sRGB decode of byte `i` of `b`.
|
|
fn srgb8(b: &[u8], i: usize) -> f64 {
|
|
srgb(f64::from(b[i]) / 255.0)
|
|
}
|
|
|
|
/// The unsigned normalized value of the `bits`-bit field at bit `at` of `word`.
|
|
fn unorm(word: u64, at: u32, bits: u32) -> f64 {
|
|
let max = (1u64 << bits) - 1;
|
|
((word >> at) & max) as f64 / max as f64
|
|
}
|
|
|
|
/// The extended-range value of the 10-bit code at bit `at` of `word`.
|
|
fn xr(word: u64, at: u32) -> f64 {
|
|
(((word >> at) & 0x3ff) as f64 - 384.0) / 510.0
|
|
}
|
|
|
|
/// The little-endian integer of `bytes`.
|
|
fn le(bytes: &[u8]) -> u64 {
|
|
bytes
|
|
.iter()
|
|
.rev()
|
|
.fold(0u64, |word, &b| (word << 8) | u64::from(b))
|
|
}
|
|
|
|
/// `bytes` of each little-endian word in `words`.
|
|
fn words_le(words: &[u64], bytes: usize) -> Vec<u8> {
|
|
words
|
|
.iter()
|
|
.flat_map(|w| w.to_le_bytes()[..bytes].to_vec())
|
|
.collect()
|
|
}
|
|
|
|
fn cases() -> Vec<Case> {
|
|
let rgb9e5 = |r: u64, g: u64, b: u64, e: u64| r | (g << 9) | (b << 18) | (e << 27);
|
|
let b5g6r5 = |r: u64, g: u64, b: u64| b | (g << 5) | (r << 11);
|
|
let a1bgr5 = |r: u64, g: u64, b: u64, a: u64| a | (b << 1) | (g << 6) | (r << 11);
|
|
let abgr4 = |r: u64, g: u64, b: u64, a: u64| a | (b << 4) | (g << 8) | (r << 12);
|
|
let bgr5a1 = |r: u64, g: u64, b: u64, a: u64| b | (g << 5) | (r << 10) | (a << 15);
|
|
let bgr10a2 = |r: u64, g: u64, b: u64, a: u64| b | (g << 10) | (r << 20) | (a << 30);
|
|
// Bits 30 and 31 are written as ones.
|
|
let bgr10xr = |r: u64, g: u64, b: u64| b | (g << 10) | (r << 20) | (3 << 30);
|
|
// Each code in its 16-bit field's top 10 bits; the low 6 are written as zeros.
|
|
let bgra10xr =
|
|
|r: u64, g: u64, b: u64, a: u64| (b << 6) | (g << 22) | (r << 38) | (a << 54);
|
|
let rgba8 = [
|
|
[0u8, 255, 51, 128],
|
|
[200, 7, 99, 180],
|
|
[255, 255, 255, 255],
|
|
[1, 2, 3, 4],
|
|
[128, 64, 32, 16],
|
|
];
|
|
let xr_codes = [
|
|
(384, 894, 0),
|
|
(1023, 511, 640),
|
|
(100, 384, 894),
|
|
(700, 300, 450),
|
|
(894, 0, 1023),
|
|
];
|
|
vec![
|
|
Case {
|
|
format: PixelFormat::A8Unorm,
|
|
bytes: 1,
|
|
texels: vec![0, 255, 51, 128, 7],
|
|
alpha: true,
|
|
decode: Decode::Exact,
|
|
value: |b| [0.0, 0.0, 0.0, f64::from(b[0]) / 255.0],
|
|
},
|
|
Case {
|
|
format: PixelFormat::R8UnormSRGB,
|
|
bytes: 1,
|
|
texels: vec![0, 255, 51, 128, 200],
|
|
alpha: false,
|
|
decode: Decode::Srgb,
|
|
value: |b| [srgb(f64::from(b[0]) / 255.0), 0.0, 0.0, 1.0],
|
|
},
|
|
Case {
|
|
format: PixelFormat::RG8UnormSRGB,
|
|
bytes: 2,
|
|
texels: vec![0, 255, 51, 128, 200, 7, 255, 0, 99, 180],
|
|
alpha: false,
|
|
decode: Decode::Srgb,
|
|
value: |b| {
|
|
[
|
|
srgb(f64::from(b[0]) / 255.0),
|
|
srgb(f64::from(b[1]) / 255.0),
|
|
0.0,
|
|
1.0,
|
|
]
|
|
},
|
|
},
|
|
Case {
|
|
format: PixelFormat::RGBA8UnormSRGB,
|
|
bytes: 4,
|
|
texels: rgba8.concat(),
|
|
alpha: true,
|
|
decode: Decode::Srgb,
|
|
value: |b| {
|
|
[
|
|
srgb8(b, 0),
|
|
srgb8(b, 1),
|
|
srgb8(b, 2),
|
|
f64::from(b[3]) / 255.0,
|
|
]
|
|
},
|
|
},
|
|
Case {
|
|
format: PixelFormat::BGRA8UnormSRGB,
|
|
bytes: 4,
|
|
texels: rgba8.concat(),
|
|
alpha: true,
|
|
decode: Decode::Srgb,
|
|
value: |b| {
|
|
[
|
|
srgb8(b, 2),
|
|
srgb8(b, 1),
|
|
srgb8(b, 0),
|
|
f64::from(b[3]) / 255.0,
|
|
]
|
|
},
|
|
},
|
|
// Each texel's shared exponent is the one Metal's encode derives: its largest
|
|
// mantissa is 256 or more.
|
|
Case {
|
|
format: PixelFormat::RGB9E5Float,
|
|
bytes: 4,
|
|
texels: words_le(
|
|
&[
|
|
rgb9e5(300, 17, 511, 15),
|
|
rgb9e5(256, 0, 0, 1),
|
|
rgb9e5(0, 511, 128, 30),
|
|
rgb9e5(400, 400, 400, 20),
|
|
rgb9e5(511, 1, 2, 5),
|
|
],
|
|
4,
|
|
),
|
|
alpha: false,
|
|
decode: Decode::Exact,
|
|
value: |b| {
|
|
let w = le(b);
|
|
let scale = 2f64.powi(((w >> 27) & 31) as i32 - 24);
|
|
let m = |at: u32| ((w >> at) & 511) as f64 * scale;
|
|
[m(0), m(9), m(18), 1.0]
|
|
},
|
|
},
|
|
Case {
|
|
format: PixelFormat::B5G6R5Unorm,
|
|
bytes: 2,
|
|
texels: words_le(
|
|
&[
|
|
b5g6r5(31, 63, 31),
|
|
b5g6r5(0, 0, 0),
|
|
b5g6r5(16, 32, 8),
|
|
b5g6r5(1, 62, 30),
|
|
b5g6r5(10, 20, 5),
|
|
],
|
|
2,
|
|
),
|
|
alpha: false,
|
|
decode: Decode::Exact,
|
|
value: |b| {
|
|
let w = le(b);
|
|
[unorm(w, 11, 5), unorm(w, 5, 6), unorm(w, 0, 5), 1.0]
|
|
},
|
|
},
|
|
Case {
|
|
format: PixelFormat::A1BGR5Unorm,
|
|
bytes: 2,
|
|
texels: words_le(
|
|
&[
|
|
a1bgr5(31, 0, 15, 1),
|
|
a1bgr5(0, 31, 0, 0),
|
|
a1bgr5(16, 8, 4, 1),
|
|
a1bgr5(5, 10, 20, 0),
|
|
a1bgr5(1, 2, 3, 1),
|
|
],
|
|
2,
|
|
),
|
|
alpha: true,
|
|
decode: Decode::Exact,
|
|
value: |b| {
|
|
let w = le(b);
|
|
[
|
|
unorm(w, 11, 5),
|
|
unorm(w, 6, 5),
|
|
unorm(w, 1, 5),
|
|
unorm(w, 0, 1),
|
|
]
|
|
},
|
|
},
|
|
Case {
|
|
format: PixelFormat::ABGR4Unorm,
|
|
bytes: 2,
|
|
texels: words_le(
|
|
&[
|
|
abgr4(15, 0, 7, 3),
|
|
abgr4(0, 15, 8, 12),
|
|
abgr4(1, 2, 3, 4),
|
|
abgr4(9, 10, 11, 12),
|
|
abgr4(15, 15, 15, 15),
|
|
],
|
|
2,
|
|
),
|
|
alpha: true,
|
|
decode: Decode::Exact,
|
|
value: |b| {
|
|
let w = le(b);
|
|
[
|
|
unorm(w, 12, 4),
|
|
unorm(w, 8, 4),
|
|
unorm(w, 4, 4),
|
|
unorm(w, 0, 4),
|
|
]
|
|
},
|
|
},
|
|
Case {
|
|
format: PixelFormat::BGR5A1Unorm,
|
|
bytes: 2,
|
|
texels: words_le(
|
|
&[
|
|
bgr5a1(31, 0, 15, 1),
|
|
bgr5a1(0, 31, 0, 0),
|
|
bgr5a1(16, 8, 4, 1),
|
|
bgr5a1(5, 10, 20, 0),
|
|
bgr5a1(1, 2, 3, 1),
|
|
],
|
|
2,
|
|
),
|
|
alpha: true,
|
|
decode: Decode::Exact,
|
|
value: |b| {
|
|
let w = le(b);
|
|
[
|
|
unorm(w, 10, 5),
|
|
unorm(w, 5, 5),
|
|
unorm(w, 0, 5),
|
|
unorm(w, 15, 1),
|
|
]
|
|
},
|
|
},
|
|
Case {
|
|
format: PixelFormat::BGR10A2Unorm,
|
|
bytes: 4,
|
|
texels: words_le(
|
|
&[
|
|
bgr10a2(1023, 0, 511, 3),
|
|
bgr10a2(0, 1023, 1, 0),
|
|
bgr10a2(300, 600, 900, 1),
|
|
bgr10a2(5, 10, 20, 2),
|
|
bgr10a2(512, 256, 128, 3),
|
|
],
|
|
4,
|
|
),
|
|
alpha: true,
|
|
decode: Decode::Exact,
|
|
value: |b| {
|
|
let w = le(b);
|
|
[
|
|
unorm(w, 20, 10),
|
|
unorm(w, 10, 10),
|
|
unorm(w, 0, 10),
|
|
unorm(w, 30, 2),
|
|
]
|
|
},
|
|
},
|
|
Case {
|
|
format: PixelFormat::BGR10XR,
|
|
bytes: 4,
|
|
texels: words_le(&xr_codes.map(|(r, g, b)| bgr10xr(r, g, b)), 4),
|
|
alpha: false,
|
|
decode: Decode::Ulp,
|
|
value: |b| {
|
|
let w = le(b);
|
|
[xr(w, 20), xr(w, 10), xr(w, 0), 1.0]
|
|
},
|
|
},
|
|
Case {
|
|
format: PixelFormat::BGR10XRSRGB,
|
|
bytes: 4,
|
|
texels: words_le(&xr_codes.map(|(r, g, b)| bgr10xr(r, g, b)), 4),
|
|
alpha: false,
|
|
decode: Decode::Srgb,
|
|
value: |b| {
|
|
let w = le(b);
|
|
[srgb(xr(w, 20)), srgb(xr(w, 10)), srgb(xr(w, 0)), 1.0]
|
|
},
|
|
},
|
|
// Alpha codes within [384, 894], whose values Metal reads unclamped.
|
|
Case {
|
|
format: PixelFormat::BGRA10XR,
|
|
bytes: 8,
|
|
texels: words_le(
|
|
&xr_codes.map(|(r, g, b)| bgra10xr(r, g, b, 384 + (r % 511))),
|
|
8,
|
|
),
|
|
alpha: true,
|
|
decode: Decode::Ulp,
|
|
value: |b| {
|
|
let w = le(b);
|
|
[xr(w, 38), xr(w, 22), xr(w, 6), xr(w, 54)]
|
|
},
|
|
},
|
|
Case {
|
|
format: PixelFormat::BGRA10XRSRGB,
|
|
bytes: 8,
|
|
texels: words_le(
|
|
&xr_codes.map(|(r, g, b)| bgra10xr(r, g, b, 384 + (g % 511))),
|
|
8,
|
|
),
|
|
alpha: true,
|
|
decode: Decode::Srgb,
|
|
value: |b| {
|
|
let w = le(b);
|
|
[srgb(xr(w, 38)), srgb(xr(w, 22)), srgb(xr(w, 6)), xr(w, 54)]
|
|
},
|
|
},
|
|
]
|
|
}
|
|
|
|
/// The bytes of a Shared buffer, as the host reads them.
|
|
fn bytes(buffer: &Buffer) -> Vec<u8> {
|
|
let contents = buffer.contents().expect("a Shared buffer");
|
|
let len = usize::try_from(buffer.length()).expect("a length");
|
|
// SAFETY: the buffer is alive, Shared, of `len` bytes, and no work in flight writes it.
|
|
unsafe { std::slice::from_raw_parts(contents.cast::<u8>().as_ptr(), len) }.to_vec()
|
|
}
|
|
|
|
/// Writes `values` to a Shared buffer's bytes from byte `first`.
|
|
fn set_bytes(buffer: &Buffer, first: usize, values: &[u8]) {
|
|
let contents = buffer.contents().expect("a Shared buffer");
|
|
let len = usize::try_from(buffer.length()).expect("a length");
|
|
assert!(first + values.len() <= len, "bytes past the buffer");
|
|
// SAFETY: the buffer is alive, Shared, and holds the bytes; no work in flight reaches it.
|
|
let all = unsafe { std::slice::from_raw_parts_mut(contents.cast::<u8>().as_ptr(), len) };
|
|
all[first..first + values.len()].copy_from_slice(values);
|
|
}
|
|
|
|
/// The `f32` lanes of a Shared buffer, as the host reads them.
|
|
fn floats(buffer: &Buffer) -> Vec<f32> {
|
|
(bytes(buffer).as_chunks::<4>().0.iter())
|
|
.map(|&c| f32::from_le_bytes(c))
|
|
.collect()
|
|
}
|
|
|
|
/// One dispatch of `state` over `THREADS` threads in one threadgroup, with `textures` and
|
|
/// `buffers` at their slots, committed and finished.
|
|
fn dispatch(
|
|
device: &Device,
|
|
state: &ComputePipelineState,
|
|
textures: &[&Texture],
|
|
buffers: &[&Buffer],
|
|
sampler: Option<&SamplerState>,
|
|
) -> Result<(), crate::Error> {
|
|
let queue = device.new_command_queue(1).expect("a queue");
|
|
let command_buffer = queue.command_buffer().expect("a command buffer");
|
|
let mut encoder =
|
|
(command_buffer.compute_command_encoder(DispatchType::Serial)).expect("an encoder");
|
|
encoder
|
|
.set_compute_pipeline_state(state)
|
|
.expect("the state");
|
|
for (slot, texture) in (0..).zip(textures) {
|
|
encoder.set_texture(Some(texture), slot).expect("a texture");
|
|
}
|
|
for (slot, buffer) in (0..).zip(buffers) {
|
|
encoder.set_buffer(Some(buffer), 0, slot).expect("a buffer");
|
|
}
|
|
if let Some(sampler) = sampler {
|
|
encoder
|
|
.set_sampler_state(Some(sampler), 0)
|
|
.expect("a sampler");
|
|
}
|
|
let threads = u32::try_from(THREADS).expect("threads");
|
|
let dispatched = encoder.dispatch_threadgroups([1, 1, 1], [threads, 1, 1]);
|
|
encoder.end_encoding();
|
|
command_buffer.commit().expect("a commit");
|
|
finished("texture buffer words", &command_buffer);
|
|
assert_eq!(command_buffer.error(), None);
|
|
dispatched
|
|
}
|
|
|
|
/// The lanes `got` read against the CPU's `want`, by `decode`: None where they agree.
|
|
fn differs(got: &[f32], want: [f64; 4], decode: Decode) -> Option<String> {
|
|
let ulp = |g: f32, w: f64| (g.to_bits() as i64 - (w as f32).to_bits() as i64).abs() <= 1;
|
|
let agree = got
|
|
.iter()
|
|
.zip(want)
|
|
.enumerate()
|
|
.all(|(c, (&g, w))| match decode {
|
|
Decode::Exact => g.to_bits() == (w as f32).to_bits(),
|
|
Decode::Ulp => ulp(g, w),
|
|
Decode::Srgb => (g - w as f32).abs() <= SRGB_TOLERANCE,
|
|
Decode::Device(bits) => {
|
|
let codes = match bits[c] {
|
|
5 | 6 => 0.18,
|
|
10 => 0.015,
|
|
_ => 0.0,
|
|
};
|
|
let code = 1.0 / ((1u32 << bits[c]).max(2) - 1) as f32;
|
|
ulp(g, w) || (g - w as f32).abs() <= codes * code
|
|
}
|
|
});
|
|
(!agree).then(|| format!("read {got:?}, the CPU's {want:?}"))
|
|
}
|
|
|
|
/// How `case`'s texels decode on `device`: where it holds the format's texture buffers as the
|
|
/// format's own view, a normalized format's fields are the device's conversion
|
|
/// ([`Decode::Device`]); else, words decoding as the CPU does, the case's own.
|
|
fn decode_on(device: &Device, case: &Case) -> Decode {
|
|
let own = matches!(
|
|
formats::texel_buffer_form(case.format, device.translator().profile()),
|
|
Some(formats::TexelBufferForm::View(_))
|
|
);
|
|
let layout = formats::texel_words(case.format).map(|w| w.layout);
|
|
match (own, case.decode, layout) {
|
|
(
|
|
true,
|
|
Decode::Exact,
|
|
Some(formats::WordLayout::Fields {
|
|
fields,
|
|
kind: formats::FieldKind::Unorm,
|
|
}),
|
|
) => Decode::Device(fields.map(|f| f.map_or(0, |f| f.bits))),
|
|
_ => case.decode,
|
|
}
|
|
}
|
|
|
|
/// Whether `device` holds `format`'s texture buffers as the format's own view and that view's
|
|
/// format lacks a storage texel buffer read without a format
|
|
/// (`VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT`), which a read-written texture
|
|
/// buffer (`access::read_write`) reads through: the runtime refuses that access
|
|
/// ([`read_write_gap`]), the runtime README's known gap.
|
|
fn reads_none_without_format(device: &Device, format: PixelFormat) -> bool {
|
|
let profile = device.translator().profile();
|
|
match formats::texel_buffer_form(format, profile) {
|
|
Some(formats::TexelBufferForm::View(view)) => {
|
|
!profile.supports_format(view, FormatUsage::StorageTexelBufferReadWithoutFormat)
|
|
}
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
/// Whether `error` is the refusal of a read-written texture buffer of `format` at slot 2
|
|
/// whose own view reads none without a format.
|
|
fn read_write_gap(error: &crate::Error, format: PixelFormat) -> bool {
|
|
matches!(
|
|
error,
|
|
crate::Error::Unsupported(crate::Gap::StorageElement {
|
|
slot: Some(2),
|
|
pixel_format,
|
|
case: crate::StorageElementCase::ReadWithoutFormat,
|
|
..
|
|
}) if *pixel_format == format
|
|
)
|
|
}
|
|
|
|
/// Runs one format's case on `device`: what differs from the CPU's answers, or why the
|
|
/// runtime did not run it.
|
|
fn run(device: &Device, library: &Library, case: &Case) -> Vec<String> {
|
|
let mut wrong = Vec::new();
|
|
let block = (device.take_block(MemoryClass::Shared, 16 << 10)).expect("a block");
|
|
let place = |(at, len)| (device.new_buffer(block.id, at, len, Some(0))).expect("a buffer");
|
|
let data = place((0, DATA));
|
|
let values = place((4096, 256));
|
|
let reads = place((8192, 256));
|
|
let rw_reads = place((12288, 256));
|
|
let widths = place((12288 + 256, 16));
|
|
let len = WIDTH * case.bytes;
|
|
let texel = |texels: &[u8], t: usize| texels[t * case.bytes..(t + 1) * case.bytes].to_vec();
|
|
// The read-written texture buffer starts with the texels in reverse.
|
|
let reversed: Vec<u8> = (0..WIDTH)
|
|
.rev()
|
|
.flat_map(|t| texel(&case.texels, t))
|
|
.collect();
|
|
set_bytes(&data, 0, &[SENTINEL; DATA as usize]);
|
|
let [src_at, dst_at, rw_at] = PLACES.map(|at| usize::try_from(at).expect("a place"));
|
|
set_bytes(&data, src_at, &case.texels);
|
|
set_bytes(&data, rw_at, &reversed);
|
|
// Thread `t` writes the value of texel `t`'s code; past the width, an arbitrary one.
|
|
let mut lanes = Vec::new();
|
|
for t in 0..THREADS {
|
|
let value = match t < WIDTH {
|
|
true => (case.value)(&texel(&case.texels, t)),
|
|
false => [0.25, 0.5, 0.75, 1.0],
|
|
};
|
|
lanes.extend(value.map(|v| (v as f32).to_le_bytes()).concat());
|
|
}
|
|
set_bytes(&values, 0, &lanes);
|
|
set_bytes(&reads, 0, &[0; 256]);
|
|
set_bytes(&rw_reads, 0, &[0; 256]);
|
|
set_bytes(&widths, 0, &[0; 16]);
|
|
let make = |at: u64, usage| {
|
|
let mut d = TextureDescriptor::new(TextureType::TextureBuffer, case.format, 5, 1);
|
|
d.usage = usage;
|
|
let index = 1 + u32::try_from(at / 1024 - 1).expect("an index");
|
|
data.new_texture(&d, Some(index), at, 256)
|
|
};
|
|
let made = (
|
|
make(PLACES[0], TextureUsage::SHADER_READ),
|
|
make(PLACES[1], TextureUsage::SHADER_WRITE),
|
|
make(
|
|
PLACES[2],
|
|
TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE,
|
|
),
|
|
);
|
|
let (src, dst, rw) = match made {
|
|
(Ok(src), Ok(dst), Ok(rw)) => (src, dst, rw),
|
|
(src, dst, rw) => {
|
|
let why = [src.err(), dst.err(), rw.err()];
|
|
return vec![format!("not made: {why:?}")];
|
|
}
|
|
};
|
|
let function = library.function("tb_word_formats").expect("the kernel");
|
|
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(
|
|
FunctionDescriptor::new(function),
|
|
));
|
|
let state = match device.new_compute_pipeline_state(&descriptor, |s| Ok(vec![0; s.len()])) {
|
|
Ok(state) => state,
|
|
Err(error) => return vec![format!("no state: {error}")],
|
|
};
|
|
let counters = &device.core().counters;
|
|
let twins = counters.twin_runs();
|
|
let held = matches!(
|
|
formats::texel_buffer_form(case.format, device.translator().profile()),
|
|
Some(formats::TexelBufferForm::Words(_))
|
|
);
|
|
let out_of_bounds = [0.0, 0.0, 0.0, if case.alpha { 0.0 } else { 1.0 }];
|
|
// The read-written one (slot 2) is refused where the device's own view of the format reads
|
|
// none without a format (the runtime README's known gap); the handles' kernel below reads
|
|
// and writes the format all the same.
|
|
let refused = reads_none_without_format(device, case.format);
|
|
match dispatch(
|
|
device,
|
|
&state,
|
|
&[&src, &dst, &rw],
|
|
&[&values, &reads, &rw_reads, &widths],
|
|
None,
|
|
) {
|
|
Err(error) if refused && read_write_gap(&error, case.format) => {}
|
|
Err(error) => return vec![format!("not dispatched: {error}")],
|
|
Ok(()) if refused => wrong.push(
|
|
"the read-written one dispatched where its own view reads none without a format"
|
|
.to_owned(),
|
|
),
|
|
Ok(()) => {}
|
|
}
|
|
if !refused {
|
|
// The words twin runs where the device holds the format as words, the plain pipeline
|
|
// elsewhere.
|
|
let ran = counters.twin_runs() - twins;
|
|
if ran != u64::from(held) {
|
|
wrong.push(format!(
|
|
"{ran} dispatches ran the words twin, held as words: {held}"
|
|
));
|
|
}
|
|
let (reads, rw_reads) = (floats(&reads), floats(&rw_reads));
|
|
for t in 0..THREADS {
|
|
let (want, rw_want) = match t < WIDTH {
|
|
true => (
|
|
(case.value)(&texel(&case.texels, t)),
|
|
(case.value)(&texel(&reversed, t)),
|
|
),
|
|
false => (out_of_bounds, out_of_bounds),
|
|
};
|
|
let decode = if t < WIDTH {
|
|
decode_on(device, case)
|
|
} else {
|
|
Decode::Exact
|
|
};
|
|
if let Some(d) = differs(&reads[4 * t..4 * t + 4], want, decode) {
|
|
wrong.push(format!("texel {t} of the read one: {d}"));
|
|
}
|
|
if let Some(d) = differs(&rw_reads[4 * t..4 * t + 4], rw_want, decode) {
|
|
wrong.push(format!("texel {t} of the read-written one: {d}"));
|
|
}
|
|
}
|
|
let all = bytes(&data);
|
|
for (what, at, before) in [
|
|
("read", src_at, &case.texels),
|
|
("written", dst_at, &case.texels),
|
|
("read-written", rw_at, &case.texels),
|
|
] {
|
|
if all[at..at + len] != before[..] {
|
|
let got = &all[at..at + len];
|
|
wrong.push(format!(
|
|
"the {what} one's bytes {got:02x?}, the codes {before:02x?}"
|
|
));
|
|
}
|
|
// The rest of the last texel's word and what follows keep theirs.
|
|
if all[at + len..at + len + 64].iter().any(|&b| b != SENTINEL) {
|
|
let got = &all[at + len..at + len + 16];
|
|
wrong.push(format!("past the {what} one's texels: {got:02x?}"));
|
|
}
|
|
}
|
|
let widths = bytes(&widths);
|
|
let widths: Vec<u32> = (widths.as_chunks::<4>().0.iter().take(3))
|
|
.map(|&c| u32::from_le_bytes(c))
|
|
.collect();
|
|
if widths != [5, 5, 5] {
|
|
wrong.push(format!("widths {widths:?}"));
|
|
}
|
|
}
|
|
// Through an argument buffer's handles: the written one cleared first.
|
|
let args_reads = place((13312, 256));
|
|
let args_widths = place((13568, 16));
|
|
let ids: Vec<u8> = [&src, &dst]
|
|
.iter()
|
|
.flat_map(|t| t.gpu_resource_id().to_bits().to_le_bytes())
|
|
.collect();
|
|
let args = place((13824, 16));
|
|
set_bytes(&args, 0, &ids);
|
|
set_bytes(&args_reads, 0, &[0; 256]);
|
|
set_bytes(&args_widths, 0, &[0; 16]);
|
|
set_bytes(&data, dst_at, &vec![SENTINEL; len]);
|
|
let function = library
|
|
.function("tb_word_formats_args")
|
|
.expect("the kernel");
|
|
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(
|
|
FunctionDescriptor::new(function),
|
|
));
|
|
let state = match device.new_compute_pipeline_state(&descriptor, |s| Ok(vec![0; s.len()])) {
|
|
Ok(state) => state,
|
|
Err(error) => {
|
|
wrong.push(format!("no state of the handles' kernel: {error}"));
|
|
return wrong;
|
|
}
|
|
};
|
|
let twins = counters.twin_runs();
|
|
if let Err(error) = dispatch(
|
|
device,
|
|
&state,
|
|
&[],
|
|
// Slot 2 is unused by the kernel.
|
|
&[&values, &args_reads, &values, &args_widths, &args],
|
|
None,
|
|
) {
|
|
wrong.push(format!("not dispatched through handles: {error}"));
|
|
return wrong;
|
|
}
|
|
// A texture buffer held as words lives while this one dispatches, so it runs the twin.
|
|
let ran = counters.twin_runs() - twins;
|
|
if held && ran != 1 {
|
|
wrong.push(format!(
|
|
"{ran} dispatches through handles ran the words twin"
|
|
));
|
|
}
|
|
let args_reads = floats(&args_reads);
|
|
for t in 0..THREADS {
|
|
let (want, decode) = match t < WIDTH {
|
|
true => (
|
|
(case.value)(&texel(&case.texels, t)),
|
|
decode_on(device, case),
|
|
),
|
|
false => (out_of_bounds, Decode::Exact),
|
|
};
|
|
if let Some(d) = differs(&args_reads[4 * t..4 * t + 4], want, decode) {
|
|
wrong.push(format!("texel {t} read through a handle: {d}"));
|
|
}
|
|
}
|
|
let all = bytes(&data);
|
|
if all[dst_at..dst_at + len] != case.texels[..] {
|
|
let got = &all[dst_at..dst_at + len];
|
|
wrong.push(format!("written through a handle: {got:02x?}"));
|
|
}
|
|
if all[dst_at + len..dst_at + len + 64]
|
|
.iter()
|
|
.any(|&b| b != SENTINEL)
|
|
{
|
|
wrong.push("past the texels written through a handle".to_owned());
|
|
}
|
|
let args_widths = bytes(&args_widths);
|
|
let args_widths: Vec<u32> = (args_widths.as_chunks::<4>().0.iter().take(2))
|
|
.map(|&c| u32::from_le_bytes(c))
|
|
.collect();
|
|
if args_widths != [5, 5] {
|
|
wrong.push(format!("widths through handles {args_widths:?}"));
|
|
}
|
|
wrong
|
|
}
|
|
|
|
/// Every format a device may hold as words, read, written, and read then written as a
|
|
/// texture buffer, answers what the CPU decodes of its bytes, in the form the device holds it.
|
|
#[test]
|
|
fn every_device_reads_and_writes_texture_buffers_of_formats_held_as_words() {
|
|
let name = "tb_word_formats.ll";
|
|
let library = match llvm_assemble(&engine_dir().join(name)) {
|
|
Ok(bitcode) => Library::from_air(&bitcode).expect("the library"),
|
|
Err(AssembleError::Missing(why)) => {
|
|
eprintln!("SKIPPED: {why}");
|
|
return;
|
|
}
|
|
Err(error) => panic!("{name}: {error:?}"),
|
|
};
|
|
each_device("texture buffer words", |name, _, device| {
|
|
let _grant = (device.grant_indices(IndexClass::Texture, 1, 3))
|
|
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
|
let mut failed = Vec::new();
|
|
let profile = device.translator().profile();
|
|
for case in cases() {
|
|
let form = match formats::texel_buffer_form(case.format, profile) {
|
|
Some(formats::TexelBufferForm::Words(_)) => "words",
|
|
Some(formats::TexelBufferForm::View(_)) => "own view",
|
|
None => "refused",
|
|
};
|
|
let wrong = run(&device, &library, &case);
|
|
let refused = reads_none_without_format(&device, case.format);
|
|
match wrong.is_empty() {
|
|
true if refused => println!(
|
|
"{name}: {:?} ({form}): every answer the CPU's; read_write refused \
|
|
(Gap::StorageElement, ReadWithoutFormat), its own view reads none \
|
|
without a format",
|
|
case.format
|
|
),
|
|
true => println!("{name}: {:?} ({form}): every answer the CPU's", case.format),
|
|
false => {
|
|
for w in &wrong {
|
|
println!("{name}: {:?} ({form}): {w}", case.format);
|
|
}
|
|
failed.push(case.format);
|
|
}
|
|
}
|
|
}
|
|
assert!(failed.is_empty(), "{name}: formats that differ: {failed:?}");
|
|
});
|
|
}
|
|
|
|
/// The bytes of a texel of `format` whose channels (red, green, blue, alpha) are each 0 or
|
|
/// 1, for the formats [`a_read_through_a_sampler_refuses_a_texture_buffer_held_as_words`]
|
|
/// reads; the alpha of `B5G6R5Unorm`, which has none, reads 1.
|
|
fn ones_texel(format: PixelFormat, c: [bool; 4]) -> Vec<u8> {
|
|
let [r, g, b, a] = c;
|
|
let n = |on: bool, max: u32| if on { max } else { 0 };
|
|
match format {
|
|
PixelFormat::RGBA32Float => (c.iter())
|
|
.flat_map(|&on| (if on { 1.0f32 } else { 0.0 }).to_le_bytes())
|
|
.collect(),
|
|
PixelFormat::RGBA16Float => (c.iter())
|
|
.flat_map(|&on| n(on, 0x3c00).to_le_bytes()[..2].to_vec())
|
|
.collect(),
|
|
PixelFormat::RGBA16Unorm => (c.iter())
|
|
.flat_map(|&on| n(on, 0xffff).to_le_bytes()[..2].to_vec())
|
|
.collect(),
|
|
PixelFormat::RGBA8Unorm => c.iter().map(|&on| n(on, 255) as u8).collect(),
|
|
PixelFormat::BGRA8Unorm => [b, g, r, a].iter().map(|&on| n(on, 255) as u8).collect(),
|
|
PixelFormat::B5G6R5Unorm => {
|
|
let t = n(r, 31) << 11 | n(g, 63) << 5 | n(b, 31);
|
|
t.to_le_bytes()[..2].to_vec()
|
|
}
|
|
other => panic!("no texel of {other:?}"),
|
|
}
|
|
}
|
|
|
|
/// What a read through a sampler of a texture buffer reads at an index outside it (MSL 4.1;
|
|
/// the `read-through-buffer` conformance case's Metal answers): the first texel, the nearest
|
|
/// texel (a runtime sampler whose `s` address mode is `clamp_to_edge`), or the border texel of
|
|
/// a border color (the `t` axis's mode `clamp_to_zero` or `clamp_to_border`), each lane `[r,
|
|
/// g, b, a]`, the alpha 1 of a format without alpha.
|
|
#[derive(Clone, Copy)]
|
|
enum Outside {
|
|
First,
|
|
Nearest,
|
|
Border([bool; 4]),
|
|
}
|
|
|
|
/// `kernel_read_through`'s texture buffer reads through a sampler: `rt_buffer`
|
|
/// (`mirrored_repeat`), `rt_buffer_ow` (`clamp_to_border`, opaque white) and `rt_arg_buffer`
|
|
/// through the runtime sampler at `[[sampler(0)]]`: `clamp_to_edge` on every axis, `repeat`
|
|
/// on `s` with `clamp_to_zero` on `t`, and with `clamp_to_border` (opaque black) on `t`. Over
|
|
/// each of six formats of four channels or none missing but alpha, in whichever form the
|
|
/// device holds it, a dispatch reads each texel in bounds and Metal's texel past the width
|
|
/// ([`Outside`]): of formats without a word layout (`RGBA32Float`, `RGBA16Float`,
|
|
/// `RGBA8Unorm`), whose word holds their border texels, and of formats with one (`BGRA8Unorm`,
|
|
/// `RGBA16Unorm`, `B5G6R5Unorm`), whose word holds the layout's fields in their place and whose
|
|
/// border texels the function takes from the format's code; held as words, through the words,
|
|
/// addressed by the sampler's state against their width. Each line names the read and the
|
|
/// form; a device that holds none of the six as words prints that the words were not reached.
|
|
#[test]
|
|
fn a_read_through_a_sampler_reads_a_texture_buffer_as_metal_in_either_form() {
|
|
let name = "kernel_read_through.ll";
|
|
let library = match llvm_assemble(&engine_dir().join(name)) {
|
|
Ok(bitcode) => Library::from_air(&bitcode).expect("the library"),
|
|
Err(AssembleError::Missing(why)) => {
|
|
eprintln!("SKIPPED: {why}");
|
|
return;
|
|
}
|
|
Err(error) => panic!("{name}: {error:?}"),
|
|
};
|
|
const FORMATS: [PixelFormat; 6] = [
|
|
PixelFormat::RGBA32Float,
|
|
PixelFormat::RGBA16Float,
|
|
PixelFormat::RGBA8Unorm,
|
|
PixelFormat::BGRA8Unorm,
|
|
PixelFormat::RGBA16Unorm,
|
|
PixelFormat::B5G6R5Unorm,
|
|
];
|
|
use SamplerAddressMode as M;
|
|
let sampler = |s, t, border| {
|
|
let mut d = SamplerDescriptor::new();
|
|
(d.s_address_mode, d.t_address_mode, d.border_color) = (s, t, border);
|
|
Some(d)
|
|
};
|
|
let reads: [(&str, &str, Option<SamplerDescriptor>, Outside); 5] = [
|
|
("rt_buffer", "mirrored_repeat", None, Outside::First),
|
|
(
|
|
"rt_buffer_ow",
|
|
"clamp_to_border opaque white",
|
|
None,
|
|
Outside::Border([true; 4]),
|
|
),
|
|
(
|
|
"rt_arg_buffer",
|
|
"clamp_to_edge",
|
|
sampler(
|
|
M::ClampToEdge,
|
|
M::ClampToEdge,
|
|
SamplerBorderColor::TransparentBlack,
|
|
),
|
|
Outside::Nearest,
|
|
),
|
|
(
|
|
"rt_arg_buffer",
|
|
"repeat, t clamp_to_zero",
|
|
sampler(
|
|
M::Repeat,
|
|
M::ClampToZero,
|
|
SamplerBorderColor::TransparentBlack,
|
|
),
|
|
Outside::Border([false; 4]),
|
|
),
|
|
(
|
|
"rt_arg_buffer",
|
|
"repeat, t clamp_to_border opaque black",
|
|
sampler(
|
|
M::Repeat,
|
|
M::ClampToBorderColor,
|
|
SamplerBorderColor::OpaqueBlack,
|
|
),
|
|
Outside::Border([false, false, false, true]),
|
|
),
|
|
];
|
|
// Thread `t` reads index `AT[t]` of a texture buffer of 4 texels: texel `t` is channel
|
|
// `c` 1 where bit `c` of `t + 1` is set, never all four; past the width, `Outside`'s.
|
|
const AT: [i32; THREADS] = [0, 1, 2, 3, 4, -1, 7, 1000];
|
|
let texel_of = |t: usize| -> [bool; 4] { std::array::from_fn(|c| (t + 1) >> c & 1 == 1) };
|
|
each_device(
|
|
"texture buffer read through a sampler",
|
|
|name, _, device| {
|
|
let _grants = [
|
|
(IndexClass::Texture, FORMATS.len() as u32),
|
|
(IndexClass::Sampler, reads.len() as u32),
|
|
]
|
|
.map(|(class, n)| {
|
|
(device.grant_indices(class, 1, n))
|
|
.unwrap_or_else(|error| panic!("{name}: {error}"))
|
|
});
|
|
let block = (device.take_block(MemoryClass::Shared, 16 << 10)).expect("a block");
|
|
let place =
|
|
|(at, len)| (device.new_buffer(block.id, at, len, Some(0))).expect("a buffer");
|
|
let data = place((0, 4096));
|
|
let at = place((4096, 256));
|
|
let out = place((8192, 256));
|
|
let ats: Vec<u8> = (AT.iter())
|
|
.flat_map(|&x| [x, 0, 0, 0].map(i32::to_le_bytes).concat())
|
|
.collect();
|
|
set_bytes(&at, 0, &ats);
|
|
let profile = device.translator().profile();
|
|
let textures: Vec<(PixelFormat, &str, Texture)> = (FORMATS.into_iter())
|
|
.enumerate()
|
|
.map(|(k, format)| {
|
|
let words = matches!(
|
|
formats::texel_buffer_form(format, profile),
|
|
Some(formats::TexelBufferForm::Words(_))
|
|
);
|
|
let form = if words { "words" } else { "own view" };
|
|
let texels: Vec<u8> = (0..4)
|
|
.flat_map(|t| ones_texel(format, texel_of(t)))
|
|
.collect();
|
|
let offset = 512 * k;
|
|
set_bytes(&data, offset, &texels);
|
|
let mut d =
|
|
TextureDescriptor::new(TextureType::TextureBuffer, format, 4, 1);
|
|
d.usage = TextureUsage::SHADER_READ;
|
|
let index = 1 + u32::try_from(k).expect("an index");
|
|
let texture = (data.new_texture(&d, Some(index), offset as u64, 256))
|
|
.unwrap_or_else(|error| {
|
|
panic!("{name}: {format:?} ({form}) not made: {error}")
|
|
});
|
|
(format, form, texture)
|
|
})
|
|
.collect();
|
|
let mut failed = Vec::new();
|
|
for (r, (entry, mode, descriptor, outside)) in (1..).zip(&reads) {
|
|
let (entry, mode, outside) = (*entry, *mode, *outside);
|
|
let function = library.function(entry).expect("the kernel");
|
|
let pipeline = ComputePipelineDescriptor::new(StageSource::Function(
|
|
FunctionDescriptor::new(function),
|
|
));
|
|
let state = (device
|
|
.new_compute_pipeline_state(&pipeline, |s| Ok(vec![0; s.len()])))
|
|
.unwrap_or_else(|error| panic!("{name}: {entry}: no state: {error}"));
|
|
let sampler = descriptor.as_ref().map(|d| {
|
|
(device.new_sampler_state(d, r))
|
|
.unwrap_or_else(|error| panic!("{name}: {mode}: {error}"))
|
|
});
|
|
for (format, form, texture) in &textures {
|
|
let read = format!("{entry} ({mode}), {format:?} ({form})");
|
|
set_bytes(&out, 0, &[0; 256]);
|
|
let buffers = [&at, &out];
|
|
if let Err(error) =
|
|
dispatch(&device, &state, &[texture], &buffers, sampler.as_ref())
|
|
{
|
|
println!("{name}: {read}: {error}");
|
|
failed.push(read);
|
|
continue;
|
|
}
|
|
let alpha = *format == PixelFormat::B5G6R5Unorm;
|
|
let texel = |i: usize| {
|
|
let mut c = texel_of(i);
|
|
c[3] |= alpha;
|
|
c
|
|
};
|
|
let got = floats(&out);
|
|
let mut wrong = Vec::new();
|
|
for (t, &x) in AT.iter().enumerate() {
|
|
let want: [bool; 4] = match (usize::try_from(x), outside) {
|
|
(Ok(i), _) if i < 4 => texel(i),
|
|
(_, Outside::First) => texel(0),
|
|
(Ok(_), Outside::Nearest) => texel(3),
|
|
(Err(_), Outside::Nearest) => texel(0),
|
|
(_, Outside::Border(mut b)) => {
|
|
b[3] |= alpha;
|
|
b
|
|
}
|
|
};
|
|
let want = want.map(|on| if on { 1.0f32 } else { 0.0 });
|
|
if got[4 * t..4 * t + 4] != want {
|
|
wrong.push(format!(
|
|
"index {x}: {:?}, Metal {want:?}",
|
|
&got[4 * t..4 * t + 4]
|
|
));
|
|
}
|
|
}
|
|
match wrong.is_empty() {
|
|
true => println!("{name}: {read}: every texel and outside Metal's"),
|
|
false => {
|
|
println!("{name}: {read}: {wrong:?}");
|
|
failed.push(read);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if textures.iter().all(|(_, form, _)| *form != "words") {
|
|
println!(
|
|
"{name}: none of the formats is held as words: the words are not reached"
|
|
);
|
|
}
|
|
assert!(failed.is_empty(), "{name}: reads that differ: {failed:?}");
|
|
},
|
|
);
|
|
}
|
|
|
|
/// The colour a fragment reads of `texel`, of `R8Unorm` or of `B5G6R5Unorm` (red in bits 11
|
|
/// to 15, green in 5 to 10, blue in 0 to 4).
|
|
fn draw_colour(format: PixelFormat, texel: &[u8]) -> [f64; 4] {
|
|
match format {
|
|
PixelFormat::R8Unorm => [f64::from(texel[0]) / 255.0, 0.0, 0.0, 1.0],
|
|
_ => {
|
|
let t = u32::from(u16::from_le_bytes([texel[0], texel[1]]));
|
|
let field = |shift: u32, bits: u32| {
|
|
let max = (1u32 << bits) - 1;
|
|
f64::from(t >> shift & max) / f64::from(max)
|
|
};
|
|
[field(11, 5), field(5, 6), field(0, 5), 1.0]
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A draw whose fragment function reads a texture buffer colours each pixel with the texel
|
|
/// the CPU decodes, and runs the content's words twin exactly where the device holds the
|
|
/// format as words.
|
|
#[test]
|
|
fn draws_read_texture_buffers_through_the_twin_where_held_as_words() {
|
|
use crate::tests::draw::on_device::{
|
|
descriptor, examples, floats, library, pass, read, run, state, target, Buffers, SIDE,
|
|
};
|
|
use crate::PrimitiveType;
|
|
let (Some(examples), Some(words)) = (
|
|
examples(),
|
|
library(&engine_dir().join("tb_word_formats.ll")),
|
|
) else {
|
|
return;
|
|
};
|
|
let mut d = descriptor(&examples, "colored_fragment", PixelFormat::RGBA8Unorm);
|
|
d.fragment = Some(StageSource::Function(FunctionDescriptor::new(
|
|
words.function("tb_word_fragment").expect("the function"),
|
|
)));
|
|
let b5g6r5: Vec<u8> = [0x0000u16, 0xf800, 0x07e0, 0x001f, 0xffff]
|
|
.iter()
|
|
.flat_map(|t| t.to_le_bytes())
|
|
.collect();
|
|
let cases = [
|
|
(PixelFormat::R8Unorm, vec![0u8, 51, 102, 204, 255]),
|
|
(PixelFormat::B5G6R5Unorm, b5g6r5),
|
|
];
|
|
each_device("texture buffer words draw", |name, _, device| {
|
|
let _grant = (device.grant_indices(IndexClass::Texture, 1, 2))
|
|
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
|
let state = state(name, &device, &d);
|
|
let counters = &device.core().counters;
|
|
let mut buffers = Buffers::new(&device);
|
|
let positions = buffers.of(&device, &floats(&[-1.0, -1.0, 3.0, -1.0, -1.0, 3.0]));
|
|
let colors = buffers.of(&device, &floats(&[0.0; 12]));
|
|
for (index, (format, texels)) in (1..).zip(&cases) {
|
|
let held = matches!(
|
|
formats::texel_buffer_form(*format, device.translator().profile()),
|
|
Some(formats::TexelBufferForm::Words(_))
|
|
);
|
|
let data = buffers.of(&device, texels);
|
|
let mut td = TextureDescriptor::new(TextureType::TextureBuffer, *format, 5, 1);
|
|
td.usage = TextureUsage::SHADER_READ;
|
|
let texture = (data.new_texture(&td, Some(index), 0, 256))
|
|
.unwrap_or_else(|error| panic!("{name}: {format:?}: {error}"));
|
|
let color = target(
|
|
&device,
|
|
PixelFormat::RGBA8Unorm,
|
|
TextureUsage::RENDER_TARGET,
|
|
);
|
|
let queue = device.new_command_queue(4).expect("a queue");
|
|
let command_buffer = queue.command_buffer().expect("a command buffer");
|
|
let ok = |result: Result<(), crate::Error>| {
|
|
result.unwrap_or_else(|error| panic!("{name}: {format:?}: {error}"))
|
|
};
|
|
let twins = counters.twin_runs();
|
|
let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None)))
|
|
.unwrap_or_else(|error| panic!("{name}: {error}"));
|
|
ok(encoder.set_render_pipeline_state(&state));
|
|
ok(encoder.set_vertex_buffer(Some(&positions), 0, 0));
|
|
ok(encoder.set_vertex_buffer(Some(&colors), 0, 1));
|
|
ok(encoder.set_fragment_texture(Some(&texture), 0));
|
|
ok(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0));
|
|
encoder.end_encoding();
|
|
run(name, &command_buffer);
|
|
let ran = counters.twin_runs() - twins;
|
|
assert_eq!(
|
|
ran,
|
|
u64::from(held),
|
|
"{name}: {format:?}: draws that ran the words twin, held as words: {held}"
|
|
);
|
|
let pixels = read(&color, 4);
|
|
for (at, pixel) in pixels.as_chunks::<4>().0.iter().enumerate() {
|
|
let x = at % SIDE as usize % 5;
|
|
let want = draw_colour(
|
|
*format,
|
|
&texels[x * (texels.len() / 5)..][..texels.len() / 5],
|
|
);
|
|
let near = (pixel.iter().zip(want))
|
|
.all(|(&got, w)| (f64::from(got) - w * 255.0).abs() <= 1.0);
|
|
assert!(
|
|
near,
|
|
"{name}: {format:?}: pixel {at}: {pixel:?}, the CPU's {want:?}"
|
|
);
|
|
}
|
|
let form = if held { "words" } else { "own view" };
|
|
println!(
|
|
"texture buffer words draw: {name}: {format:?} ({form}): every pixel the CPU's"
|
|
);
|
|
}
|
|
});
|
|
}
|
|
|
|
/// An indirect command buffer's execution that runs a content's words twin sizes a shape of
|
|
/// its own: an execution's preprocess requirements are queried with the pipeline it binds
|
|
/// (`VUID-VkGeneratedCommandsInfoEXT-preprocessSize-11071`), and the twin is another pipeline
|
|
/// than the plain one under the same raster state. So for a content of plain draws, and, on a
|
|
/// device whose executions run tessellation stages, for one of patch draws
|
|
/// (`icb_merged_patch_vertex`, a post-tessellation vertex function), each under its layout.
|
|
#[test]
|
|
fn an_execution_through_the_twin_sizes_its_own_shape() {
|
|
use crate::indirect::CommandDraw;
|
|
use crate::render::Raster;
|
|
use crate::tests::draw::on_device::{descriptor, examples, library, state};
|
|
use crate::{ColorAttachmentDescriptor, RenderPipelineDescriptor};
|
|
use ash::vk;
|
|
use metal2vulkan::pipeline::IndirectDrawLayout;
|
|
let (Some(examples), Some(words), Some(patches)) = (
|
|
examples(),
|
|
library(&engine_dir().join("tb_word_formats.ll")),
|
|
library(&engine_dir().join("icb_merged_patches.ll")),
|
|
) else {
|
|
return;
|
|
};
|
|
let function = |library: &Library, name: &str| {
|
|
StageSource::Function(FunctionDescriptor::new(
|
|
library.function(name).expect("the function"),
|
|
))
|
|
};
|
|
let mut plain = descriptor(&examples, "colored_fragment", PixelFormat::RGBA8Unorm);
|
|
plain.fragment = Some(function(&words, "tb_word_fragment"));
|
|
plain.support_indirect_command_buffers = true;
|
|
let mut patch =
|
|
RenderPipelineDescriptor::new(function(&patches, "icb_merged_patch_vertex"));
|
|
patch.fragment = Some(function(&words, "tb_word_fragment"));
|
|
patch.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm));
|
|
patch.support_indirect_command_buffers = true;
|
|
let contents = [
|
|
(
|
|
"plain draws",
|
|
&plain,
|
|
vk::PrimitiveTopology::TRIANGLE_LIST,
|
|
CommandDraw::Plain,
|
|
),
|
|
(
|
|
"patch draws",
|
|
&patch,
|
|
vk::PrimitiveTopology::PATCH_LIST,
|
|
CommandDraw::Patches,
|
|
),
|
|
];
|
|
each_device("texture buffer words shapes", |name, _, device| {
|
|
let core = device.core();
|
|
let Some(indirect) = core.indirect.as_ref() else {
|
|
println!("texture buffer words shapes: {name}: no indirect command buffers");
|
|
return;
|
|
};
|
|
for (what, d, class, draw) in contents {
|
|
if draw == CommandDraw::Patches && !indirect.limits.tessellation_stages {
|
|
println!("texture buffer words shapes: {name}: {what}: no tessellation stages");
|
|
continue;
|
|
}
|
|
let state = state(name, &device, d);
|
|
let compiled = &state.inner.compiled;
|
|
// A content has a words twin where the device holds some format as words.
|
|
if !compiled.binds_words(|_, _| true) {
|
|
println!("texture buffer words shapes: {name}: {what}: no words twin");
|
|
continue;
|
|
}
|
|
let made = |words| {
|
|
(compiled.pipeline(class, Raster::default(), words))
|
|
.unwrap_or_else(|error| panic!("{name}: {what}: {error}"))
|
|
};
|
|
let (plain, twin) = (made(false), made(true));
|
|
assert_ne!(
|
|
plain, twin,
|
|
"{name}: {what}: the twin is a pipeline of its own"
|
|
);
|
|
let layout = IndirectDrawLayout::new(0, 0).expect("a layout");
|
|
let before = indirect.held().1;
|
|
for pipeline in [plain, twin] {
|
|
(indirect.shape(core, (compiled, pipeline), (layout, draw), 1))
|
|
.unwrap_or_else(|error| panic!("{name}: {what}: {error}"));
|
|
}
|
|
let shapes = indirect.held().1 - before;
|
|
println!(
|
|
"texture buffer words shapes: {name}: {what}: plain and twin sized {shapes} shapes"
|
|
);
|
|
assert_eq!(
|
|
shapes, 2,
|
|
"{name}: {what}: a shape for the plain pipeline and one for the twin"
|
|
);
|
|
}
|
|
});
|
|
}
|
|
}
|