Take the device's native texel rounding, residency, level clamp and stores

One work packet, landed as 7 commits (d1161d6b38..322dc6354d on archive/development-linear-2026-10-28), in order:

* Take the device's native texel rounding, residency, level clamp and stores

Rule 1: where the device has a native form it is the only form, noted where it can differ.

- Half texels on MoltenVK: a `half` read, sample or gather is the device's `float` texel (Metal's
  there) rounded to nearest even. The routine keeps only the YCbCr 8192 grid's ties away (the
  YCbCr work's), so the Metal-sampler families (32-bit float sample toward zero, the 16-bit
  normalized grids' exact half, the unmeasured class) go, with `HalfFamilies`, `HalfForm`, the
  grid constants and `texel_round::ones_ratio_*`. `HalfTexelConversion` is recorded under the
  bound format for a 32-bit float sample, a 16-bit normalized texel and an unmeasured format.
- Subnormal coordinates: the clamp-to-zero flush is gone; the device reads the coordinate
  (`DeviceSampling`).
- Residency: on a device with `shaderResourceResidency` a sample's or gather's word is the
  device's sparse residency (`SparseResidency`); Metal's footprint rule and the tile map stay only
  where the device has no residency of its own. `Probe`, the named footprint taps and the
  zeroing of them go.
- Level clamps: a sampler's `lodMinClamp`/`lodMaxClamp` reach the device as given, not snapped to
  Metal's 1/64 grid; MoltenVK's Metal sampler snaps itself. Level queries are noted
  `DeviceSampling` off MoltenVK.
- Stores: an integer texel written into a half-float or `RG11B10Float` storage texture of the
  float class is the store's to convert (noted `DeviceColorConversion`), and a `float` blend
  into a 16-bit float attachment through the pixel interlock is the store's to round (Metal's
  where the profile takes `MetalHalfStorageWrites`, else noted). Only
  `TextureWriteRoundingMode::NearestEven` keeps the shader's rounding (no store gives it).
- color_writes.rs docs: drivers round small floats toward zero as measured.

Docs: FAST-PATHS rows 60/61 and the subnormal gap removed; API.md catalogue entries;
`PrecisionNote` and `DriverDeviation` docs. SEMANTICS_VERSION 1950, RUNTIME_VERSION 1750 (the
runtime's sampler cache docs and test).

Verified: cargo clippy --workspace --all-targets --all-features -D warnings clean; the
metal2vulkan suite (3370 tests) with every failure fixed or updated to the native answer
(half_texel, texture_interp's 16-bit grid, srgb_decode, the sparse binder tests, cross-class
writes on the interpreter, fetch_blend16_narrow); golden_hashes moves and is left for
development's re-bless; api-signatures and refusal-surface checks unchanged.

* Take Vulkan's cube-gradient rule on a driver whose route is not measured

A MoltenVK release or GPU whose cube-gradient route no measurement covers took Metal's anisotropic
level and taps in the shader (`CubeGradientRoute::Unmeasured`), and elsewhere an isotropic sampler
made for the use. Rule 1: the device has a native gradient sample, so it is the only form. Such a
driver now takes `CubeGradientRoute::Vulkan` (the form Vulkan's derivative rule reads), the
device's reading recorded as `CubeGradientFootprint`; the emulation stays only for a device
without `samplerAnisotropy`.

With the variant gone nothing sets the isotropic-sampler use, so it is deleted throughout:
`SamplerUse::cube_gradient` and `with_cube_gradient`, `CombinedSampler::cube_gradient` and its
index bit, `HandleClass::Sampler`'s `cube_gradient` (four heap sampler classes, not eight), the
binding keys, the plan's `WriteSource::Sampler`/`ArgumentSampler` and `SamplerSource::Slot`
fields, the codec, the runtime's and the validation executor's binders. The anisotropic emulation
loses its isotropic one-tap form and the `answered` input.

Consumer-visible: `SamplerUse`, `CombinedSampler`, `HandleClass::Sampler`, `WriteSource` and
`SamplerSource` lose the field; `CubeGradientRoute::Unmeasured` is gone (api_signatures blessed).
ARTIFACT_FORMAT_VERSION 470 (the encoded classes and symbols changed).

Docs: profile.rs and error/mod.rs route docs, the AnisotropicFilter and CubeGradientFootprint
notes, API.md's catalogue, FAST-PATHS's unmeasured-route gap removed.

Verified: workspace clippy (all targets, all features) clean; nextest of the touched families
(engine_sampler_unk, engine_heap_binder, engine_handles, anisotropic, driver_facts, cache, bind
heap/plan, sym, metal::sampler, link, runtime sampler_cache, validation argument_buffer_members,
api_signatures/api_surface/fast_paths): 429 run, all pass after updating the tests to the Vulkan
route.

* Ledger lavapipe's halfway nearest-mip level under a descriptor clamp

With the level clamp handed to the device as given, lavapipe rounds a nearest mip filter's level
at `lodMinClamp` 1.5 up to level 2 where Metal reads level 1; Vulkan allows either rounding at a
half. The five `sampler-mip-*` sites are the device's native level selection: `DeviceSampling`'s
docs (and API.md's entry) now state the shape, and known-gaps.tsv holds the five llvmpipe rows.

Verified: `conformance replay --cpu` on lavapipe (linux-gate, arm64) listed exactly these five
sites as unlisted and nothing stale; the conformance ledger tests pass.

* Ledger the two filter-pair sites at their measured difference

The two mixed-filter sites of sampler-mip-filter-pairs-nearest differ by 1000, as the other three
do; the rows copied a truncated figure. Verified by conformance replay --cpu on lavapipe, whose
rerun named these two rows both unlisted and stale.

* Number ARTIFACT_FORMAT_VERSION 472 past the fast-math change's 470

Both the fast-math change and this series moved the artifact format to 470, so the
rebase merged them silently; 471 is held for the maths-functions series.

* Drop the YCbCr sample module's cube_gradient field, gone from CombinedSampler

This series removed CombinedSampler::cube_gradient with the isotropic sampler use;
the YCbCr sample module landed meanwhile still set it. Verified: clippy
--workspace --all-targets --all-features -D warnings clean.

* Re-pin the runtime sources at the landing tip

The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
This commit is contained in:
Anees Iqbal committed 2026-10-28 17:24:22 +02:00
1 parent cdc09276f3
commit ae70850097
65 files changed
+1119 -3621

No files matched your search

@@ -1030,3 +1030,8 @@ compressed-blits-rgb9e5f llvmpipe divergent case/level-3-padded 8 elements diffe
compressed-blits-rgb9e5f llvmpipe divergent case/out-of-compressed 509 elements differ (U32), the largest difference 400620895 Metal's blit through the lossless compression it keeps this `RGB9E5Float` texture in lowers each texel's shared exponent to the least that holds its value, and the device's copy keeps the bytes it read, the same value in another encoding. `shared-exponent-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the same value -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-rgb9e5f llvmpipe divergent case/over-a-buffer 532 elements differ (U32), the largest difference 426639677 Metal's blit through the lossless compression it keeps this `RGB9E5Float` texture in lowers each texel's shared exponent to the least that holds its value, and the device's copy keeps the bytes it read, the same value in another encoding. `shared-exponent-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the same value -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
compressed-blits-rgb9e5f llvmpipe divergent case/tall 494 elements differ (U32), the largest difference 402462819 Metal's blit through the lossless compression it keeps this `RGB9E5Float` texture in lowers each texel's shared exponent to the least that holds its value, and the device's copy keeps the bytes it read, the same value in another encoding. `shared-exponent-kept` records it (the runtime's `compressed_blit.rs`), and its bound -- the same value -- covers the difference (Metal's probes behind `compressed_blit.rs`: the same value, another encoding). Open: nothing; rule 1 rules out a pass that writes Metal's encoding.
sampler-mip-nearest llvmpipe divergent case/clamp-1-5/sampled 16 elements differ (F32), the largest difference 1000 Under a nearest mip filter and `lodMinClamp` 1.5 Metal reads level 1 (`ceil(clamp + 0.5) - 1`, the case's table); the device's own sampler takes the descriptor's clamp as given and lavapipe rounds the halfway level up, reading level 2, which Vulkan allows (its nearest mip level may round either way at a half). The device's native level selection, recorded as `DeviceSampling` (device-sampling), whose documentation states this shape (a nearest mip filter's level at a clamp halfway between two levels). Open: nothing; rule 1 makes the device's level the answer, and no clamp nudged off Metal's grid is kept to steer it.
sampler-mip-filter-pairs-nearest llvmpipe divergent case/linear-linear-clamp-1-5/sampled 16 elements differ (F32), the largest difference 1000 Under a nearest mip filter and `lodMinClamp` 1.5 Metal reads level 1 (`ceil(clamp + 0.5) - 1`, the case's table); the device's own sampler takes the descriptor's clamp as given and lavapipe rounds the halfway level up, reading level 2, which Vulkan allows (its nearest mip level may round either way at a half). The device's native level selection, recorded as `DeviceSampling` (device-sampling), whose documentation states this shape (a nearest mip filter's level at a clamp halfway between two levels). Open: nothing; rule 1 makes the device's level the answer, and no clamp nudged off Metal's grid is kept to steer it.
sampler-mip-filter-pairs-nearest llvmpipe divergent case/linear-min-nearest-mag-clamp-1-5/sampled 16 elements differ (F32), the largest difference 1000 Under a nearest mip filter and `lodMinClamp` 1.5 Metal reads level 1 (`ceil(clamp + 0.5) - 1`, the case's table); the device's own sampler takes the descriptor's clamp as given and lavapipe rounds the halfway level up, reading level 2, which Vulkan allows (its nearest mip level may round either way at a half). The device's native level selection, recorded as `DeviceSampling` (device-sampling), whose documentation states this shape (a nearest mip filter's level at a clamp halfway between two levels). Open: nothing; rule 1 makes the device's level the answer, and no clamp nudged off Metal's grid is kept to steer it.
sampler-mip-filter-pairs-nearest llvmpipe divergent case/nearest-min-linear-mag-clamp-1-5/sampled 16 elements differ (F32), the largest difference 1000 Under a nearest mip filter and `lodMinClamp` 1.5 Metal reads level 1 (`ceil(clamp + 0.5) - 1`, the case's table); the device's own sampler takes the descriptor's clamp as given and lavapipe rounds the halfway level up, reading level 2, which Vulkan allows (its nearest mip level may round either way at a half). The device's native level selection, recorded as `DeviceSampling` (device-sampling), whose documentation states this shape (a nearest mip filter's level at a clamp halfway between two levels). Open: nothing; rule 1 makes the device's level the answer, and no clamp nudged off Metal's grid is kept to steer it.
sampler-mip-filter-pairs-nearest llvmpipe divergent case/nearest-nearest-clamp-1-5/sampled 16 elements differ (F32), the largest difference 1000 Under a nearest mip filter and `lodMinClamp` 1.5 Metal reads level 1 (`ceil(clamp + 0.5) - 1`, the case's table); the device's own sampler takes the descriptor's clamp as given and lavapipe rounds the halfway level up, reading level 2, which Vulkan allows (its nearest mip level may round either way at a half). The device's native level selection, recorded as `DeviceSampling` (device-sampling), whose documentation states this shape (a nearest mip filter's level at a clamp halfway between two levels). Open: nothing; rule 1 makes the device's level the answer, and no clamp nudged off Metal's grid is kept to steer it.
Can't render this file because it is too large.
+3 -6
View File
@@ -1628,11 +1628,10 @@ fn image_descriptor(
slot,
compare,
integer,
cube_gradient,
opaque_black,
} => sampler(
*slot,
SamplerUse::new(*compare, *integer).with_cube_gradient(*cube_gradient),
SamplerUse::new(*compare, *integer),
*opaque_black,
format,
)?,
@@ -1648,11 +1647,10 @@ fn image_descriptor(
slot,
compare,
integer,
cube_gradient,
opaque_black,
} => vk::DescriptorImageInfo::default().sampler(sampler(
*slot,
SamplerUse::new(*compare, *integer).with_cube_gradient(*cube_gradient),
SamplerUse::new(*compare, *integer),
*opaque_black,
None,
)?),
@@ -1778,13 +1776,12 @@ fn image_descriptor(
index,
compare,
integer,
cube_gradient,
} => match tables.argument_samplers.get(*index as usize) {
Some(state) => {
let desc = metal2vulkan::bind::sampler_desc(
device.compile_device(),
state.descriptor(),
SamplerUse::new(*compare, *integer).with_cube_gradient(*cube_gradient),
SamplerUse::new(*compare, *integer),
OpaqueBlackBorder::Stated,
None,
)
+8 -8
View File
@@ -151,15 +151,15 @@ impl SamplerKey {
/// two, and the device's live samplers are held to its limit on every creation ([`SamplerCount`]).
///
/// A state's distinct Vulkan samplers are its descriptor's, one per fact Metal keeps out of the
/// descriptor: how a function samples through it (`SamplerUse`, eight in all: a depth comparison,
/// an integer texture and a cube's explicit gradients), the opaque-black border a view needs, and
/// the LOD clamps a bind replaces the descriptor's with. Without a bind's clamps a state has at
/// most **8** descriptions on every committed device profile, and over the sixteen mip levels a
/// texture-streaming workload clamps to it has **128** (`tests/sampler_cache.rs`, which enumerates
/// descriptor: how a function samples through it (`SamplerUse`, four in all: a depth comparison
/// and an integer texture), the opaque-black border a view needs, and the LOD clamps a bind
/// replaces the descriptor's with. Without a bind's clamps a state has at most **8** descriptions
/// on every committed device profile, and over the sixteen mip levels a texture-streaming
/// workload clamps to it has **128** (`tests/sampler_cache.rs`, which enumerates
/// them through `bind::sampler_desc` over every profile in `validation/profiles`). A bind's clamps
/// are taken on Metal's grid of a sixty-fourth of a level, so a workload clamping off the integer
/// levels can ask one state for more than this; it then forgets and makes Vulkan samplers, which
/// is why the lookup is a map and not a walk of what the state keeps ([`KeptSamplers`]).
/// are handed to the device as given, so a workload clamping off the integer levels can ask one
/// state for more than this; it then forgets and makes Vulkan samplers, which is why the lookup is
/// a map and not a walk of what the state keeps ([`KeptSamplers`]).
const KEPT: usize = 128;
/// The device's live Vulkan samplers, at most `maxSamplerAllocationCount`: every sampler the
@@ -32,16 +32,14 @@ use std::sync::Arc;
/// finds every one of them (`sampler::KEPT`, which is private).
const KEPT: usize = 128;
/// Every way a function can sample through one sampler state: a depth comparison, an integer
/// texture and a cube's explicit gradients, the eight facts Metal keeps out of the descriptor and
/// the heap's sampler classes name (`pipeline::sym::HandleClass::Sampler`).
/// Every way a function can sample through one sampler state: a depth comparison and an integer
/// texture, the four uses of the facts Metal keeps out of the descriptor that the heap's sampler
/// classes name (`pipeline::sym::HandleClass::Sampler`).
fn uses() -> Vec<SamplerUse> {
let mut out = Vec::new();
for compare in [false, true] {
for integer in [false, true] {
for cube in [false, true] {
out.push(SamplerUse::new(compare, integer).with_cube_gradient(cube));
}
out.push(SamplerUse::new(compare, integer));
}
}
out
@@ -106,11 +104,11 @@ fn devices() -> Vec<(String, Device)> {
.collect()
}
/// A state bound without a bind's LOD clamps has one Vulkan sampler per use a function samples it
/// through, eight at the most and four for Metal's default descriptor (whose nearest filters and
/// unmipmapped levels leave a comparison and an integer texture the only facts that change it), on
/// every committed profile: well inside what the state keeps, so the cache answers every bind of
/// such a state after the first of each use.
/// A state bound without a bind's LOD clamps has a Vulkan sampler per use a function samples it
/// through and per form of its opaque-black border, eight at the most and four for Metal's default
/// descriptor (whose nearest filters and unmipmapped levels leave a comparison and an integer
/// texture the only facts that change it), on every committed profile: well inside what the state
/// keeps, so the cache answers every bind of such a state after the first of each use.
#[test]
fn a_state_has_at_most_eight_descriptions_without_a_binds_lod_clamps() {
for (stem, device) in devices() {
@@ -126,7 +124,7 @@ fn a_state_has_at_most_eight_descriptions_without_a_binds_lod_clamps() {
}
/// A state a texture-streaming workload binds with the lower LOD clamp of each resident mip level
/// has one Vulkan sampler per level per use: 128 over the sixteen levels of the largest mip chain
/// has eight Vulkan samplers per level: 128 over the sixteen levels of the largest mip chain
/// Metal's level grid reaches, on every committed profile. That is what the cache is sized at, so
/// such a workload finds every one of them.
#[test]
@@ -136,18 +134,18 @@ fn a_streaming_state_has_a_hundred_and_twenty_eight() {
assert_eq!(
streaming.len(),
128,
"{stem}: sixteen clamp levels, eight uses"
"{stem}: sixteen clamp levels, eight descriptions each"
);
assert_eq!(streaming.len(), KEPT, "{stem}: what the state keeps");
}
}
/// A bind's LOD clamps are taken on Metal's grid of a sixty-fourth of a level, so clamps off the
/// integer levels are distinct descriptions and a workload can ask one state for more than it
/// keeps: a thousand lower clamps across one level are sixty-four of them. The cache is bounded
/// whatever a workload asks, which is why its lookup may not be a walk.
/// A bind's LOD clamps are handed to the device as given, so clamps off the integer levels are
/// distinct descriptions and a workload can ask one state for more than it keeps: a thousand lower
/// clamps across one level are a thousand of them. The cache is bounded whatever a workload asks,
/// which is why its lookup may not be a walk.
#[test]
fn a_binds_clamps_are_taken_on_metals_level_grid() {
fn a_binds_clamps_are_handed_to_the_device_as_given() {
let mut d = SamplerDescriptor::new();
d.min_filter = F::Linear;
d.mag_filter = F::Linear;
@@ -168,7 +166,7 @@ fn a_binds_clamps_are_taken_on_metals_level_grid() {
.unwrap_or_else(|e| panic!("{stem}: {e:?}"));
seen.insert(desc);
}
assert_eq!(seen.len(), 64, "{stem}: a level holds sixty-four clamps");
assert_eq!(seen.len(), 1000, "{stem}: every clamp its own description");
}
}
@@ -1 +1 @@
95d9629482dcdae2e9f76fab633ccbecd7d39146383389a828ea12c5bcacf668
76a9fc3f3f8c0034a0863faf5ff0172cabf44f29990bd86cd25c47ab61fd1afa
@@ -736,8 +736,7 @@ fn an_argument_buffer_sampler_is_the_sampler_table_entry_its_owner_names() {
index,
compare,
integer,
cube_gradient,
} => Some((write.array_element, index, compare, integer, cube_gradient)),
} => Some((write.array_element, index, compare, integer)),
_ => None,
})
.collect::<Vec<_>>();
@@ -745,7 +744,7 @@ fn an_argument_buffer_sampler_is_the_sampler_table_entry_its_owner_names() {
assert_eq!(
elements,
(1..32)
.map(|e| (e, e - 1, false, false, false))
.map(|e| (e, e - 1, false, false))
.collect::<Vec<_>>()
);
assert!(plan.descriptors.iter().any(|write| write.array_element == 0
@@ -548,12 +548,10 @@ impl<'a> PlanResources<'a> {
slot,
compare,
integer,
cube_gradient,
opaque_black,
} => {
let desc = bound_sampler(guest, *slot)?;
let use_ =
SamplerUse::new(*compare, *integer).with_cube_gradient(*cube_gradient);
let use_ = SamplerUse::new(*compare, *integer);
self.slot_sampler(
context,
device,
@@ -581,11 +579,10 @@ impl<'a> PlanResources<'a> {
slot,
compare,
integer,
cube_gradient,
opaque_black,
} => {
let desc = bound_sampler(guest, *slot)?;
let use_ = SamplerUse::new(*compare, *integer).with_cube_gradient(*cube_gradient);
let use_ = SamplerUse::new(*compare, *integer);
let sampler =
self.slot_sampler(context, device, desc, (use_, *opaque_black), None)?;
Info::Image(vk::DescriptorImageInfo::default().sampler(sampler))
@@ -596,9 +593,8 @@ impl<'a> PlanResources<'a> {
index,
compare,
integer,
cube_gradient,
} => {
let use_ = SamplerUse::new(*compare, *integer).with_cube_gradient(*cube_gradient);
let use_ = SamplerUse::new(*compare, *integer);
let sampler = match guest.argument_samplers.get(*index as usize) {
Some(listed) => self.slot_sampler(
context,
@@ -22,8 +22,9 @@
//! lane extended by the format's signedness) saturated to its channel's range, through a slot
//! of the format's own class as through one of another class.
//! - [`integer_writes_into_float_formats_store_the_bits_as_floats`]: an `int` or `uint` write to
//! a float format stores what a `float` write of those bits stores, rounded to nearest even
//! onto a half-float channel; a `short` or `ushort` write what a `half` write of those bits
//! a float format stores what a `float` write of those bits stores, the device's conversion
//! onto a half-float channel, announced as `device-color-conversion` (Metal rounds it to
//! nearest even); a `short` or `ushort` write what a `half` write of those bits
//! stores; a NaN channel's bits the device's (counted apart), where the device announced
//! `native-half-conversion`, `native-nan-encoding` or `device-nan-encoding` (the pipeline it
//! specialized to the bound format records the write's note, which the stage compiled without
@@ -33,7 +34,7 @@
use super::degrade_notices::on_device;
use super::driver_deviations::{half_nan, stage_notes};
use super::extended_range_targets::{half_bits, half_value};
use super::extended_range_targets::half_value;
use super::{buffer_with, read_buffer, Messages};
use crate::air_library::AirLibrary;
use metal2vulkan::metal::format::sampled_type;
@@ -765,12 +766,11 @@ fn integer_writes_store_metals_saturated_words() {
}
/// Each `int` or `uint` write to a float format of [`FORMATS`] stores what a `float` write of
/// the lanes' bits stores (rounded to nearest even, a finite value past the range to infinity,
/// onto a half-float channel: what a `half` write of that rounding stores), and each `short` or
/// the lanes' bits stores, the device's conversion onto a half-float channel (where Metal rounds
/// to nearest even, so the stage records `device-color-conversion`), and each `short` or
/// `ushort` write what a `half` write of the same bits stores, through an `access::write` 2D slot
/// and a texture buffer; a NaN as Metal stores it: an `int` or `uint` NaN's bits
/// in a half-float channel `0x7e00`, a 16-bit lane's NaN in a 32-bit float channel `0x7fc00000`.
/// None announces the neutral.
/// and a texture buffer; a 16-bit lane's NaN in a 32-bit float channel as Metal stores it,
/// `0x7fc00000`. None announces the neutral.
#[test]
fn integer_writes_into_float_formats_store_the_bits_as_floats() {
on_device(|device, messages| {
@@ -778,6 +778,8 @@ fn integer_writes_into_float_formats_store_the_bits_as_floats() {
let mut pipelines: BTreeMap<(Kind, Ty), ComputePipelineState> = BTreeMap::new();
let (mut checked, mut differ, mut skipped) = (0usize, 0usize, 0usize);
let mut nans = 0usize;
// A 32-bit lane written into a half-float format, which the device's conversion rounds.
let mut rounded = false;
let _ = messages.take_notices();
for &(format, bytes, _) in &FORMATS {
if sampled_type(format) != Some(SampledType::Float) {
@@ -786,11 +788,11 @@ fn integer_writes_into_float_formats_store_the_bits_as_floats() {
let halves = matches!(format, P::R16Float | P::RGBA16Float);
for kind in [Kind::Write, Kind::BufWrite] {
for ty in [Ty::Int, Ty::Uint, Ty::Short, Ty::Ushort] {
// The native write giving Metal's answer, and its lanes.
// Metal's NaNs: an `int` or `uint` NaN's bits into a half-float
// channel `0x7e00`, a 16-bit lane's NaN into a 32-bit float channel
// `0x7fc00000` (the rule for a `half` write), so those take the `float` write
// of the widened value, which stores its bits.
// The native write giving the answer, and its lanes: an `int` or `uint`
// write's the `float` write of its bits, the device's conversion; a 16-bit
// lane's NaN into a 32-bit float channel Metal's `0x7fc00000` (the rule for a
// `half` write), so those take the `float` write of the widened value, which
// stores its bits.
let wide = matches!(format, P::R32Float | P::RGBA32Float);
let (native, lanes): (Ty, Box<dyn Fn(u64, usize) -> u32>) =
match (ty.narrow(), halves) {
@@ -805,18 +807,9 @@ fn integer_writes_into_float_formats_store_the_bits_as_floats() {
}),
),
(true, _) => (Ty::Half, Box::new(move |t, c| lane(ty, t, c))),
(false, true) => (
Ty::Half,
Box::new(move |t, c| {
let f = f32::from_bits(lane(ty, t, c));
match f.is_nan() {
true => 0x7e00,
false => u32::from(half_bits(f)),
}
}),
),
(false, false) => (Ty::Float, Box::new(move |t, c| lane(ty, t, c))),
(false, _) => (Ty::Float, Box::new(move |t, c| lane(ty, t, c))),
};
rounded |= halves && !ty.narrow();
let n = kind.threads();
let mut run = |t: Ty, src: &[u8]| -> Option<Vec<u8>> {
let (texture, backing) = made(device, (format, bytes), kind, None)?;
@@ -884,6 +877,11 @@ fn integer_writes_into_float_formats_store_the_bits_as_floats() {
!announced.contains(&Degradation::CrossClassTextureNeutral),
"an exact write bound the neutral"
);
assert!(
!rounded || announced.contains(&Degradation::DeviceColorConversion),
"a 32-bit lane rounded onto a half-float channel without device-color-conversion, \
announced {announced:?}"
);
let nan_kinds = NAN_NOTES.map(Degradation::from_precision_note);
assert!(
nans == 0 || nan_kinds.iter().any(|k| announced.contains(k)),
@@ -314,17 +314,18 @@ const BELOW_ZERO: [(usize, u32); 3] = [(289, 0x8000_0001), (291, 0x8000_0002), (
/// keeps the subnormal would read the border, 0, through both.
const METAL_BELOW_ZERO: [f32; 2] = [80.0, 40.0];
/// Both constexpr clamp-to-zero samplers read Metal's value one, two and three units in the last
/// place below `+0.0`: the module flushes a subnormal coordinate on a border axis as Metal's
/// texture unit reads it (`lower::sampler::position::subnormal_flush`), so the device's own border
/// test is handed Metal's coordinate.
/// Both constexpr clamp-to-zero samplers one, two and three units in the last place below `+0.0`
/// read what the device's sampler reads there: the module hands the coordinate as given. Through
/// Metal's own texture unit (MoltenVK) that is Metal's value, which flushes the subnormal; a
/// device of its own (`device-sampling` announced) reads it as it does, Metal's value or the
/// border.
#[test]
fn clamp_to_zero_samples_just_below_zero_read_metal_s_texels() {
fn clamp_to_zero_samples_just_below_zero_read_the_devices_texels() {
let us = lanes();
for &(lane, bits) in &BELOW_ZERO {
assert_eq!(us[lane].to_bits(), bits, "lane {lane}");
}
super::degrade_notices::on_device(|device, _| {
super::degrade_notices::on_device(|device, messages| {
let float = texture(device, PixelFormat::R32Float, (WIDTH, HEIGHT), |x, y| {
((x + 16 * y) as f32).to_le_bytes()
});
@@ -345,6 +346,14 @@ fn clamp_to_zero_samples_just_below_zero_read_metal_s_texels() {
}
}
}
if own_sampler(device, messages) {
println!(
"BELOW-ZERO {}: the device's own sampler, {} lanes differ from Metal",
device.name(),
wrong.len()
);
return;
}
assert!(wrong.is_empty(), "{}: {wrong:#?}", device.name());
});
}
+10 -21
View File
@@ -169,7 +169,7 @@ pub enum HeapSource {
/// Every heap array class of `profile`, sorted and distinct: the image classes the core can declare
/// there, then the sampler classes of every use (with comparison or without, of an integer texture
/// or not, for a cube's explicit gradients or not).
/// or not).
pub fn heap_classes(profile: &DeviceProfile) -> Vec<HandleClass> {
let mut out: Vec<HandleClass> = image_classes(profile)
.into_iter()
@@ -177,13 +177,7 @@ pub fn heap_classes(profile: &DeviceProfile) -> Vec<HandleClass> {
.collect();
for compare in [false, true] {
for integer in [false, true] {
for cube_gradient in [false, true] {
out.push(HandleClass::Sampler {
compare,
integer,
cube_gradient,
});
}
out.push(HandleClass::Sampler { compare, integer });
}
}
out.sort();
@@ -1146,14 +1140,10 @@ impl<'a> HeapPlanner<'a> {
}
let image = match class {
HandleClass::Image(image) => image,
// The array's `VkSampler`s are made for its use: the comparison, the texel class, and
// a cube's explicit gradients in the isotropic form, which makes a listed anisotropic
// state isotropic.
HandleClass::Sampler {
compare,
integer,
cube_gradient,
} => return self.sampler_array(set, b, (compare, integer, cube_gradient)),
// The array's `VkSampler`s are made for its use: the comparison and the texel class.
HandleClass::Sampler { compare, integer } => {
return self.sampler_array(set, b, (compare, integer))
}
HandleClass::FunctionTable => return self.function_table_array(set, b),
};
let expected = if image.access == ImageAccess::Storage {
@@ -1269,14 +1259,14 @@ impl<'a> HeapPlanner<'a> {
})
}
/// The writes of the sampler array `b` of set `set` for the use (`compare`, `integer`,
/// `cube_gradient`): element 0 the use's neutral sampler, element `i + 1` argument sampler `i`
/// made for the use, through the class's entries.
/// The writes of the sampler array `b` of set `set` for the use (`compare`, `integer`):
/// element 0 the use's neutral sampler, element `i + 1` argument sampler `i` made for the use,
/// through the class's entries.
fn sampler_array(
&self,
set: u32,
b: &DescriptorBinding,
(compare, integer, cube_gradient): (bool, bool, bool),
(compare, integer): (bool, bool),
) -> Result<Vec<DescriptorWrite>, BindError> {
if b.ty != vk::DescriptorType::SAMPLER {
return Err(internal(format!(
@@ -1307,7 +1297,6 @@ impl<'a> HeapPlanner<'a> {
index: element - 1,
compare,
integer,
cube_gradient,
},
));
}
+13 -40
View File
@@ -54,9 +54,9 @@ const READ: TextureUsage = TextureUsage::SHADER_READ;
const WRITE: TextureUsage = TextureUsage::SHADER_WRITE;
/// On every committed profile the heap classes are distinct and sorted, every image class has
/// a neutral of exactly its type (an empty heap element can be written), the eight sampler
/// classes (one per use: comparison, integer texel, and a cube's explicit gradients) close the
/// list, and cube arrays and multisampled storage images follow the profile.
/// a neutral of exactly its type (an empty heap element can be written), the four sampler
/// classes (one per use: comparison and integer texel) close the list, and cube arrays and
/// multisampled storage images follow the profile.
#[test]
fn heap_classes_are_the_declarable_images_and_every_sampler_use() {
for (stem, p) in committed_profiles().expect("profiles") {
@@ -64,19 +64,10 @@ fn heap_classes_are_the_declarable_images_and_every_sampler_use() {
assert!(classes.windows(2).all(|w| w[0] < w[1]), "{stem}");
for compare in [false, true] {
for integer in [false, true] {
for cube_gradient in [false, true] {
let class = HandleClass::Sampler {
compare,
integer,
cube_gradient,
};
assert!(classes.contains(&class));
assert_eq!(
class.sampler_use(),
Some(SamplerUse::new(compare, integer).with_cube_gradient(cube_gradient))
);
assert_eq!(class.sampler_use().map(HandleClass::sampler), Some(class));
}
let class = HandleClass::Sampler { compare, integer };
assert!(classes.contains(&class));
assert_eq!(class.sampler_use(), Some(SamplerUse::new(compare, integer)));
assert_eq!(class.sampler_use().map(HandleClass::sampler), Some(class));
}
}
let images = &p.fields().images;
@@ -96,7 +87,7 @@ fn heap_classes_are_the_declarable_images_and_every_sampler_use() {
assert!(images.storage_multisample, "{stem}: {i:?}");
}
}
let n_images = classes.len() - 8;
let n_images = classes.len() - 4;
assert_eq!(n_images, image_classes(&p).len(), "{stem}: duplicates");
}
}
@@ -909,7 +900,6 @@ fn sampler_tables_relist_states_of_the_plans_shapes() {
classes: vec![HandleClass::Sampler {
compare: false,
integer: false,
cube_gradient: false,
}],
cubic: true,
opaque_black: false,
@@ -1012,7 +1002,6 @@ fn a_late_cubic_sampler_is_listed_with_its_cubic_bit_beside_tested_stages() {
classes: vec![HandleClass::Sampler {
compare: false,
integer: false,
cube_gradient: false,
}],
cubic: tested,
opaque_black: false,
@@ -1092,10 +1081,9 @@ fn sampler_tables_admit_the_shapes_the_plan_s_checks_pass() {
},
..ResourceTemplate::default()
};
let class = |cube_gradient: bool| HandleClass::Sampler {
let class = HandleClass::Sampler {
compare: false,
integer: false,
cube_gradient,
};
let held_on =
|profile: &DeviceProfile, template: &ResourceTemplate, late: SamplerDescriptor| -> bool {
@@ -1136,17 +1124,11 @@ fn sampler_tables_admit_the_shapes_the_plan_s_checks_pass() {
};
assert!(anisotropic.shape().anisotropic);
assert!(black.shape().opaque_black_border);
let sampled = template(vec![class(false)], false);
let sampled = template(vec![class], false);
assert!(!held(&sampled, lod), "invalid LOD clamps");
assert!(
held(&sampled, anisotropic),
"anisotropic, no cube gradients"
);
assert!(held(&sampled, anisotropic), "anisotropic");
assert!(!held(&sampled, black), "members unchecked for the border");
let gradients = template(vec![class(false), class(true)], false);
assert!(held(&gradients, anisotropic), "beside a cube's gradients");
// Without `samplerAnisotropy` the plan's check refuses an anisotropic state for a use without
// a cube's gradients and passes it for one with them, whose sampler it makes isotropic.
// Without `samplerAnisotropy` the plan's check refuses an anisotropic state.
assert!(
!floor
.fields()
@@ -1159,16 +1141,7 @@ fn sampler_tables_admit_the_shapes_the_plan_s_checks_pass() {
!held_on(&floor, &sampled, anisotropic),
"anisotropic without samplerAnisotropy"
);
assert!(
!held_on(&floor, &gradients, anisotropic),
"anisotropic beside a use without the gradients, without samplerAnisotropy"
);
let cube_only = template(vec![class(true)], false);
assert!(
held_on(&floor, &cube_only, anisotropic),
"a cube's gradients alone, without samplerAnisotropy"
);
let checked = template(vec![class(false)], true);
let checked = template(vec![class], true);
assert!(held(&checked, black), "members checked for the border");
let naming = template(Vec::new(), false);
for late in [lod, anisotropic, black] {
+3 -7
View File
@@ -627,9 +627,8 @@ pub enum WriteSource {
window: Window,
},
/// A `VkSampler` for the sampler bound at `slot`, made for this use: `compare` enables depth
/// comparison, `integer` selects integer border colors, and `cube_gradient` makes it isotropic
/// for a cube's explicit gradients in Metal's isotropic footprint
/// (`metal::sampler::SamplerUse`, `bind::sampler_desc`). The plan checks what the shape states
/// comparison and `integer` selects integer border colors (`metal::sampler::SamplerUse`,
/// `bind::sampler_desc`). The plan checks what the shape states
/// (reduction); the rest of the descriptor is per bind. `opaque_black` says how an opaque-black
/// border is made to read Metal's texel through every texture the sampler meets
/// (`metal::sampler::OpaqueBlackBorder`).
@@ -637,7 +636,6 @@ pub enum WriteSource {
slot: SlotRef,
compare: bool,
integer: bool,
cube_gradient: bool,
opaque_black: OpaqueBlackBorder,
},
/// The stage's argument table; instantiation fills the bytes.
@@ -722,7 +720,7 @@ pub enum WriteSource {
TileMap { slot: SlotRef },
/// Element `index + 1` of a set-1 sampler array: a `VkSampler` for
/// `BindState::argument_samplers[index]`, made for this use as `Sampler` is
/// (`bind::sampler_desc` with `compare`, `integer` and `cube_gradient`), or the neutral sampler
/// (`bind::sampler_desc` with `compare` and `integer`), or the neutral sampler
/// (`NeutralResource::Sampler { compare }`) where the state lists fewer samplers: no handle
/// names that element then. The plan writes every element of its shape's capacity class
/// (`ArgumentSamplersShape::entries`), so the list may grow or shrink within the class
@@ -731,7 +729,6 @@ pub enum WriteSource {
index: u32,
compare: bool,
integer: bool,
cube_gradient: bool,
},
/// The shadow of the render pass's stencil attachment that a fragment function's
/// shader-side stencil tests and writes (`GraphicsState::shadow_stencil`): the consumer's
@@ -844,7 +841,6 @@ pub enum SamplerSource {
slot: SlotRef,
compare: bool,
integer: bool,
cube_gradient: bool,
opaque_black: OpaqueBlackBorder,
},
/// The layout's immutable (constexpr) sampler: the write carries only the image.
@@ -95,7 +95,7 @@ pub(crate) fn bind_error(e: Error) -> BindError {
/// The `VkSampler` of the sampler bound at a plan's `WriteSource::Sampler`,
/// `WriteSource::ArgumentSampler` or `SamplerSource::Slot`: `metal::sampler::vk_sampler` for the
/// write's use (its `compare`, `integer` and `cube_gradient`) on `device`, its opaque-black border
/// write's use (its `compare` and `integer`) on `device`, its opaque-black border
/// made as the write says (`opaque_black`, transparent black, or opaque black with the view's
/// mapping in `border_components`), and, when the sampler reads an image of `image_format` (a
/// combined write's view format), the format's linear-filtering and min/max features the
@@ -1285,7 +1285,6 @@ impl ResourcePlanner<'_> {
slot,
compare,
integer: use_.integer_texture,
cube_gradient: use_.cube_gradient,
opaque_black,
})
}
@@ -1414,13 +1413,11 @@ impl ResourcePlanner<'_> {
slot,
compare,
integer,
cube_gradient,
opaque_black,
} => WriteSource::Sampler {
slot,
compare,
integer,
cube_gradient,
opaque_black,
},
SamplerSource::Neutral(n) => WriteSource::Neutral(n),
@@ -537,7 +537,6 @@ fn runtime_sampler_values_are_checked_at_plan_time() {
slot,
compare,
integer: false,
cube_gradient: false,
opaque_black: crate::metal::sampler::OpaqueBlackBorder::Stated,
}),
"{stem} {name} compare={compare}"
@@ -862,143 +861,6 @@ fn bicubic_texels_follow_the_bound_format() {
);
}
/// A combined binding with the cube-gradient bit (a cube's explicit gradients in Metal's isotropic
/// footprint, which a function takes through a runtime sampler where the device's cube-gradient
/// route is not measured) takes an anisotropic runtime sampler on every committed profile, without
/// `samplerAnisotropy` too: its Vulkan sampler is isotropic (no anisotropy handed), and Metal's
/// anisotropic filter is the function's emulation, whose taps read explicit levels, under the
/// variant naming the slot (`anisotropic_variant`) wherever the function states
/// `RuntimeFact::AnisotropicSampler` for it. An isotropic sampler is accepted for it, and the same
/// anisotropic sampler for a binding without the bit (every other cube-gradient binding, whose
/// footprint the sampler's word chooses) gets the ordinary verdict (`samplerAnisotropy`).
#[test]
fn an_explicit_cube_gradient_binding_takes_an_anisotropic_sampler_isotropically() {
use crate::bind::state::SamplerDescriptor;
use crate::metal::sampler::{vk_sampler, SamplerUse};
let texture = SlotRef {
stage: Stage::Kernel,
class: SlotClass::Texture,
index: 0,
};
let sampler_slot = SlotRef {
stage: Stage::Kernel,
class: SlotClass::Sampler,
index: 2,
};
let isotropic = SamplerDescriptor::new();
let mut anisotropic = isotropic;
anisotropic.max_anisotropy = 4;
let (mut isotropic_taken, mut compiled) = (0, 0);
for (stem, p) in crate::spirv::testing::committed_profiles().expect("profiles") {
let t = slot_iface(TextureType::Cube, SampledType::Float);
let slots = BTreeMap::from([
(texture, SlotInterface::Texture(t)),
(
sampler_slot,
SlotInterface::Sampler(SamplerSlot {
compare: false,
coordinate_sensitive: false,
}),
),
]);
for (name, desc) in [("isotropic", isotropic), ("anisotropic", anisotropic)] {
for cube_gradient in [false, true] {
let mut stage = StageShape::default();
stage.textures.insert(
texture.index,
TextureShape::Texture {
address_modes: crate::metal::sampler::AddressModeMap::IDENTITY,
offset_base_axes: 0,
ycbcr_in_place: false,
texture_type: TextureType::Cube,
pixel_format: PixelFormat::RGBA8Unorm,
sample_count: 1,
usage: crate::metal::TextureUsage::SHADER_READ,
mipmap_level_count: 1,
sparse: false,
swizzle: crate::metal::TextureSwizzleChannels::DEFAULT,
},
);
stage
.samplers
.insert(sampler_slot.index, BoundSampler::new(desc).shape());
let shape = BTreeMap::from([(Stage::Kernel, stage.clone())]);
let mut planner = ResourcePlanner {
profile: &p,
shape: &shape,
slots: &slots,
dependencies: &[],
stage_flags: |_| vk::PipelineStageFlags2::COMPUTE_SHADER,
variant: VariantKey::new(),
diagnostics: Vec::new(),
uses: Vec::new(),
template: Default::default(),
alpha_red_texels: Default::default(),
};
let sampler =
CombinedSampler::new(SamplerRef::Slot(sampler_slot.index), false, false)
.with_cube_gradient(cube_gradient);
let planned = planner.combined(texture, sampler, None);
let verdict = vk_sampler(
&desc,
SamplerUse::new(false, false).with_cube_gradient(cube_gradient),
&p,
);
if name == "anisotropic" && cube_gradient {
let made = verdict.unwrap_or_else(|e| panic!("{stem}: {e:?}"));
assert_eq!(made.max_anisotropy, None, "{stem}: {made:?}");
// The write carries the use, so the binder's `VkSampler` (`sampler_desc`)
// is the isotropic one too.
let Ok(WriteSource::CombinedImageSampler {
sampler:
SamplerSource::Slot {
compare,
integer,
cube_gradient: true,
..
},
..
}) = planned
else {
panic!("{stem}: {planned:?}");
};
let use_ = SamplerUse::new(compare, integer).with_cube_gradient(true);
assert_eq!(vk_sampler(&desc, use_, &p), Ok(made), "{stem}");
let mut bind = crate::bind::state::BindShape::default();
bind.stages.insert(Stage::Kernel, stage);
let stated = [crate::pipeline::RuntimeDependency::new(
crate::pipeline::facts::RuntimeFact::AnisotropicSampler {
slot: sampler_slot,
},
crate::pipeline::facts::Mechanism::Variant,
)];
assert_eq!(
crate::bind::plan::slots::anisotropic_variant(&stated, &bind),
BTreeSet::from([sampler_slot]),
"{stem}"
);
isotropic_taken += 1;
} else {
match verdict {
Ok(_) => {
assert!(
matches!(planned, Ok(WriteSource::CombinedImageSampler { .. })),
"{stem} {name} {cube_gradient}: {planned:?}"
);
compiled += 1;
}
Err(e) => assert_eq!(planned, Err(bind_error(e)), "{stem} {name}"),
}
}
}
}
}
assert!(
isotropic_taken > 0 && compiled > 0,
"{isotropic_taken} taken isotropically, {compiled} accepted"
);
}
/// A runtime sampler slot specializes `SamplerState` to the bound sampler's word masked by the
/// fields the function reads, and an unbound slot to 0. So the pixel predicates hold as they did of
/// `SamplerCoords` and `SamplerPixelNearest`: pixel coordinates wherever the sampler uses them, a
@@ -1348,7 +1210,6 @@ fn a_separate_pair_takes_the_combined_pairs_checks() {
slot: sampler_slot,
compare: false,
integer: false,
cube_gradient: false,
opaque_black: crate::metal::sampler::OpaqueBlackBorder::Stated,
},
None => WriteSource::Neutral(NeutralResource::Sampler { compare: false }),
@@ -105,7 +105,6 @@ const PLANES: ResourceSlot = ResourceSlot {
sampler: SamplerRef::Slot(0),
compare: false,
integer: false,
cube_gradient: false,
}),
index: 0,
};
+2 -2
View File
@@ -811,7 +811,7 @@ codec_struct! {
codec_struct! {
SlotRef { stage, class, index }
ImageHandleClass { dim, arrayed, multisampled, sampled_type, depth_compare, access, format }
CombinedSampler { sampler, compare, integer, cube_gradient }
CombinedSampler { sampler, compare, integer }
ResourceSlot { stage, kind, index }
}
@@ -825,7 +825,7 @@ codec_enum! {
SampledType { Float, Sint, Uint, Uint64 }
ImageAccess { Sampled, Storage }
StorageFormatClass { NotStorage, Unknown, Format(f0) }
HandleClass { Image(f0), Sampler { compare, integer, cube_gradient }, FunctionTable }
HandleClass { Image(f0), Sampler { compare, integer }, FunctionTable }
SyntheticBinding {
ArgumentTable, ExecutionStatus, RootTable, HandleTable, ConstantBlob, TessellationFactors, Imageblock,
SamplerTable,
+3 -3
View File
@@ -60,7 +60,7 @@ mod tests;
/// unchanged version, and its bless records the version. Independent of the crate's version and of
/// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no
/// history.
pub const SEMANTICS_VERSION: u32 = 1901;
pub const SEMANTICS_VERSION: u32 = 1903;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 1901;
/// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag
/// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that
/// bumps it says what changed; this comment keeps no history.
pub const ARTIFACT_FORMAT_VERSION: u32 = 470;
pub const ARTIFACT_FORMAT_VERSION: u32 = 472;
/// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding
/// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 470;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 1674;
pub const RUNTIME_VERSION: u32 = 1675;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
+9 -12
View File
@@ -809,11 +809,11 @@ fn the_version_377_member_round_trips() {
/// The members format versions 153, 154, 155, 157 and 161 joined from every side encode and
/// decode together in one render pipeline: `PrecisionNote::CubeGradientFootprint` and
/// `CombinedSampler::cube_gradient`, `RuntimeFact::InterlockedFramebufferFetch` and
/// `CombinedSampler`, `RuntimeFact::InterlockedFramebufferFetch` and
/// `GraphicsState::storage_attachments`, `SpecKey::TexelFormat`, `RuntimeFact::TexelFormat` and
/// `SrgbTexture`, `VkProperty::MetalSampler`, and `PrecisionNote::HalfTexelConversion`,
/// `HalfSampleFilter`, `SrgbTexelDecode`, and `FloatSampleFilter`,
/// `HandleClass::Sampler { compare, integer, cube_gradient }` and
/// `HandleClass::Sampler { compare, integer }` and
/// `SyntheticBinding::SamplerTable`, and `RuntimeFact::UlongAtomicView`, each beside the others
/// rather than only on its own side's fixtures.
#[test]
@@ -832,7 +832,7 @@ fn the_merged_members_round_trip_in_one_render_pipeline() {
class: SlotClass::Texture,
index: 3,
};
let sampler = CombinedSampler::new(SamplerRef::Slot(1), false, false).with_cube_gradient(true);
let sampler = CombinedSampler::new(SamplerRef::Slot(1), true, false);
let kind = ResourceKind::CombinedTextureSampler(sampler);
assert_eq!(decode::<ResourceKind>(&encode(&kind)), Ok(kind));
let notes = [
@@ -892,8 +892,8 @@ fn the_merged_members_round_trip_in_one_render_pipeline() {
],
flags: vk::DescriptorSetLayoutCreateFlags::empty(),
});
// An argument buffer's sampler array of a comparison use of an integer texel sampling a cube
// with explicit gradients, and the stage's sampler table.
// An argument buffer's sampler array of a comparison use of an integer texel, and the stage's
// sampler table.
let argument_samplers = vec![
DescriptorBinding {
binding: 2,
@@ -903,7 +903,6 @@ fn the_merged_members_round_trip_in_one_render_pipeline() {
source: BindingSource::Heap(HandleClass::Sampler {
compare: true,
integer: true,
cube_gradient: true,
}),
immutable_sampler: None,
flags: vk::DescriptorBindingFlags::PARTIALLY_BOUND,
@@ -989,7 +988,7 @@ fn the_merged_members_round_trip_in_one_render_pipeline() {
assert!(matches!(
bindings.map(|b| &b[0].source),
Some(BindingSource::CombinedTextureSampler { sampler, .. })
if sampler.cube_gradient
if sampler.compare
));
assert_eq!(
bindings.map(|b| &b[1].source),
@@ -999,8 +998,7 @@ fn the_merged_members_round_trip_in_one_render_pipeline() {
bindings.map(|b| &b[2].source),
Some(BindingSource::Heap(HandleClass::Sampler {
compare: true,
integer: true,
cube_gradient: true
integer: true
}))
));
assert!(matches!(
@@ -1496,9 +1494,8 @@ fn combined_and_separate_texture_symbols_round_trip() {
SamplerRef::Slot(3),
SamplerRef::Constexpr([u64::MAX >> 1, 7]),
] {
for rank in 0..8u32 {
let c = CombinedSampler::new(sampler, rank & 4 != 0, rank & 2 != 0)
.with_cube_gradient(rank & 1 != 0);
for rank in 0..4u32 {
let c = CombinedSampler::new(sampler, rank & 2 != 0, rank & 1 != 0);
for texture in [0, 127, (1 << 28) - 1] {
let combined = ResourceSlot {
stage: Stage::Fragment,
+7 -9
View File
@@ -348,16 +348,14 @@ fn derive_fields(
),
// The device's measured value, keyed on its identity as the workarounds are, or the floor.
function_storage: function_storage::of(desc),
// The measured deviations, one per pipeline kind. Unmeasured, a MoltenVK driver's route is unknown, since
// it hands the gradients to Metal by some route; another driver's is Vulkan's rule.
// The measured deviations, one per pipeline kind; unmeasured, Vulkan's rule, the device's
// own reading of the gradients handed to it.
cube_gradients: {
let route = |measured: &[(DriverDeviation, CubeGradientRoute)]| match (
measured.iter().find(|(deviation, _)| deviates(*deviation)),
desc.driver_id,
) {
(Some(&(_, route)), _) => route,
(None, Some(vk::DriverId::MOLTENVK)) => CubeGradientRoute::Unmeasured,
(None, _) => CubeGradientRoute::Vulkan,
let route = |measured: &[(DriverDeviation, CubeGradientRoute)]| {
measured
.iter()
.find(|(deviation, _)| deviates(*deviation))
.map_or(CubeGradientRoute::Vulkan, |&(_, route)| route)
};
CubeGradients {
graphics: route(&[(
+5 -13
View File
@@ -517,8 +517,8 @@ pub struct ProfileFields {
/// How a driver hands a cube sample's explicit gradients to the GPU
/// ([`ProfileFields::cube_gradients`]), per pipeline kind, each decided by the driver's measured
/// deviations (`DriverDeviation::GraphicsCubeGradientTangents` and
/// `DriverDeviation::CubeGradientRoute`);
/// without them, Vulkan's rule, but [`CubeGradientRoute::Unmeasured`] on a MoltenVK `driver_id`.
/// `DriverDeviation::CubeGradientRoute`); without them, Vulkan's rule, the device's own reading,
/// on every driver.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct CubeGradients {
@@ -538,7 +538,9 @@ pub enum CubeGradientRoute {
/// function hands an isotropic sample Metal's length of the two tangent components on one
/// tangent, and an anisotropic one Metal's face gradients without their normal component
/// (`lower::sampler::CubeFootprint::Length` and `Face`); the level and the anisotropic filter
/// are the device's (`PrecisionNote::CubeGradientFootprint`).
/// are the device's (`PrecisionNote::CubeGradientFootprint`). Also the route of a driver no
/// measurement covers (a MoltenVK release or GPU without the deviations), whose reading of
/// the form is its own.
Vulkan,
/// SPIRV-Cross's `spvGradientCube` (its `agx_manual_cube_grad_fixup`) projects each onto the
/// face as Vulkan's rule does and swizzles the two values, then hands them to Metal's
@@ -551,16 +553,6 @@ pub enum CubeGradientRoute {
/// They reach Metal's `gradientcube` as given, which the GPU reads by Metal's own rule, so
/// the function hands Metal's own (`lower::sampler::CubeFootprint::Metal`).
Metal,
/// The driver hands them to Metal by a route its description does not state: a MoltenVK
/// `driver_id` at a release no measurement covers, or a document of one that states no
/// route. The function takes Metal's footprint itself where its emulation reaches the sample
/// (`lower::sampler::anisotropic`): Metal's level, and an anisotropic sampler's taps, each an
/// explicit level of Metal's own sampler, which no route alters
/// (`PrecisionNote::AnisotropicFilter` for the taps). Elsewhere it hands the isotropic form's
/// length, on one tangent, which every route above reads alike (but a `y` face's through
/// [`CubeGradientRoute::AppleProjected`]'s fixup), through an isotropic sampler
/// (`metal::sampler::SamplerUse::cube_gradient`, `PrecisionNote::CubeGradientFootprint`).
Unmeasured,
}
impl CubeGradients {
@@ -328,18 +328,16 @@ fn the_profile_takes_the_deviations_its_driver_is_measured_with() {
assert_eq!(taken(&p), m4_measured, "{version}");
assert!(!centered(&p), "{version}");
}
// Another vendor's GPU: none, the cube routes unmeasured.
// Another vendor's GPU: none, the cube routes unmeasured and so Vulkan's rule.
let vulkan = CubeGradients {
graphics: CubeGradientRoute::Vulkan,
compute: CubeGradientRoute::Vulkan,
};
let mut intel = m3.clone();
intel.vendor_id = 0x8086;
let p = profile_of(intel);
assert_eq!(taken(&p), Vec::new());
assert_eq!(
p.fields().cube_gradients,
CubeGradients {
graphics: CubeGradientRoute::Unmeasured,
compute: CubeGradientRoute::Unmeasured,
}
);
assert_eq!(p.fields().cube_gradients, vulkan);
assert!(!centered(&p));
// Another driver on Apple's vendor: that driver's rows of every GPU (lavapipe's), with
// Vulkan's rule and a centered offset.
@@ -354,10 +352,6 @@ fn the_profile_takes_the_deviations_its_driver_is_measured_with() {
D::MetalFloatStorageNans,
]
);
let vulkan = CubeGradients {
graphics: CubeGradientRoute::Vulkan,
compute: CubeGradientRoute::Vulkan,
};
assert_eq!(p.fields().cube_gradients, vulkan);
assert!(centered(&p));
// NVIDIA's color-NaN stores and `float` denormals: per GPU (the 3090 and the 5080 Laptop
+16 -9
View File
@@ -546,11 +546,11 @@ pub enum Needs {
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DriverDeviation {
/// How the driver hands a kernel's cube sample's explicit gradients to the GPU
/// (`ProfileFields::cube_gradients`'s compute route, `CubeGradientRoute::Unmeasured`): as
/// given, to Metal's own reading. Unmeasured, the function emulates Metal's footprint where
/// its emulation reaches the sample, and elsewhere hands the form every route reads alike
/// through an isotropic sampler. A vertex or fragment function's route is
/// [`DriverDeviation::GraphicsCubeGradientTangents`].
/// (`ProfileFields::cube_gradients`'s compute route, `CubeGradientRoute::Metal`): as given, to
/// Metal's own reading. Unmeasured, the route is Vulkan's rule (`CubeGradientRoute::Vulkan`):
/// the function hands Metal's footprint in the form that rule reads, and the device's reading
/// of it is recorded as `PrecisionNote::CubeGradientFootprint`. A vertex or fragment
/// function's route is [`DriverDeviation::GraphicsCubeGradientTangents`].
CubeGradientRoute,
/// The device runs each 32 consecutive invocations of a compute workgroup in lockstep, as
/// an Apple GPU runs a Metal simdgroup (`VkProperty::SimdgroupLockstep`). Unmeasured, a kernel
@@ -568,10 +568,13 @@ pub enum DriverDeviation {
MetalCanonicalNans,
/// The device samples, filters and converts texels through Metal's own sampler
/// (`VkProperty::MetalSampler`), an 8-bit sRGB texel's decode included. Unmeasured, every
/// sample, gather and comparison is the device's own sampler's all the same
/// sample, gather, comparison and level query is the device's own sampler's all the same
/// (`VkProperty::DeviceSampling`), recorded as `PrecisionNote::DeviceSampling`, and every
/// read, sample, gather and input-attachment read of an sRGB texel the device's own decode,
/// recorded as `PrecisionNote::SrgbTexelDecode`.
/// recorded as `PrecisionNote::SrgbTexelDecode`. A `half` result is the device's `float`
/// texel rounded to nearest even either way; where the profile takes it the module records
/// `PrecisionNote::HalfTexelConversion` only for a class whose Metal `half` is not that
/// `float` rounded so.
MetalSampler,
/// How the driver hands a vertex or fragment function's cube sample's explicit gradients to
/// the GPU under macOS 27 (the graphics route, `CubeGradientRoute::AppleProjected`): through
@@ -683,8 +686,12 @@ pub enum DriverDeviation {
/// stores a kernel's write (`VkProperty::MetalHalfStorageWrites`): rounded toward zero, a
/// finite value past 65504 stored as 65504, an infinity as itself. The shader writes the
/// value as computed either way (`StorageImageClass::Identity`), its NaN as
/// [`MetalHalfStorageNans`] states. Where the profile takes it the module requires the
/// property; unmeasured, such a write records `PrecisionNote::DeviceColorConversion`.
/// [`MetalHalfStorageNans`] states: a fragment function's `float` blend into a 16-bit float
/// attachment in the storage form among them, which Metal's blended write rounds so too.
/// Where the profile takes it the module requires the property; unmeasured, such a write
/// records `PrecisionNote::DeviceColorConversion`. An integer texel written into a half-float
/// image (its bits as the `float`), which Metal's integer store rounds to nearest even, is the
/// store's to convert either way, and records the note.
///
/// [`MetalHalfStorageNans`]: DriverDeviation::MetalHalfStorageNans
MetalHalfStorageWrites,
File diff suppressed because it is too large. Load diff
@@ -198,94 +198,10 @@ fn f32_to_half_from_even_is_exact_on_every_tie() {
}
}
/// `ones_ratio_to_half` is `m / (2^b - 1)` correctly rounded to `half` for every `m` of every
/// `b` it takes, 13 to 16: the 16-bit normalized grids `65535` and `32767` among them, with the
/// quotients that round twice through `f32`.
#[test]
fn ones_ratio_to_half_is_exact_on_every_step() {
let u = vec(int(32), 4);
for b in 13..=16u64 {
let d = (1u64 << b) - 1;
let cases: Vec<Case> = (0..=d)
.collect::<Vec<_>>()
.chunks(4)
.map(|m| {
let mut lanes = m.to_vec();
lanes.resize(4, d);
vec![lanes, vec![b; 4]]
})
.collect();
check(
&format!("m / {d} to half"),
&[u, u],
vec(float(32), 4),
&|fb, a| texel_round::ones_ratio_to_half(fb, u, a[0], a[1]),
&cases,
&|c| {
Some(
c[0].iter()
.map(|m| {
let h = f64_to_f16(*m as f64 / d as f64);
u64::from((f16_to_f64(h) as f32).to_bits())
})
.collect(),
)
},
false,
);
}
}
/// `ones_ratio_factor`'s product of every step `m` of the 16-bit normalized grids rounds to `half`
/// as `m / D` does, from either `f32` neighbour of the exact product; and the factors `2^-b · (1 +
/// k · 2^-23)` that do so are exactly those its note states, strictly between `2^-b` (`k = 0`)
/// and the reciprocal `RN(1 / D)` (`k = 128` on `65535`, `256` on `32767`). Exact: the product of
/// a step below `2^16` and a 24-bit factor has at most 40 bits, and the `half` of an `f32` and of
/// `f64`'s correctly rounded quotient are single roundings (the module note).
#[test]
fn the_ones_ratio_factor_rounds_every_step() {
for (b, last) in [(16u32, 127u32), (15, 255)] {
let d = (1u32 << b) - 1;
let want: Vec<u16> = (0..=d)
.map(|m| f64_to_f16(f64::from(m) / f64::from(d)))
.collect();
let holds = |k: u32| {
let c = f64::from(f32::from_bits(((127 - b) << 23) | k));
(0..=d).all(|m| {
let exact = f64::from(m) * c;
let near = exact as f32;
let other = match f64::from(near).partial_cmp(&exact) {
Some(std::cmp::Ordering::Greater) => f32::from_bits(near.to_bits() - 1),
Some(std::cmp::Ordering::Less) => f32::from_bits(near.to_bits() + 1),
_ => near,
};
[near, other]
.iter()
.all(|v| f64_to_f16(f64::from(*v)) == want[m as usize])
})
};
let reciprocal = (1.0 / d as f32).to_bits();
assert_eq!(reciprocal, ((127 - b) << 23) | (last + 1), "RN(1 / {d})");
assert!(!holds(0), "2^-{b} itself");
assert!(!holds(last + 1), "RN(1 / {d}) itself");
let failing: Vec<u32> = (1..=last).filter(|k| !holds(*k)).collect();
assert!(
failing.is_empty(),
"1 / {d}: factors {failing:?} below RN(1 / D)"
);
let k = texel_round::ONES_RATIO_FACTOR_ULPS;
assert!((1..=last).contains(&k), "the factor's {k} ulps on {d}");
assert_eq!(
texel_round::ones_ratio_factor(b).to_bits(),
((127 - b) << 23) | k
);
}
}
/// The normalized grids the bicubic filter's exact sums land on: `16 · 255`, `16 · 127`, `65535`,
/// `32767`, and the sRGB step scale 4095. The grids: a texture's `half` conversion's, the sRGB
/// table's, and the normalized formats' fields' that a tile function's `half` member reads, down to
/// a 2-bit alpha's 3 and 1, where `3 · 2^24 / d` reaches `2^24`.
/// `32767`, and the sRGB step scale 4095. The grids: the bicubic sums', the sRGB table's, and the
/// normalized formats' fields' that a tile function's `half` member reads, down to a 2-bit alpha's
/// 3 and 1, where `3 · 2^24 / d` reaches `2^24`.
const GRIDS: [u32; 10] = [4080, 2032, 65535, 32767, 4095, 1023, 255, 127, 3, 1];
fn ratio_cases(d: u32) -> Vec<Case> {
@@ -17,11 +17,8 @@
//! with ties away, by an addition and a mask.
//! - [`f32_to_half_from_even`]: toward zero saturating or ties away, derived from an exact
//! rounding to nearest even.
//! - [`ones_ratio_to_half`]: `m / (2^b - 1)` correctly rounded to `half` by one multiplication,
//! for the 16-bit normalized grids.
//! - [`grid_step`] and [`grid_value`]: a normalized texel's step on its format's grid, and a
//! signed step's value `n / D` exactly, shared by the bicubic sums and the conversion of a texel
//! to a `half` result.
//! signed step's value `n / D` exactly, shared by the bicubic sums and the tile reads.
//!
//! Metal's texture reads and samples decode a raw sRGB code through its twelve-bit table, as
//! `air.unpack` does: the step `k` of [`srgb`](crate::lower::arith::srgb), then `k / 4095`
@@ -472,59 +469,6 @@ pub fn ratio_to_half(fb: &mut FunctionBuilder<'_>, u: Form, k: Value, d: Value)
fb.convert(ConvOp::Bitcast, bits, ft)
}
/// `m / (2^b - 1)` correctly rounded to `half` (nearest even), held as its `f32`, for `u32` lanes
/// (form `u`) with `0 <= m <= 2^b - 1` and `13 <= b <= 16` (`b` a run-time value of the same
/// lanes), by one multiplication and no division: `m = 0` is `+0`.
///
/// `m / (2^b - 1) = T / 2^(2b) · 1 / (1 - 2^(-2b))` for `T = m · (2^b + 1) < 2^(2b)`, so the
/// quotient is `(T + ε) / 2^(2b)` with `0 < ε < 1` where `m > 0`. Rounded at bit `s` of `T`
/// (`s = max(msb(T) - 10, 2b - 24)`: eleven significant bits, or the half denormal grid `2^-24`),
/// the discarded part `T mod 2^s + ε` is never a tie and passes half of `2^s` exactly when bit
/// `s - 1` of `T` is set; and `ε` never carries `T + ε` past a power of two, so `msb(T)` places the
/// significand. The result is `keep · 2^(s - 2b)` for `keep = (T >> s) + bit s - 1`, at most
/// `2^11`: its `f32` (exact) with `s - 2b` added to the exponent. On these grids an `f32`
/// quotient rounded to `half` rounds twice: the correctly rounded one differs at `65455 / 65535`
/// ([`ratio_to_half`]'s note), and the product by the reciprocal `1 / D` rounded to `f32` also at
/// `65327 / 65535`, `32727 / 32767` and others.
pub fn ones_ratio_to_half(
fb: &mut FunctionBuilder<'_>,
u: Form,
m: Value,
b: Value,
) -> BResult<Value> {
let c = |fb: &mut FunctionBuilder<'_>, v: u64| splat(fb, u, v);
let (z, one) = (c(fb, 0)?, c(fb, 1)?);
let pow = bin(fb, BinOp::ShiftLeftLogical, one, b)?;
let times = bin(fb, BinOp::IAdd, pow, one)?;
let t = bin(fb, BinOp::IMul, m, times)?;
let two_b = bin(fb, BinOp::ShiftLeftLogical, b, one)?;
let k24 = c(fb, 24)?;
let least = bin(fb, BinOp::ISub, two_b, k24)?;
// `msb(T) - 10`, kept from wrapping where `T = 0` (selected away below).
let k1024 = c(fb, 1024)?;
let some = fb.glsl(GlslOp::UMax, &[t, k1024])?;
let msb = fb.glsl(GlslOp::FindUMsb, &[some])?;
let k10 = c(fb, 10)?;
let s = bin(fb, BinOp::ISub, msb, k10)?;
let s = fb.glsl(GlslOp::UMax, &[s, least])?;
let kept = bin(fb, BinOp::ShiftRightLogical, t, s)?;
let s1 = bin(fb, BinOp::ISub, s, one)?;
let round = bin(fb, BinOp::ShiftRightLogical, t, s1)?;
let round = bin(fb, BinOp::BitwiseAnd, round, one)?;
let kept = bin(fb, BinOp::IAdd, kept, round)?;
let ft = ty(fb, floats(u))?;
let ut = ty(fb, u)?;
let kf = fb.convert(ConvOp::ConvertUToF, kept, ft)?;
let bits = fb.convert(ConvOp::Bitcast, kf, ut)?;
let scale = bin(fb, BinOp::ISub, s, two_b)?;
let k23 = c(fb, 23)?;
let scale = bin(fb, BinOp::ShiftLeftLogical, scale, k23)?;
let bits = bin(fb, BinOp::IAdd, bits, scale)?;
let zero = bin(fb, BinOp::IEqual, t, z)?;
let bits = fb.select(zero, z, bits)?;
fb.convert(ConvOp::Bitcast, bits, ft)
}
/// The step of normalized texel value `x` (`f32` lanes of form `f`) on the grid of `±D` (`d` and
/// `neg_d`, `f32` lanes of the same form): `RoundEven(x · D)`, the product taken without
/// contraction and clamped into `[-D, D]` first, as `i32` bits in `u32` lanes. Vulkan converts a
@@ -541,47 +485,13 @@ pub fn grid_step(
d: Value,
neg_d: Value,
) -> BResult<Value> {
let y = grid_round(fb, x, d, neg_d)?;
let y = fb.binary_no_contraction(BinOp::FMul, x, d)?;
let y = fb.glsl(GlslOp::NClamp, &[y, neg_d, d])?;
let y = fb.glsl(GlslOp::RoundEven, &[y])?;
let it = ty(fb, words(f))?;
fb.convert(ConvOp::ConvertFToS, y, it)
}
/// [`grid_step`]'s step before its conversion to an integer: `RoundEven` of the product clamped
/// into `[-D, D]`, an integral `f32` in `x`'s lanes whose zero may be `-0`.
pub fn grid_round(
fb: &mut FunctionBuilder<'_>,
x: Value,
d: Value,
neg_d: Value,
) -> BResult<Value> {
let y = fb.binary_no_contraction(BinOp::FMul, x, d)?;
let y = fb.glsl(GlslOp::NClamp, &[y, neg_d, d])?;
fb.glsl(GlslOp::RoundEven, &[y])
}
/// The factor `c = 2^-b · (1 + 2^-17)` of the grid `D = 2^b - 1` (`b` 15 or 16, the 16-bit
/// normalized grids) whose product by a step `m` (`0 <= m <= D`) rounds to `half` as `m / D` does:
/// either `f32` neighbour of the exact product `m · c`, rounded to `half` to nearest even, is
/// `m / D` correctly rounded to `half`. So [`ones_ratio_to_half`]'s value is one product rounded
/// by the device's conversion to `half`, for any `f32` rounding of the product.
///
/// Why: `m / D = m · 2^-b · (1 + 2^-b + 2^-2b + ...)` lies above the dyadic `m · 2^-b` (for `m >
/// 0`), by too little to reach the next point where the rounding to `half` changes, and so does
/// `m · c` for every `c` strictly between `2^-b` and `1 / D`; but in `f32` the product may round
/// onto such a point. Checked exhaustively on every step (`the_ones_ratio_factor_rounds_every_step`,
/// both neighbours of each exact product), the factors that hold are exactly those strictly between
/// `2^-b` and the reciprocal `RN(1 / D)`: `2^-b · (1 + k · 2^-23)` for `k` in `1..=127` (`b = 16`)
/// and `1..=255` (`b = 15`). At `k = 0` the product is the dyadic step itself, whose tie to even
/// is wrong where `m / D` lies above a midpoint (`2049 / 65535`); the reciprocal itself (`k = 128`,
/// `256`) rounds twice at `65455` and `65519` (`32759` on `32767`). The factor takes `k = 64`, inside
/// both ranges.
pub fn ones_ratio_factor(b: u32) -> f32 {
f32::from_bits(((127 - b) << 23) | ONES_RATIO_FACTOR_ULPS)
}
/// The `k` of [`ones_ratio_factor`]: its `f32` units above `2^-b`.
pub const ONES_RATIO_FACTOR_ULPS: u32 = 64;
/// The value `n / D` of signed grid step `n` (`i32` bits in `u32` lanes of form `u`, within
/// `[-D, D]`; `d` the grid `D` in `u32` lanes, `1 <= D < 2^16`): `+0` for zero, else the
/// magnitude `|n| / D` correctly rounded by `round` ([`ratio_to_f32`], [`ratio_to_half`], or a
+19 -14
View File
@@ -188,8 +188,11 @@
//! factor of the second source, take the generic blend, below), and stores the
//! result (`extended_range::Blend::half_float`, [`half_blended`]). Metal's compiler appends the
//! blend to the function, in the output's type: a `half` output blends in `half` arithmetic, a
//! `float` one in `float`, its result converted to `half` as Metal's write of a `float` converts it
//! (toward zero; to nearest even under `TextureWriteRoundingMode::NearestEven`). An output of fewer
//! `float` one in `float`, its result converted to `half` by the storage image's store, as Metal's
//! write of a `float` converts it (toward zero) where the profile takes
//! `DriverDeviation::MetalHalfStorageWrites` and as the device does elsewhere
//! (`PrecisionNote::DeviceColorConversion`), and to nearest even in the shader under
//! `TextureWriteRoundingMode::NearestEven`, which no measured store gives. An output of fewer
//! than four lanes (Metal takes none with fewer than the format's channels, so it writes `R16Float`
//! or `RG16Float`, which have no alpha) blends as four whose missing lanes play no part, but where
//! the color channels' factors read the source alpha (`SourceAlpha`, `OneMinusSourceAlpha`): that
@@ -220,8 +223,9 @@
//! function records `PrecisionNote::HalfOutputFastMathBlend` (`HalfOutputPrecision` for a module
//! that names no math mode): measured within 2 `half` units in the last place at the operands'
//! magnitude, 16 at the output's under cancellation (below one at the function's own largest term).
//! The texel stores a `half` in every channel, so no conversion of the device's bears on it, but
//! for a NaN: the blend gives every NaN as `0x7fc00000` (Metal stores each as `0x7e00`), which the
//! A `half` output's blend stores a `half` in every channel, so no conversion of the device's
//! bears on it, and a `float` one's only by the store's rounding above; for a NaN, the blend gives
//! every NaN as `0x7fc00000` (Metal stores each as `0x7e00`), which the
//! storage image's store converts, Metal's where the profile takes
//! `DriverDeviation::MetalFloatStorageNans` and the device's elsewhere, noted
//! `PrecisionNote::DeviceNanEncoding` (`stage_io::color_write`; ANV stores `0xfe00`). An
@@ -2775,9 +2779,11 @@ type Write = (SValue, SValue, SValue, ImageOperands);
/// invocation's pixel (and sample), inside the interlock, as [`merge`] reads it, and Metal's
/// arithmetic of the output over it in the output's type
/// (`extended_range::blend::blend_half_float`; the blend color from `PushField::HalfBlendColor`
/// where the blend reads it), a `float` result converted to `half` as Metal's blended write
/// converts it: toward zero, the largest finite `half` past it, or to nearest even under
/// `TextureWriteRoundingMode::NearestEven` (`color_writes::HALF`, `HALF_NEAREST`; for the former).
/// where the blend reads it), a `float` result converted to `half` by the storage image's store,
/// the device's conversion (Metal's blended write's, toward zero, the largest finite `half` past
/// it, where the profile takes `DriverDeviation::MetalHalfStorageWrites`), or rounded to nearest
/// even under `TextureWriteRoundingMode::NearestEven` (`color_writes::HALF_NEAREST`), which no
/// measured device's store gives.
/// An output of fewer than four lanes blends as four whose missing lanes are zero, alpha among
/// them, and the result keeps the output's lanes. The channels a write
/// mask keeps are [`merge`]'s to take back from the texel.
@@ -2821,19 +2827,18 @@ fn half_blended(
let s = four_lanes(fb, form, part)?;
let v = extended_range::blend::blend_half_float(fb, &b, arith, (s, d), constant)?;
let v = output_lanes(fb, form, v)?;
if arith == extended_range::blend::BlendArith::Half {
if arith == extended_range::blend::BlendArith::Half || !sc.nearest_even {
// Every NaN as `0x7fc00000`, which the storage image's store converts (a NaN the
// device's arithmetic gave keeps its own sign and payload there; a `float` result's is
// rounded to it below): Metal stores every NaN of the blend as `0x7e00`.
// device's arithmetic gave keeps its own sign and payload there; a `float` result's
// rounded to nearest even is rounded to it below): Metal stores every NaN of the blend as
// `0x7e00`. A `float` result is the device's store's to convert, as Metal's blended write
// converts it toward zero where the profile takes `MetalHalfStorageWrites`.
let f32_form = form.with(Held::Float(FloatFmt::F32));
let nan = fb.unary(UnOp::IsNan, v)?;
let quiet = ops::splat(fb, f32_form, 0x7FC0_0000)?;
return fb.select(nan, quiet, v);
}
let rule = match sc.nearest_even {
true => crate::pipeline::color_writes::HALF_NEAREST,
false => crate::pipeline::color_writes::HALF,
};
let rule = crate::pipeline::color_writes::HALF_NEAREST;
crate::lower::arith::color_write::small_float(fb, form, v, rule)
}
@@ -105,11 +105,7 @@
//! sampler slot whose word states anisotropy, on a device without `samplerAnisotropy`: every
//! Vulkan sampler is isotropic there (`metal::sampler::device_anisotropy`), so the emulation goes
//! where that feature's refusal was, the device's own sampling unchanged where the feature is. A
//! cube's also on a device that samples through Metal's own sampler where its stage's
//! cube-gradient route is not measured (`CubeGradientRoute::Unmeasured`): its explicit levels are
//! Metal's own, which no route alters, so the emulation goes where the refusal of an anisotropic
//! sampler was. A runtime
//! slot's degree is its `SpecKey::SamplerAnisotropy` specialization; where its word states no
//! runtime slot's degree is its `SpecKey::SamplerAnisotropy` specialization; where its word states no
//! anisotropy, the sample is the plain one. Elsewhere (a cube's implicit level, a 3D texture, a
//! comparison, an observed residency, an argument buffer's sampler) the device filters, recorded
//! as `PrecisionNote::DeviceAnisotropicFilter` where the sampler's anisotropy is known (on Metal's
@@ -131,7 +127,6 @@
use crate::air::abi::{Coordinates, MipFilter};
use crate::air::intrinsics::{ImageDim, ImageShape};
use crate::budget::Meter;
use crate::device::profile::CubeGradientRoute;
use crate::error::Error;
use crate::lower::emit::EmitCx;
use crate::lower::select::{NoteOn, NoteTest, SelectCx};
@@ -311,7 +306,7 @@ pub(super) fn select(
cx: &mut SelectCx<'_>,
op: &SampleOp,
(sampler, image, shape): (Option<SamplerRef>, ImageRef, ImageShape),
(integer, observed, other_class, swizzled, answered): (bool, bool, bool, bool, bool),
(integer, observed, other_class, swizzled): (bool, bool, bool, bool),
use_: SamplerUse,
m: &mut Meter,
) -> Result<Option<Anisotropic>, Error> {
@@ -330,14 +325,8 @@ pub(super) fn select(
if integer || !derived {
return Ok(None);
}
// A cube's explicit gradients through a route the device's description does not state take
// the emulation on a device that samples through Metal's own sampler too: its explicit
// levels are Metal's, whatever the route.
let cube = matches!(lod, Lod::CubeGrad(..));
let unmeasured =
cube && cx.profile.fields().cube_gradients.route(cx.stage) == CubeGradientRoute::Unmeasured;
let native = !unmeasured;
if native && anisotropy {
if anisotropy {
cx.families.sampler.device_sampling = true;
if let Some(SamplerRef::Constexpr(words)) = sampler {
if own_not_mipmapped(words, use_, cx.profile)? {
@@ -350,18 +339,10 @@ pub(super) fn select(
let (degree, mip, device) = match sampler {
Some(SamplerRef::Constexpr(words)) => {
let state = super::constexpr::state_of(words)?;
// An isotropic sampler's cube takes Metal's level where no exact path of its own
// answers the sample, on a device whose own sampler does not answer it.
let isotropic = state.max_anisotropy <= 1;
if (isotropic && (native || !cube || answered))
|| state.coordinates == Coordinates::Pixel
{
if state.max_anisotropy <= 1 || state.coordinates == Coordinates::Pixel {
return Ok(None);
}
let la = match isotropic {
true => 0,
false => state.max_anisotropy.next_power_of_two().trailing_zeros(),
};
let la = state.max_anisotropy.next_power_of_two().trailing_zeros();
let device = super::constexpr::constexpr_desc(words, use_, cx.profile)?
.max_anisotropy
.is_some();
@@ -399,8 +380,6 @@ pub(super) fn select(
false => PrecisionNote::DeviceAnisotropicFilter,
};
match degree {
// An isotropic sampler's cube: Metal's level, each level the device's filter.
Degree::Const(0) => {}
Degree::Const(_) => {
cx.precision.insert(note);
}
@@ -773,16 +752,7 @@ fn emulate(
Degree::Const(la) => 1 << la.min(MOST_LOG as u32),
Degree::Slot(_) => MOST_TAPS,
};
// An isotropic sampler's (a cube's): one tap, at Metal's level alone.
let isotropic = a.degree == Degree::Const(0);
filtered(
cx,
fb,
(source, lanes),
&at,
(la, mip, minified),
(most, isotropic),
)
filtered(cx, fb, (source, lanes), &at, (la, mip, minified), most)
}
/// What a sample's emulation reads, taken in the sample's own position.
@@ -927,7 +897,7 @@ fn word_minified_level(
}
/// The emulation's sum of the device's texels of `source` (its coordinate of `lanes` plane lanes):
/// the footprint, then up to `most` taps; an `isotropic` sampler's level alone and its one tap.
/// the footprint, then up to `most` taps.
/// `minified` is the level handed for level 0 where Metal minifies under a nearest mip filter or
/// none ([`minified_level`]).
fn filtered(
@@ -936,7 +906,7 @@ fn filtered(
src: (Source, u8),
at: &At,
(la, mip, minified): (SValue, SValue, SValue),
(most, isotropic): (u32, bool),
most: u32,
) -> BResult<SValue> {
let f = float(fb)?;
let v2 = fb.module().ty(SType::Vector { elem: f, len: 2 })?;
@@ -944,7 +914,7 @@ fn filtered(
let texels = fb.convert(ConvOp::ConvertUToF, plane, v2)?;
let gx = fb.binary(BinOp::FMul, at.grads.0, texels)?;
let gy = fb.binary(BinOp::FMul, at.grads.1, texels)?;
let foot = footprint(fb, (gx, gy), (la, mip), at.levels, isotropic)?;
let foot = footprint(fb, (gx, gy), (la, mip), at.levels)?;
let levels = read_levels(fb, &foot, at, (mip, minified))?;
// The taps' weights: `floor(256 / n)` each, the remainder one each to the middle taps.
let n = foot.n;
@@ -1032,14 +1002,12 @@ struct Footprint {
}
/// Metal's footprint of gradients `gx`, `gy` (level-0 texels) through a sampler of degree `2^la`
/// (`i32`) and mip filter code `mip` (`u32`) on a texture of `levels` (`u32`) levels; an
/// `isotropic` sampler's level is its major axis's alone (`la` 0), its one tap at the centre.
/// (`i32`) and mip filter code `mip` (`u32`) on a texture of `levels` (`u32`) levels.
fn footprint(
fb: &mut FunctionBuilder<'_>,
(gx, gy): (SValue, SValue),
(la, mip): (SValue, SValue),
levels: SValue,
isotropic: bool,
) -> BResult<Footprint> {
let f = float(fb)?;
let i = int(fb)?;
@@ -1067,25 +1035,6 @@ fn footprint(
let fifteen = i32c(fb, 15)?;
let zi = i32c(fb, 0)?;
let one = i32c(fb, 1)?;
// An isotropic sampler's level: its major axis's (an isotropic cube's measured on the Apple
// M3 Max under macOS 27, `emit::cube_footprint`'s `Length` form, which hands Metal the major
// axis alone, reading as Metal's own gradients on every lane).
if isotropic {
let raw = fb.binary(BinOp::ShiftRightArithmetic, vmaj, fifteen)?;
let last = fb.convert(ConvOp::Bitcast, levels, i)?;
let last = fb.binary(BinOp::ISub, last, one)?;
let last = fb.glsl(GlslOp::SMax, &[last, zi])?;
let full = i32c(fb, 256)?;
let top = fb.binary(BinOp::IMul, last, full)?;
let lambda = fb.glsl(GlslOp::SClamp, &[raw, zi, top])?;
return Ok(Footprint {
lambda,
raw,
n: one,
u,
s0: zf,
});
}
// The determinant of the gradients, each component's mantissa truncated to 12 bits, rounded
// as written (no contraction).
let component = |fb: &mut FunctionBuilder<'_>, v: SValue, c: u32| -> BResult<SValue> {
@@ -707,14 +707,14 @@ fn unmeasured_moltenvk() -> DeviceProfile {
}
/// A cube's explicit gradients through a constexpr sampler of `maxAnisotropy` 8 under a linear
/// mip filter take Metal's footprint in the shader on every device without `samplerAnisotropy`,
/// and on MoltenVK where its kernel cube-gradient route is not measured: Metal's level and taps
/// (no gradient sample, the level count queried, tap 0 and the loop's tap of two explicit levels
/// each, `AnisotropicFilter` recorded and `CubeGradientFootprint` not). Through an isotropic
/// sampler the unmeasured route alone takes Metal's level and its one tap (two explicit levels, no
/// loop, neither note), where the refusal was; a device without the feature keeps its own gradient
/// sample there, at the footprint the cube's form hands it. On a measured route (`moltenvk-m3`, whose kernels hand Metal's own gradients) the
/// device's gradient sample stays, unrecorded.
/// mip filter take Metal's footprint in the shader on every device without `samplerAnisotropy`:
/// Metal's level and taps (no gradient sample, the level count queried, tap 0 and the loop's tap
/// of two explicit levels each, `AnisotropicFilter` recorded and `CubeGradientFootprint` not).
/// Through an isotropic sampler a device without the feature keeps its own gradient sample, at the
/// footprint the cube's form hands it. On a measured route (`moltenvk-m3`, whose kernels hand
/// Metal's own gradients) the device's gradient sample stays, unrecorded; on MoltenVK where its
/// kernel route is not measured it stays too, Vulkan's rule's form, recorded as
/// `CubeGradientFootprint`.
#[test]
fn a_cubes_explicit_gradients_take_metals_level_and_taps() {
const GRAD: u32 = 0x4;
@@ -727,8 +727,11 @@ fn a_cubes_explicit_gradients_take_metals_level_and_taps() {
return;
};
let explicit = 2 * if taps { WRITTEN_TAPS as usize } else { 1 };
let mut shader = vec![("unmeasured MoltenVK", unmeasured_moltenvk())];
let mut device = vec![("moltenvk-m3", full("moltenvk-m3"))];
let mut shader = Vec::new();
let mut device = vec![
("moltenvk-m3", full("moltenvk-m3")),
("unmeasured MoltenVK", unmeasured_moltenvk()),
];
for stem in ["lavapipe", "amd-rdna3-radv", "intel-irisxe-anv"] {
match taps {
true => shader.push((stem, p(stem))),
@@ -765,13 +768,20 @@ fn a_cubes_explicit_gradients_take_metals_level_and_taps() {
"{what}: {:?}",
a.precision
);
// Metal's own sampler on a measured route takes Metal's own gradients.
if stem == "moltenvk-m3" {
assert!(
// Metal's own sampler on a measured route takes Metal's own gradients; on an
// unmeasured one, Vulkan's rule's form, the device's reading.
match stem {
"moltenvk-m3" => assert!(
!a.precision.contains(&PrecisionNote::CubeGradientFootprint),
"{what}: {:?}",
a.precision
);
),
"unmeasured MoltenVK" => assert!(
a.precision.contains(&PrecisionNote::CubeGradientFootprint),
"{what}: {:?}",
a.precision
),
_ => {}
}
}
}
+29 -95
View File
@@ -1,7 +1,7 @@
//! Emission of the sampling strategies.
use crate::lower::emit::EmitCx;
use crate::lower::texture::half::{HalfForm, TexelOrigin};
use crate::lower::texture::half::TexelOrigin;
use crate::lower::texture::{
half_class, heap_element, held_texel, live_or_zero, resident_access, sparse_spec, tile_map,
tiled_word, with_word, ImageRef,
@@ -939,20 +939,17 @@ pub(super) fn sampled_value(
}
// Metal's footprint: the device's plain sample or gather, and the word of exactly the texels
// Metal counts, through the slot's sparse arm or tile map.
let exact = match (arm, s.footprint) {
(Some((spec, binding)), Some(fp)) => {
let probe = match tiled {
Some(map) => super::footprint::Probe::Tiled(map),
None => super::footprint::Probe::Sparse,
};
Some((spec, binding, fp, probe))
let exact = match (arm, s.footprint, tiled) {
(Some((spec, binding)), Some(fp), Some(map)) => Some((spec, binding, fp, map)),
(Some(_), Some(_), None) => {
return Err(cx.fail("Metal's footprint on a slot without a tile map"))
}
_ => None,
};
let arm = if exact.is_some() { None } else { arm };
if let SampleOp::PixelFetch { offset } = &s.op {
let (x, word) = pixel_fetch(cx, fb, s, si, image, offset.as_ref(), arm)?;
let x = unmapped_value(cx, fb, s, x, word.map(Named::Word))?;
let x = unmapped_value(cx, fb, s, x, word)?;
let x = live_or_zero(fb, live, x)?;
return texel_value(cx, fb, s, image, (x, TexelOrigin::Image), word);
}
@@ -1163,54 +1160,30 @@ pub(super) fn sampled_value(
return Err(cx.fail("a fetching sample or level query past its own path"))
}
};
let (word, named) = match exact {
Some((spec, binding, fp, probe)) => {
let word = match exact {
Some((spec, binding, fp, map)) => {
let site = super::footprint::Site {
binding,
coord: plane,
lanes: s.lanes,
layer,
};
let counted = super::footprint::word(cx, fb, fp, spec, probe, site)?;
// The texels a nearest sample or a gather of Metal's footprint names.
let named = match fp.kind {
super::footprint::Kind::Nearest => Some(Named::Word(counted.word)),
super::footprint::Kind::Gather => {
let mut taps = [counted.word; 4];
for (tap, k) in taps.iter_mut().zip(super::footprint::GATHER_TEXELS) {
let Some(&r) = counted.resident.get(k) else {
return Err(cx.fail("a gather's footprint without its four texels"));
};
*tap = r;
}
Some(Named::Taps(taps))
}
super::footprint::Kind::Linear => None,
};
(Some(counted.word), named)
Some(super::footprint::word(cx, fb, fp, spec, map, site)?)
}
None => (word, None),
None => word,
};
// Metal's value of texels in a sparse image's block that holds no mapped tile.
let texel = unmapped_value(cx, fb, s, texel, named)?;
let texel = live_or_zero(fb, live, texel)?;
texel_value(cx, fb, s, image, (texel, TexelOrigin::Image), word)
}
/// The plane coordinate of `s`, read from the AIR operand with a subnormal lane of a border axis
/// flushed to the zero of its sign, as Metal's texture unit reads it
/// (`position::subnormal_flush`). Every path that reads the coordinate of a sampling takes it
/// here, so the emulations and the device's own sampler alike are handed Metal's coordinate.
/// The plane coordinate of `s`, read from the AIR operand as given: the device's sampler, and an
/// emulation's arithmetic, read a subnormal coordinate as the device does.
pub(super) fn plane_coord(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
s: &Sampling,
) -> BResult<SValue> {
let coord = cx.operand(fb, s.coord)?;
match s.flush_subnormals {
0 => Ok(coord),
axes => super::position::emit_flush(fb, coord, s.lanes, axes),
}
cx.operand(fb, s.coord)
}
/// The plane coordinate of `s` and its explicit gradients, read from the AIR operands: a cube's
@@ -2041,52 +2014,30 @@ fn pixel_fetch(
Ok((x, word))
}
/// The texels an access names whose residency it reads.
#[derive(Clone, Copy)]
enum Named {
/// Its one texel, unmapped where its status word (a `u32`) is not 0.
Word(SValue),
/// A gather's four taps, in its lanes' order, each resident where its `bool` holds.
Taps([SValue; 4]),
}
/// `x`, the device's four-lane value of access `s`, with zero for each texel `named` says is
/// unmapped under [`Unmapped::Named`]: Metal reads zero memory there, where a block of a sparse
/// image that holds no mapped tile reads the device's value. The lanes the format lacks take their
/// constants after the held texel's conversion ([`held_constants`]).
/// `x`, the device's four-lane value of pixel fetch `s`, zero where its status word `word` (a
/// `u32`) says its texel is unmapped under [`Unmapped::Named`]: Metal reads zero memory there,
/// where a block of a sparse image that holds no mapped tile reads the device's value. The lanes
/// the format lacks take their constants after the held texel's conversion ([`held_constants`]).
fn unmapped_value(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
s: &Sampling,
x: SValue,
named: Option<Named>,
word: Option<SValue>,
) -> BResult<SValue> {
if s.unmapped != Unmapped::Named {
return Ok(x);
}
match named {
Some(Named::Word(word)) => {
let zero = fb.u32_const(0)?;
let zero = fb.module().const_value(zero)?;
let kept = fb.binary(BinOp::IEqual, word, zero)?;
let ty = fb.value_ty(x)?;
let null = fb.module().constant(Constant::Null { ty })?;
let null = fb.module().const_value(null)?;
fb.select(kept, x, null)
}
Some(Named::Taps(taps)) => {
let (ty, elem) = four_lanes(cx, fb, x)?;
let null = fb.module().constant(Constant::Null { ty: elem })?;
let null = fb.module().const_value(null)?;
let mut lanes = Vec::with_capacity(4);
for (lane, resident) in (0u32..).zip(taps) {
let v = fb.composite_extract(x, &[lane])?;
lanes.push(fb.select(resident, v, null)?);
}
fb.composite_construct(ty, &lanes)
}
None => Err(cx.fail("an access that names its texels without their residency")),
}
let Some(word) = word else {
return Err(cx.fail("an access that names its texel without its residency"));
};
let zero = fb.u32_const(0)?;
let zero = fb.module().const_value(zero)?;
let kept = fb.binary(BinOp::IEqual, word, zero)?;
let ty = fb.value_ty(x)?;
let null = fb.module().constant(Constant::Null { ty })?;
let null = fb.module().const_value(null)?;
fb.select(kept, x, null)
}
/// `held`, the held texel of access `s`, with the lanes Metal reads as constants set to them
@@ -2113,19 +2064,6 @@ pub(super) fn held_constants(
crate::lower::texture::constant_lanes(cx, fb, key.texture, held, gathered)
}
/// The four-lane vector type of `x` and its element type.
fn four_lanes(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
x: SValue,
) -> BResult<(TypeId, TypeId)> {
let ty = fb.value_ty(x)?;
match fb.module().types().get(ty)? {
SType::Vector { elem, len: 4 } => Ok((ty, *elem)),
_ => Err(cx.fail("a texel that is not four lanes")),
}
}
/// The sampling result of image texel `texel`: the held texel ([`held_value`]) with the lanes
/// Metal reads as constants set ([`held_constants`]), as `{T, i8}` where the result is one, with
/// status word `word` (the sparse arm's; 0 where none is given, Metal's for a resident access).
@@ -2186,12 +2124,8 @@ pub(super) fn held_value(
};
Ok(match half {
Some(h) => {
let access = match s.op {
SampleOp::Gather { .. } => HalfForm::Read,
_ => HalfForm::Sample,
};
let lanes = sample_lanes(cx, fb, s)?;
h.convert(fb, texel, (access, lanes), origin)?
h.convert(fb, texel, lanes, origin)?
}
None => held_texel(fb, image.texel, form, texel)?,
})
@@ -7,7 +7,7 @@ use super::kernel_on;
use crate::device::profile::DriverWorkaround;
use crate::device::DevicePolicy;
use crate::lower::sampler::bicubic::routines;
use crate::lower::texture::half::{self, HalfFamilies};
use crate::lower::texture::half;
use crate::pipeline::testing::profile;
use crate::spirv::builder::ModuleBuilder;
use crate::spirv::serialize::serialize_for;
@@ -34,7 +34,7 @@ fn controls(words: &[u32]) -> Vec<u32> {
#[test]
fn the_sampling_routines_are_declared_dont_inline_where_every_call_is_inlined() {
let mut b = ModuleBuilder::new();
half::define(&mut b, HalfFamilies::Every).expect("half texel");
half::define(&mut b).expect("half texel");
routines::define_plane(&mut b).expect("plane");
routines::define_line(&mut b).expect("line");
routines::define_quad(&mut b).expect("quad");
@@ -18,19 +18,20 @@
//!
//! A clamp-to-edge axis reads the texel clamped into the level, which counts; a clamp-to-zero or
//! clamp-to-border axis's texel outside the level is the border, which is no texel (Metal answers
//! resident across it; fd292944 measured both modes). [`of`] states where the rule decides the footprint: a constexpr normalized sampler, no
//! comparison or anisotropy (a lowered sampler's reduction is the weighted average), one filter for
//! minification and magnification, clamp addressing, level 0 (the sampler not mipmapped, or a
//! level-0 sample whose sampler neither biases nor clamps the level), and no texel offset.
//! Elsewhere (a runtime sampler, mip levels, repeat or mirrored addressing, an offset, none of them
//! measured) the footprint is the device's, as before.
//! resident across it; fd292944 measured both modes). [`of`] states where the rule decides the
//! footprint: a constexpr normalized sampler, no comparison or anisotropy (a lowered sampler's
//! reduction is the weighted average), one filter for minification and magnification, clamp
//! addressing, level 0 (the sampler not mipmapped, or a level-0 sample whose sampler neither
//! biases nor clamps the level), and no texel offset. Elsewhere (a runtime sampler, mip levels,
//! repeat or mirrored addressing, an offset, none of them measured) no tile map answers the
//! access. The rule is the residency of a device without residency code of its own (no
//! `shaderResourceResidency`), whose slot's tile map answers it; a device with it answers a
//! sample's or gather's residency itself (its `OpImageSparse*` word,
//! `PrecisionNote::SparseResidency`), and selection asks for no rule there.
//!
//! [`word`] emits the status word of such an access: the residency of each counted texel at
//! level 0, through the slot's sparse arm (`OpImageSparseFetch` of the texel) or its tile map,
//! under the slot's `SparseTexture` specialization, and the residency of each texel; the sample
//! itself is the device's plain sample. Where the bound texture is a sparse image, a nearest
//! sample's or a gather's texel that is not resident then reads zero, Metal's unmapped value,
//! before the slot's constant lanes are set (`emit::unmapped_value`).
//! level 0, through the slot's tile map, under the slot's `SparseTexture` specialization, and the
//! residency of each texel; the sample itself is the device's plain sample.
use crate::air::abi::SamplerState;
use crate::air::abi::{AddressMode, Coordinates, Filter, MipFilter};
@@ -43,7 +44,7 @@ use crate::spirv::builder::FunctionBuilder;
use crate::spirv::error::BResult;
use crate::spirv::ids::Value as SValue;
use crate::spirv::ir::{
BinOp, ConstBits, Constant, ConvOp, GlslOp, ImageOperands, ImageQuery, Type as SType, UnOp,
BinOp, ConstBits, Constant, ConvOp, GlslOp, ImageQuery, Type as SType, UnOp,
};
use super::{Lod, SampleOp};
@@ -141,14 +142,6 @@ pub fn of(
Some(Footprint { kind, axes, border })
}
/// Where an access reads a texel's residency: the slot's sparse arm (the combined binding's
/// variable, a fetch of the texel), or its tile map.
#[derive(Clone, Copy, Debug)]
pub enum Probe {
Sparse,
Tiled(View),
}
/// Whether an axis's `i0 + 1` is in the footprint.
#[derive(Clone, Copy)]
enum Second {
@@ -289,85 +282,43 @@ pub struct Site {
pub layer: Option<SValue>,
}
/// The status word of a sample or gather and the residency of its texels ([`counted`]).
pub struct Counted {
/// The status word (a `u32`): 1 where a texel Metal counts is not resident, else 0.
pub word: SValue,
/// Per texel of the footprint, in [`Footprint::texels`]' order, whether it is resident as
/// far as the word goes (a `bool`): a texel that does not count (its weight 0, or the
/// border) is.
pub resident: Vec<SValue>,
}
impl Footprint {
/// The texels of the footprint, each a combination of each axis's texels: bit `a` of a
/// combination picks axis `a`'s `i0 + 1` over its `i0`. A nearest filter reads combination 0
/// alone; a linear filter and a gather read every one, a 2D gather's taps `x`, `y`, `z` and
/// `w` (`(i0, j0 + 1)`, `(i0 + 1, j0 + 1)`, `(i0 + 1, j0)`, `(i0, j0)`) its combinations 2,
/// 3, 1 and 0 ([`GATHER_TEXELS`]).
pub fn texels(&self) -> usize {
match self.kind {
Kind::Nearest => 1,
Kind::Linear | Kind::Gather => 1 << self.axes,
}
}
}
/// The combination ([`Footprint::texels`]) of each tap of a 2D gather, in its lanes' order.
pub const GATHER_TEXELS: [usize; 4] = [2, 3, 1, 0];
/// The status word of a sample or gather with footprint `fp` at `site`, on a slot whose
/// `SparseTexture` specialization is `spec`, and the residency of each of its texels:
/// [`counted`]'s where the bound texture is sparse, and 0 and every texel resident where it is
/// not.
/// `SparseTexture` specialization is `spec` and whose tile map is `map`: [`counted`]'s where the
/// bound texture is sparse, and 0 where it is not.
pub fn word(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
fp: Footprint,
spec: SValue,
probe: Probe,
map: View,
site: Site,
) -> BResult<Counted> {
let n = fp.texels();
) -> BResult<SValue> {
let sparse: ArmFn<'_, ()> = Box::new(move |fb, _| {
let c = counted(fb, fp, probe, site)?;
Ok(ArmEnd::FallThrough(
std::iter::once(c.word).chain(c.resident).collect(),
))
let word = counted(fb, fp, map, site)?;
Ok(ArmEnd::FallThrough(vec![word]))
});
let plain: ArmFn<'_, ()> = Box::new(move |fb, _| {
let word = u32_const(fb, 0)?;
let b = fb.module().ty(SType::Bool)?;
let yes = fb.module().constant(Constant::Scalar {
ty: b,
bits: ConstBits(1),
})?;
let yes = fb.module().const_value(yes)?;
Ok(ArmEnd::FallThrough(
std::iter::once(word)
.chain(std::iter::repeat_n(yes, n))
.collect(),
))
Ok(ArmEnd::FallThrough(vec![word]))
});
let Merged(merged) = fb.if_(&mut (), spec, sparse, Some(plain))?;
match merged.split_first() {
Some((&word, resident)) if resident.len() == n => Ok(Counted {
word,
resident: resident.to_vec(),
}),
_ => Err(cx.fail("a footprint arm without its word and texels")),
match merged[..] {
[word] => Ok(word),
_ => Err(cx.fail("a footprint arm without its word")),
}
}
/// The status word (a `u32`) of a sample or gather of a sparse texture with footprint `fp` at
/// `site`: 1 where a texel Metal counts is not resident at level 0, read through `probe`, else 0;
/// and the residency of each texel of the footprint ([`Counted::resident`]).
/// `site`: 1 where a texel Metal counts is not resident at level 0, read through tile map `map`,
/// else 0. The footprint's texels are each a combination of each axis's texels: bit `a` of a
/// combination picks axis `a`'s `i0 + 1` over its `i0`; a nearest filter reads combination 0
/// alone, a linear filter and a gather every one.
pub fn counted(
fb: &mut FunctionBuilder<'_>,
fp: Footprint,
probe: Probe,
map: View,
site: Site,
) -> BResult<Counted> {
) -> BResult<SValue> {
let Site {
binding,
coord,
@@ -396,16 +347,13 @@ pub fn counted(
};
// Each axis's texels, once: `i0`, and `i0 + 1` where the footprint has it, each clamped into
// the level, with whether it counts (its weight is not 0, and it is not the border).
let tiles = match probe {
Probe::Tiled(map) => Some(TileLevel::new(fb, map, zero, slice.unwrap_or(zero))?),
Probe::Sparse => None,
};
let tiles = TileLevel::new(fb, map, zero, slice.unwrap_or(zero))?;
let mut picks: Vec<Vec<Pick>> = Vec::with_capacity(axes.len());
for (a, ax) in axes.iter().enumerate() {
let border = fp.border.get(a).copied().unwrap_or(false);
let mut both = Vec::with_capacity(2);
let (t, inside) = texel(fb, ax.i0, ax.size, border)?;
both.push(pick(fb, tiles.as_ref(), a, t, inside)?);
both.push(pick(fb, &tiles, a, t, inside)?);
if !matches!(ax.second, Second::No) {
let one = i32_const(fb, 1)?;
let i = fb.binary(BinOp::IAdd, ax.i0, one)?;
@@ -417,19 +365,18 @@ pub fn counted(
(Second::If(weighed), None) => Some(weighed),
(_, inside) => inside,
};
both.push(pick(fb, tiles.as_ref(), a, t, counts)?);
both.push(pick(fb, &tiles, a, t, counts)?);
}
picks.push(both);
}
// A 2D texture's tiles are in its one z tile.
let tz = match &tiles {
Some(l) if picks.len() < 3 => Some(l.tile(fb, 2, zero)?),
_ => None,
let tz = match picks.len() < 3 {
true => Some(tiles.tile(fb, 2, zero)?),
false => None,
};
// Every combination of each axis's texels (bit `a` of `combo` picks axis `a`'s second); a
// combination that picks a second an axis lacks is not in the footprint.
let mut all: Option<SValue> = None;
let mut resident_texels = Vec::with_capacity(fp.texels());
for combo in 0..(1usize << picks.len()) {
let chosen: Option<Vec<Pick>> = picks
.iter()
@@ -445,33 +392,11 @@ pub fn counted(
counts = Some(and(fb, counts, c)?);
}
}
let resident = match (&tiles, probe) {
(Some(l), _) => {
let mut at = [tz.unwrap_or(zero); 3];
for (slot, p) in at.iter_mut().zip(&chosen) {
*slot = p.tile.unwrap_or(zero);
}
l.mapped(fb, at)?
}
(None, _) => {
let u = fb.module().ty(SType::Int {
width: 32,
signed: false,
})?;
let mut parts: Vec<SValue> = chosen.iter().map(|p| p.texel).collect();
parts.extend(slice);
let n = u8::try_from(parts.len()).unwrap_or(u8::MAX);
let ty = fb.module().ty(SType::Vector { elem: u, len: n })?;
let at = fb.composite_construct(ty, &parts)?;
let ops = ImageOperands {
lod: Some(zero),
..ImageOperands::default()
};
let r = fb.sparse_fetch(img, at, &ops)?;
let code = fb.composite_extract(r, &[0])?;
fb.texels_resident(code)?
}
};
let mut at = [tz.unwrap_or(zero); 3];
for (slot, p) in at.iter_mut().zip(&chosen) {
*slot = p.tile;
}
let resident = tiles.mapped(fb, at)?;
// A texel that does not count is resident as far as the word goes.
let ok = match counts {
Some(c) => {
@@ -481,43 +406,32 @@ pub fn counted(
None => resident,
};
all = Some(and(fb, all, ok)?);
resident_texels.push(ok);
}
// Combination 0 (every axis's `i0`) is always in the footprint, so `all` is set.
let one = u32_const(fb, 1)?;
let word = match all {
Some(all) => fb.select(all, zero, one)?,
None => zero,
};
Ok(Counted {
word,
resident: resident_texels,
})
match all {
Some(all) => fb.select(all, zero, one),
None => Ok(zero),
}
}
/// One texel of an axis of the footprint: its coordinate clamped into the level, its tile under a
/// tile map, and whether it counts (`None`: always).
/// One texel of an axis of the footprint: its tile in the tile map, and whether it counts
/// (`None`: always).
#[derive(Clone, Copy)]
struct Pick {
texel: SValue,
tile: Option<SValue>,
tile: SValue,
counts: Option<SValue>,
}
fn pick(
fb: &mut FunctionBuilder<'_>,
tiles: Option<&TileLevel>,
tiles: &TileLevel,
axis: usize,
texel: SValue,
counts: Option<SValue>,
) -> BResult<Pick> {
let tile = match tiles {
Some(l) => Some(l.tile(fb, axis, texel)?),
None => None,
};
Ok(Pick {
texel,
tile,
tile: tiles.tile(fb, axis, texel)?,
counts,
})
}
@@ -10,7 +10,7 @@ use std::collections::BTreeSet;
use crate::spv::ImageFormat;
use super::{counted, Footprint, Kind, Probe, Site};
use super::{counted, Footprint, Kind, Site};
use crate::bind::{SparseTileMap, TileMapping};
use crate::memory::views::{View, ViewKind};
use crate::metal::TextureType;
@@ -74,20 +74,16 @@ fn element(f: &mut FunctionBuilder<'_>, g: GlobalId, i: Value) -> BResult<Value>
f.access_chain(base, &[zero, i])
}
/// Where a kernel reads a texel's residency: texture 0's sparse fetches, or a tile map in buffer 2
/// with tiles of the given texels (x, y, z), made from the image's unmapped texels, which must be
/// whole tiles; the image itself is then resident everywhere, so only the map can answer.
/// Where a kernel reads a texel's residency: a tile map in buffer 2 with tiles of the given texels
/// (x, y, z), made from the image's unmapped texels, which must be whole tiles; the image itself is
/// then resident everywhere, so only the map can answer.
#[derive(Clone, Copy, Debug)]
enum Arm {
Sparse,
Tiled([u32; 3]),
}
struct Arm([u32; 3]);
/// A kernel whose invocation `i` reads `vec4` probe `i` of buffer 0 (the coordinate in its first
/// `axes` lanes; the layer, as a float, in lane 3 of an array) and writes the word of `fp` at it,
/// through texture 0's sparse fetches or, where `tiled`, buffer 2's tile map, to `uint` element
/// `i` of buffer 1.
fn kernel(fp: Footprint, dim: Dim, arrayed: bool, tiled: bool) -> BResult<TypedModule> {
/// through buffer 2's tile map, to `uint` element `i` of buffer 1.
fn kernel(fp: Footprint, dim: Dim, arrayed: bool) -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let f32_ = b.ty(Type::Float { width: 32 })?;
let u32_ = b.ty(Type::Int {
@@ -109,15 +105,11 @@ fn kernel(fp: Footprint, dim: Dim, arrayed: bool, tiled: bool) -> BResult<TypedM
let texture = b.resource(combined(), StorageClass::UniformConstant, sampled)?;
let probes = storage_buffer(&mut b, 0, vec4, 16)?;
let words = storage_buffer(&mut b, 1, u32_, 4)?;
let probe = if tiled {
let map = storage_buffer(&mut b, 2, u32_, 4)?;
Probe::Tiled(View {
global: map,
kind: ViewKind::Storage,
u32_ty: u32_,
})
} else {
Probe::Sparse
let map = storage_buffer(&mut b, 2, u32_, 4)?;
let map = View {
global: map,
kind: ViewKind::Storage,
u32_ty: u32_,
};
let id = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
@@ -142,7 +134,7 @@ fn kernel(fp: Footprint, dim: Dim, arrayed: bool, tiled: bool) -> BResult<TypedM
lanes,
layer,
};
let word = counted(&mut f, fp, probe, site)?.word;
let word = counted(&mut f, fp, map, site)?;
let out = element(&mut f, words, i)?;
f.store(out, word, MemAccess::default())?;
f.ret(None)?;
@@ -234,7 +226,7 @@ fn words(
probes: &[[f32; 4]],
arm: Arm,
) -> Vec<u32> {
let m = kernel(fp, dim, arrayed, matches!(arm, Arm::Tiled(_))).expect("kernel");
let m = kernel(fp, dim, arrayed).expect("kernel");
let bytes: Vec<u8> = probes
.iter()
.flat_map(|p| p.iter().flat_map(|x| x.to_le_bytes()))
@@ -252,14 +244,13 @@ fn words(
bytes: vec![0xAB; probes.len() * 4],
},
];
if let Arm::Tiled(tile) = arm {
buffers.push(Buffer {
slot: Some(slot(ResourceKind::Buffer, 2)),
address: None,
bytes: tile_map(dim, arrayed, &img, tile).to_bytes(),
});
img.unmapped.clear();
}
let Arm(tile) = arm;
buffers.push(Buffer {
slot: Some(slot(ResourceKind::Buffer, 2)),
address: None,
bytes: tile_map(dim, arrayed, &img, tile).to_bytes(),
});
img.unmapped.clear();
let res = Resources {
buffers,
..Resources::default()
@@ -426,9 +417,7 @@ const MIDDLE_384: &[Reading] = &[
];
fn check(width: u32, mapped: std::ops::Range<u32>, border: bool, readings: &[Reading]) {
for arm in [Arm::Sparse, Arm::Tiled([64, 64, 1])] {
check_arm(width, mapped.clone(), border, readings, arm);
}
check_arm(width, mapped, border, readings, Arm([64, 64, 1]));
}
fn check_arm(
@@ -550,10 +539,7 @@ const VOLUME: &[(Kind, [u32; 3], bool)] = &[
#[test]
fn the_footprint_word_answers_metal_along_a_volumes_depth() {
let mut seen = 0;
for (arm, kind) in [Arm::Sparse, Arm::Tiled([64, 64, 1])]
.into_iter()
.flat_map(|arm| [(arm, L), (arm, N)])
{
for (arm, kind) in [(Arm([64, 64, 1]), L), (Arm([64, 64, 1]), N)] {
let rows: Vec<_> = VOLUME.iter().filter(|r| r.0 == kind).collect();
let probes: Vec<[f32; 4]> = rows
.iter()
@@ -569,7 +555,7 @@ fn the_footprint_word_answers_metal_along_a_volumes_depth() {
}
seen += got.len();
}
assert_eq!(seen, 2 * VOLUME.len());
assert_eq!(seen, VOLUME.len());
}
/// The rule on one axis of `n` texels: the texels counted at `u`, and whether each is inside.
@@ -613,14 +599,8 @@ fn the_footprint_word_applies_the_rule_on_every_axis() {
let mut runs = 0;
// The tile maps' tiles are whole runs of the unmapped texels: 8x8x1 for the 3D texture's
// slices, 1x8x1 for the array's columns.
let arms = [
(Arm::Sparse, Arm::Sparse),
(Arm::Tiled([8, 8, 1]), Arm::Tiled([1, 8, 1])),
];
for ((volume, array), border) in arms
.into_iter()
.flat_map(|arms| [(arms, true), (arms, false)])
{
let (volume, array) = (Arm([8, 8, 1]), Arm([1, 8, 1]));
for border in [true, false] {
for kind in [L, N] {
let probes: Vec<[f32; 4]> = sweep.iter().map(|&w| [0.5, 0.25, w, 0.0]).collect();
let img = image(Dim::D3, [16, 16, 16], 1, |_, _, z, _| {
@@ -44,11 +44,11 @@
//!
//! **A runtime or argument buffer's sampler** holds its clamp as `f32`s, not `half`s (Apple M4 on
//! macOS 27.0.1: all 37,080 lanes of `level(x)` and a kernel's `bias(x)` through eighteen clamps,
//! nearest and linear filters and mip filters). The function does not know the clamp; the
//! `VkSampler` holds it on Metal's grid instead where the sampler takes one filter both ways and no
//! anisotropy (`metal::sampler::clamps_on_grid`): the level a nearest mip filter reads at each
//! bound, or the bound truncated onto sixty-fourths under a linear one. The function reads a
//! nearest mip filter's level within the levels the word's clamp leaves ([`word_level`]).
//! nearest and linear filters and mip filters). The function reads a nearest mip filter's level
//! within the levels the word's clamp leaves ([`word_level`]), and a linear one's from the
//! clamp's minimum on Metal's grid (`SpecKey::SamplerMinLevel`). A sample the device makes is
//! clamped by the device into the `VkSampler`'s clamp, the descriptor's
//! (`metal::sampler::vk_sampler`).
use crate::lower::arith::legal::{FloatFmt, Form, Held};
use crate::lower::arith::texel_round::{self, HalfRounding};
@@ -24,7 +24,6 @@ use crate::air::abi::{Filter, MipFilter, SamplerState};
use crate::error::Error;
use crate::lower::select::{any_of, NoteClause, NoteOn, NoteTest, SelectCx};
use crate::lower::texture::{ImageRef, TexelConv, TexelForm};
use crate::metal::sampler::SamplerWord;
use crate::metal::texel_format::{PackedTexels, TexelFormat};
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::sym::SamplerRef;
@@ -111,22 +110,6 @@ pub(super) fn metal_filtered_ycbcr(cx: &SelectCx<'_>, image: ImageRef) -> Option
})
}
/// Where runtime sampler slot `n`'s word states a sampler that filters: a linear minification or
/// magnification filter, a linear mip filter, or anisotropy, any of which [`unfiltered`]'s single
/// texel of one level excludes.
pub(crate) fn word_filters(n: u32) -> Vec<NoteClause> {
let on = NoteOn::Sampler(n);
any_of(
[
SamplerWord::MIN_LINEAR,
SamplerWord::MAG_LINEAR,
2 << SamplerWord::MIP_FILTER_SHIFT,
SamplerWord::ANISOTROPIC,
]
.map(|bit| NoteTest::differ(on, bit, 0)),
)
}
/// Whether a sample through sampler `s` reads one texel of one level, its value unfiltered:
/// nearest minification and magnification, no mip filter or the nearest level's, and no
/// anisotropy (a lowered sampler's reduction is the weighted average). Any other sampler filters:
+12 -33
View File
@@ -226,37 +226,30 @@ impl FamilyStrategy for SamplerStrategy {
}
/// One combined image-sampler binding of the function, before its texture's numeric type is
/// final: the texture slot index, the sampler, whether it samples with comparison, and whether it
/// samples a cube with explicit gradients in the `Length` form through a sampler that may be
/// anisotropic, on a device whose cube-gradient route is not measured ([`Lod::CubeGrad`], whose
/// sampler is made isotropic for it: `metal::sampler::SamplerUse::cube_gradient`).
/// final: the texture slot index, the sampler, and whether it samples with comparison.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BindingKey {
pub texture: u32,
pub sampler: SamplerRef,
pub compare: bool,
pub cube_gradient: bool,
}
/// One separate heap sampler use: heap group `group` sampled through `sampler`, with comparison or
/// without, with explicit cube gradients or without. Its binding is final once the group's numeric
/// type is ([`finish`]).
/// without. Its binding is final once the group's numeric type is ([`finish`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HeapKey {
pub group: u32,
pub sampler: SamplerRef,
pub compare: bool,
pub cube_gradient: bool,
}
/// One use of an argument buffer's sampler: heap group `group` sampled through a heap sampler
/// handle, with comparison or without, a cube with explicit gradients or not. Its sampler array is
/// final once the group's numeric type is ([`finish`]).
/// handle, with comparison or without. Its sampler array is final once the group's numeric type
/// is ([`finish`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HeapSamplerKey {
pub group: u32,
pub compare: bool,
pub cube_gradient: bool,
}
/// An upper estimate of the SPIR-V words of an argument-buffer sampler's cubic test past its
@@ -357,8 +350,7 @@ pub enum Lod {
pub enum CubeFootprint {
/// Metal's isotropic footprint, through an isotropic constexpr sampler: the Metal length of
/// each gradient's two tangent components, on one tangent, for Vulkan's cube derivative rule
/// (`CubeGradientRoute::Vulkan`); through any sampler on a route not measured, whose sampler
/// is made isotropic for it where it may be anisotropic (`BindingKey::cube_gradient`).
/// (`CubeGradientRoute::Vulkan`).
Length,
/// Metal's anisotropic face gradients through an anisotropic constexpr sampler: each gradient
/// without its normal component, mirrored on the faces Metal mirrors, for Vulkan's rule.
@@ -585,10 +577,6 @@ pub struct Sampling {
/// A gather or nearest sample whose plane coordinate is snapped onto the texels Metal reads
/// ([`position`]).
pub snap: Option<position::Snap>,
/// The plane axes whose coordinate the sample flushes a subnormal of to the zero of its sign
/// before anything reads it, as Metal's texture unit reads it, a bit per axis
/// ([`position::subnormal_flush`]).
pub flush_subnormals: u8,
/// It reads a cube by a direction, whose ties between major axes the device is handed broken
/// as Metal breaks them ([`face`]).
pub cube: bool,
@@ -713,10 +701,9 @@ pub enum Unmapped {
/// others are the device's: an access whose residency the function does not read, a
/// filtered sample, or an access whose texels the device's footprint decides.
Constants,
/// As [`Unmapped::Constants`], after each texel the access reads reads zero where its residency
/// As [`Unmapped::Constants`], after the texel the access reads reads zero where its residency
/// says it is unmapped, Metal's unmapped value (zero memory, its missing channels the
/// constants): a pixel fetch, or a nearest sample or gather of Metal's footprint, whose texels
/// and residency the function names.
/// constants): a pixel fetch, whose texel and residency the function names.
Named,
}
@@ -918,8 +905,7 @@ impl Sampling {
/// filter, an sRGB texel's raw decode, a cube gradient's footprint, an argument buffer's pixel
/// sampler's flagged fetch, a snapped coordinate and the positions of an observed footprint,
/// the lanes Metal reads as constants, a cube direction's broken ties, a runtime pixel
/// sampler's texel centre, a raw heap sample's decode, and a border axis's flush of a subnormal
/// coordinate.
/// sampler's texel centre, and a raw heap sample's decode.
pub fn words(&self) -> u32 {
// A swizzled slot's sampling: its swizzle, and a gather's of each component.
match (self.swizzle, &self.op) {
@@ -1028,11 +1014,7 @@ impl Sampling {
.snap
.as_ref()
.filter(|_| offset.is_some())
.map_or(0, position::Snap::offset_words)
+ match self.flush_subnormals {
0 => 0,
_ => position::FLUSH_WORDS,
};
.map_or(0, position::Snap::offset_words);
let footprint = self
.footprint
.map_or(0, |fp| u32::from(fp.axes) * position::POSITION_WORDS);
@@ -1341,8 +1323,7 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
.shape
.ok_or_else(|| invariant("a sampled texture slot without a shape"))?;
let texel = crate::lower::texture::image_class(cx.inputs, s);
let sampler = CombinedSampler::new(key.sampler, key.compare, texel != TexelClass::Float)
.with_cube_gradient(key.cube_gradient);
let sampler = CombinedSampler::new(key.sampler, key.compare, texel != TexelClass::Float);
if let SamplerRef::Constexpr(words) = key.sampler {
constexpr_desc(words, sampler.sampler_use(), cx.profile)?;
}
@@ -1393,8 +1374,7 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
.filter(|h| h.decl.is_some())
.ok_or_else(|| invariant("a heap sampler of an undeclared heap group"))?;
let texel = h.texel.unwrap_or(TexelClass::Float);
let sampler = CombinedSampler::new(key.sampler, key.compare, texel != TexelClass::Float)
.with_cube_gradient(key.cube_gradient);
let sampler = CombinedSampler::new(key.sampler, key.compare, texel != TexelClass::Float);
// A runtime heap sampler is the sampler bound at its slot, which the binder writes for
// this use.
if let SamplerRef::Constexpr(words) = key.sampler {
@@ -1447,8 +1427,7 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
let texel = h.texel.unwrap_or(TexelClass::Float);
heap_sampler_decls.insert(
*key,
SamplerUse::new(key.compare, texel != TexelClass::Float)
.with_cube_gradient(key.cube_gradient),
SamplerUse::new(key.compare, texel != TexelClass::Float),
);
}
// The bound format's treatment under the bicubic filter.
@@ -82,13 +82,6 @@
//! whose tests (`texture::OffsetBase`) the rule reads; a heap element's access reads none, and
//! records `PrecisionNote::ViewBaseTexelOffset` (the residue there).
//!
//! **A subnormal coordinate** ([`subnormal_flush`]). Apple's texture unit reads a subnormal
//! normalized coordinate as the zero of its sign before the address mode decides (measured on an
//! Apple M3 Max), so a border axis reads texel 0 just outside the level where a device that keeps
//! the subnormal reads the border. The border axes of a constexpr sampler flush it before anything
//! reads it (`emit::plane_coord`), so the emulations and the device's own sampler alike are handed
//! Metal's coordinate; every other address mode reads the same texel either way.
//!
//! **The snapped coordinate** ([`snapped`]). A pixel sampler's coordinate, scaled for the
//! device, reads whichever texels the device's own arithmetic gives near a texel edge. Where
//! Metal's texels follow from the coordinate as given, a snapped axis instead hands the device a
@@ -248,124 +241,6 @@ pub(super) fn address(m: AddressMode) -> TapAddress {
}
}
/// The census words of the subnormal flush ([`subnormal_flush`]): the bitcast, the magnitude, the
/// comparison with each axis's threshold, the sign, the select, and the bitcast back, with their
/// constant vectors.
pub const FLUSH_WORDS: u32 = 56;
/// The plane axes of a sample of `op` on a texture of `shape` through the static sampler `stat`
/// (`None`: an argument buffer's) whose coordinate the module flushes a subnormal of to the zero
/// of its sign before the sample, as a bit per axis ([`emit_flush`]).
///
/// **Metal flushes a subnormal texture coordinate.** Apple's texture unit reads a subnormal
/// normalized coordinate as the zero of its sign before the address mode decides, so a clamping
/// axis that reads the border outside the level reads texel 0 there, where a device that keeps
/// the subnormal reads the border. Measured on an Apple M3 Max (macOS 27.0.1) through a
/// 13x11 `R32Float` texture and constexpr clamp-to-zero samplers: at `-1.1754942e-38`
/// (bits `0x007f_ffff`, the largest subnormal magnitude) and at `-1e-40`, `-1e-42` and
/// `-1e-44` the nearest sample reads texel 0 and the linear one averages it with the border,
/// while at `f32::MIN_POSITIVE` negated (bits `0x0080_0000`) and at every larger magnitude down
/// to `-1.2e-38`, `-1e-30` and `-1e-37` both read the border: the boundary is `f32`'s own
/// subnormal edge, one unit in the last place wide, and not a quantization of the coordinate
/// (two ladders of 40 rungs each walking up to a clamp-to-zero edge from outside it, from
/// `2^-1` down to `2^-40` of a texel, read the border on every rung, which no fixed-point
/// quantum of any width would).
///
/// The flush is emitted where the measurement reaches: a constexpr sampler with normalized
/// coordinates, of a single-sampled 1D, 2D, or 3D texture or array, on each axis the sampler
/// addresses through the border (`clamp_to_zero`, and `clamp_to_border_color`, which the
/// lowering does not distinguish: the border test is the only address decision a subnormal can
/// flip, and the two modes differ only in the border colour). A repeating, mirrored or
/// edge-clamping axis reads texel 0 at a subnormal coordinate with the flush or without it, so
/// none is emitted for one. A cube's coordinate is a direction, a pixel sampler's is in texels,
/// and a runtime or argument buffer's sampler's addressing is not known when the function
/// compiles: none is measured, and none takes the flush.
pub(super) fn subnormal_flush(
stat: Option<(SamplerRef, Coordinates)>,
shape: ImageShape,
) -> Result<u8, Error> {
let Some((SamplerRef::Constexpr(words), Coordinates::Normalized)) = stat else {
return Ok(0);
};
let plane = match (shape.dim, shape.ms) {
(ImageDim::D1, false) => 1,
(ImageDim::D2, false) => 2,
(ImageDim::D3, false) => 3,
_ => return Ok(0),
};
let state = super::state_of(words)?;
let modes = [state.address_s, state.address_t, state.address_r];
let mut axes = 0u8;
for (axis, mode) in modes.into_iter().take(plane).enumerate() {
if address(mode) == TapAddress::Border {
axes |= 1 << axis;
}
}
Ok(axes)
}
/// `coord` (`lanes` floats) with the subnormal lanes of `axes` ([`subnormal_flush`]) replaced by
/// the zero of their sign, as Metal's texture unit reads them.
///
/// The test and the replacement are integer, so a device that flushes subnormals in its own float
/// arithmetic and one that keeps them emit the same answer: a lane whose magnitude bits lie below
/// `f32::MIN_POSITIVE`'s (`0x0080_0000`) becomes its sign bit alone, and every other lane is kept.
/// An axis outside `axes` takes the threshold 0, which no magnitude is below, so it is kept
/// whatever it holds (a zero included, which the replacement would leave unchanged anyway).
pub(super) fn emit_flush(
fb: &mut FunctionBuilder<'_>,
coord: SValue,
lanes: u8,
axes: u8,
) -> BResult<SValue> {
let u32_ = fb.module().ty(SType::Int {
width: 32,
signed: false,
})?;
let float = fb.module().ty(SType::Float { width: 32 })?;
let vector = |fb: &mut FunctionBuilder<'_>, ty, n: u8| match n {
1 => Ok(ty),
n => fb.module().ty(SType::Vector { elem: ty, len: n }),
};
let uvec = vector(fb, u32_, lanes)?;
let fvec = vector(fb, float, lanes)?;
let splat = |fb: &mut FunctionBuilder<'_>, bits: Vec<u32>| -> BResult<SValue> {
let mut parts = Vec::new();
for b in &bits {
let c = fb.module().constant(Constant::Scalar {
ty: u32_,
bits: ConstBits(u64::from(*b)),
})?;
parts.push(c);
}
let c = match parts.as_slice() {
[one] => *one,
many => fb.module().constant(Constant::Composite {
ty: uvec,
parts: many.to_vec().into(),
})?,
};
fb.module().const_value(c)
};
let magnitudes = splat(fb, vec![0x7fff_ffff; usize::from(lanes)])?;
let signs = splat(fb, vec![0x8000_0000; usize::from(lanes)])?;
let thresholds = splat(
fb,
(0..lanes)
.map(|axis| match axes & (1 << axis) {
0 => 0,
_ => 0x0080_0000,
})
.collect(),
)?;
let bits = fb.convert(ConvOp::Bitcast, coord, uvec)?;
let magnitude = fb.binary(BinOp::BitwiseAnd, bits, magnitudes)?;
let small = fb.binary(BinOp::ULessThan, magnitude, thresholds)?;
let sign = fb.binary(BinOp::BitwiseAnd, bits, signs)?;
let flushed = fb.select(small, sign, bits)?;
fb.convert(ConvOp::Bitcast, flushed, fvec)
}
/// The snap of `op` on a texture of `shape` through the static sampler `stat` (`None`: an
/// argument buffer's), where the module docs snap it. A pixel sampler's coordinate is Metal's
/// position as given, which the device's sampler, reading the coordinate over the size, does not
@@ -8,8 +8,6 @@
//! significant bits), and rounds it to `f32` with ties away from zero.
use super::{celled_by_word, gathered_by_word, offset_dropped, position, snapped_axis, AxisSnap};
use crate::air::abi::Coordinates;
use crate::air::intrinsics::ImageDim;
use crate::lower::sampler::bicubic::TapAddress;
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
@@ -1017,235 +1015,3 @@ fn a_runtime_samplers_gather_centres_metals_block_by_its_word() {
}
assert!(checked > 15_000, "{checked}");
}
/// A kernel whose invocation `i` reads the bits of a two-lane coordinate from buffer 0 and writes
/// the bits of [`super::emit_flush`]'s result of `axes` to buffer 1.
fn flush_kernel(axes: u8) -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let f32_ = b.ty(Type::Float { width: 32 })?;
let u32_ = b.ty(Type::Int {
width: 32,
signed: false,
})?;
let fvec2 = b.ty(Type::Vector { elem: f32_, len: 2 })?;
let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?;
let input = storage_buffer(&mut b, 0, u32_)?;
let output = storage_buffer(&mut b, 1, u32_)?;
let id = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let gid = f.module().global_value(id)?;
let gid = f.load(gid, MemAccess::default())?;
let i = f.composite_extract(gid, &[0])?;
let mut lanes = Vec::new();
for lane in 0..2 {
let at = word(&mut f, input, i, 2, lane)?;
let bits = f.load(at, MemAccess::default())?;
lanes.push(f.convert(ConvOp::Bitcast, bits, f32_)?);
}
let coord = f.composite_construct(fvec2, &lanes)?;
let flushed = super::emit_flush(&mut f, coord, 2, axes)?;
for lane in 0..2u32 {
let c = f.composite_extract(flushed, &[lane])?;
let bits = f.convert(ConvOp::Bitcast, c, u32_)?;
let at = word(&mut f, output, i, 2, lane)?;
f.store(at, bits, MemAccess::default())?;
}
f.ret(None)?;
let main = f.finish()?;
b.entry(
ExecModel::GLCompute,
main,
vec![ExecMode::LocalSize { x: 1, y: 1, z: 1 }],
)?;
b.finalize()
}
/// `bits` with a subnormal magnitude replaced by the zero of its sign, Metal's reading of a
/// subnormal texture coordinate.
fn flushed_bits(bits: u32) -> u32 {
match bits & 0x7fff_ffff < 0x0080_0000 {
true => bits & 0x8000_0000,
false => bits,
}
}
/// The flush replaces every subnormal magnitude by the zero of its sign on the axes it names and
/// keeps every other lane and axis exactly, for each of the four masks of two axes. The lanes
/// cover the whole deciding region exhaustively: every subnormal whose significand is a power of
/// two or one off it, of both signs, the two floats either side of `f32::MIN_POSITIVE`, the
/// magnitudes the Metal measurement read (`1e-30`, `1e-37`, `1.2e-38`, `1e-40`, `1e-42`,
/// `1e-44`), both zeros, and normals that must be kept.
#[test]
fn the_flush_reads_a_subnormal_coordinate_as_the_zero_of_its_sign() {
let mut magnitudes: Vec<u32> = Vec::new();
for e in 0..24u32 {
for d in [0u32, 1] {
let one = 1u32 << e;
magnitudes.push(one + d);
magnitudes.push(one.saturating_sub(d));
}
}
magnitudes.extend([
0x0000_0000,
0x007f_ffff,
0x0080_0000,
0x0080_0001,
1.2e-38f32.to_bits(),
1e-30f32.to_bits(),
1e-37f32.to_bits(),
1e-40f32.to_bits(),
1e-42f32.to_bits(),
1e-44f32.to_bits(),
1.0f32.to_bits(),
0.375f32.to_bits(),
f32::MAX.to_bits(),
]);
magnitudes.sort_unstable();
magnitudes.dedup();
let lanes: Vec<u32> = magnitudes
.iter()
.flat_map(|&m| [m, m | 0x8000_0000])
.collect();
let mut checked = 0usize;
for axes in 0..4u8 {
let m = flush_kernel(axes).expect("kernel");
// Each invocation takes one lane on axis 0 and its reverse on axis 1, so both axes see
// every value under every mask.
let pairs: Vec<(u32, u32)> = lanes
.iter()
.copied()
.zip(lanes.iter().rev().copied())
.collect();
let bytes: Vec<u8> = pairs
.iter()
.flat_map(|&(s, t)| [s.to_le_bytes(), t.to_le_bytes()])
.flatten()
.collect();
let res = Resources {
buffers: vec![
Buffer {
slot: Some(slot(0)),
address: None,
bytes,
},
Buffer {
slot: Some(slot(1)),
address: None,
bytes: vec![0xAB; pairs.len() * 8],
},
],
..Resources::default()
};
let cfg = Config {
workgroups: [u32::try_from(pairs.len()).expect("lanes"), 1, 1],
..Config::default()
};
let (out, _) = interp::run_with_images(&m, &cfg, res, Vec::new()).expect("run");
for (&(s, t), got) in pairs.iter().zip(out.buffers[1].as_chunks::<8>().0.iter()) {
let read = |k: usize| u32::from_le_bytes(got[4 * k..4 * k + 4].try_into().unwrap());
for (axis, given) in [(0usize, s), (1, t)] {
let want = match axes & (1 << axis) {
0 => given,
_ => flushed_bits(given),
};
assert_eq!(
read(axis),
want,
"axes {axes:#b} axis {axis} given {given:#010x}"
);
checked += 1;
}
}
}
assert!(checked > 700, "only {checked} lanes checked");
}
/// The plan names exactly the border axes of a constexpr sampler with normalized coordinates, of
/// a single-sampled 1D, 2D or 3D texture or array: a repeating, mirrored or edge-clamping axis,
/// an axis past the texture's dimensions, a pixel sampler, a cube, a multisampled texture and an
/// argument buffer's sampler take no flush.
#[test]
fn the_flush_names_the_border_axes_of_a_constexpr_normalized_sampler() {
use crate::air::abi::{AddressMode as M, SamplerState};
use crate::air::intrinsics::ImageShape;
use crate::lower::sampler::constexpr::state_words;
use crate::pipeline::sym::SamplerRef;
let modes = [
(M::ClampToEdge, false),
(M::Repeat, false),
(M::MirroredRepeat, false),
(M::ClampToZero, true),
(M::ClampToBorder, true),
];
let shape = |dim, array, ms| ImageShape {
dim,
array,
ms,
depth: false,
};
let mut checked = 0usize;
for (s_mode, s_border) in modes {
for (t_mode, t_border) in modes {
for (r_mode, r_border) in modes {
let mut state =
SamplerState::from_words([0, 0]).expect("a decodable sampler state");
state.address_s = s_mode;
state.address_t = t_mode;
state.address_r = r_mode;
let words = state_words(&state);
let constexpr = SamplerRef::Constexpr(words);
let borders = [s_border, t_border, r_border];
let mask = |axes: usize| {
borders
.iter()
.take(axes)
.enumerate()
.fold(0u8, |m, (a, &b)| m | u8::from(b) << a)
};
for (dim, axes) in [(ImageDim::D1, 1usize), (ImageDim::D2, 2), (ImageDim::D3, 3)] {
for array in [false, true] {
let got = super::subnormal_flush(
Some((constexpr, Coordinates::Normalized)),
shape(dim, array, false),
)
.expect("flush");
assert_eq!(got, mask(axes), "{dim:?} array {array} {s_mode:?}");
checked += 1;
}
// A multisampled texture of the same modes takes none.
let ms = super::subnormal_flush(
Some((constexpr, Coordinates::Normalized)),
shape(dim, false, true),
)
.expect("flush");
assert_eq!(ms, 0, "{dim:?} multisampled");
}
// A pixel sampler's coordinate is in texels, a cube's is a direction, and an
// argument buffer's sampler states no mode in the function.
let pixel = super::subnormal_flush(
Some((constexpr, Coordinates::Pixel)),
shape(ImageDim::D2, false, false),
)
.expect("flush");
assert_eq!(pixel, 0, "pixel coordinates");
let cube = super::subnormal_flush(
Some((constexpr, Coordinates::Normalized)),
shape(ImageDim::Cube, false, false),
)
.expect("flush");
assert_eq!(cube, 0, "a cube");
let heap =
super::subnormal_flush(None, shape(ImageDim::D2, false, false)).expect("flush");
assert_eq!(heap, 0, "an argument buffer's sampler");
let slot = super::subnormal_flush(
Some((SamplerRef::Slot(0), Coordinates::Normalized)),
shape(ImageDim::D2, false, false),
)
.expect("flush");
assert_eq!(slot, 0, "a runtime sampler");
}
}
}
assert!(checked > 500, "only {checked} shapes checked");
}
+45 -82
View File
@@ -1825,17 +1825,13 @@ fn select_one(
}
SamplerArg::Static(SamplerRef::Slot(_), _) | SamplerArg::Heap(_) => None,
};
// A route the device's description does not state takes the isotropic form, whose
// length every known route reads alike (but a `y` face's through macOS 27's
// fixup), through every sampler: Metal's footprint emulated replaces it where the
// emulation reaches the sample (`anisotropic::select`), and elsewhere an
// anisotropic sampler is made isotropic for it (`cube_gradient`).
// A route the device's description does not state is Vulkan's rule: the device's
// own reading of the form handed to it (`PrecisionNote::CubeGradientFootprint`).
let route = cx.profile.fields().cube_gradients.route(cx.stage);
let form = match (route, anisotropic) {
(CubeGradientRoute::Metal, _) => CubeFootprint::Metal,
(CubeGradientRoute::AppleProjected, _) => CubeFootprint::Projected,
(CubeGradientRoute::Vulkan, Some(false))
| (CubeGradientRoute::Unmeasured, _) => CubeFootprint::Length,
(CubeGradientRoute::Vulkan, Some(false)) => CubeFootprint::Length,
(CubeGradientRoute::Vulkan, Some(true)) => CubeFootprint::Face,
(CubeGradientRoute::Vulkan, None) => CubeFootprint::Word,
};
@@ -2027,9 +2023,20 @@ fn select_one(
let observed = !matches!(op, SampleOp::Lod { .. } | SampleOp::QueryLevel { .. })
&& crate::lower::texture::residency(cx, at, image)?;
let fetches = matches!(op, SampleOp::Bicubic(_));
// Metal's footprint where its measured rule decides it: a constexpr sampler's.
let sparse_images = cx
.profile
.fields()
.enabled
.features
.contains(&VkFeature::ShaderResourceResidency);
// Metal's footprint where its measured rule decides it, a constexpr sampler's, on a device
// without residency code of its own (no `shaderResourceResidency`), where the slot's tile map
// answers the residency. A device with it answers a sample's or gather's residency itself,
// its `OpImageSparse*` word (`PrecisionNote::SparseResidency`).
let footprint = match (observed, image, sampler) {
(true, ImageRef::Slot(_), SamplerArg::Static(SamplerRef::Constexpr(words), _)) => {
(true, ImageRef::Slot(_), SamplerArg::Static(SamplerRef::Constexpr(words), _))
if !sparse_images =>
{
let state = super::constexpr::state_of(words)?;
super::footprint::of(&state, &op, shape, integer)
}
@@ -2043,26 +2050,18 @@ fn select_one(
// sample's, gather's, or pixel fetch's texels in a block of it that holds no mapped tile read
// the device's non-resident value under either arm (zero only under
// `residencyNonResidentStrict`, and RADV's zero alpha where Metal reads a missing alpha as 1),
// and on the sparse arm a footprint Metal's rule does not decide is the device's. There every
// access of a slot's color texture sets the lanes Metal reads as constants (a channel the
// format lacks, through the swizzle), whether the function reads its residency or not, and one
// whose residency it reads zeroes each texel it names (a pixel fetch, a nearest sample's or a
// gather's of Metal's footprint) where its residency says it is unmapped, Metal's value; a
// filtered sample's lanes that are no constants, and the word and value of an access whose
// footprint the device's filter decides, stay the device's. A bicubic sample's fetches, and a
// level query, take neither. Elsewhere the texture's image holds Metal's unmapped value and its
// tile map answers exactly the texels Metal counts.
let sparse_images = cx
.profile
.fields()
.enabled
.features
.contains(&VkFeature::ShaderResourceResidency);
// and a sample's or gather's footprint and word on the sparse arm are the device's. There
// every access of a slot's color texture sets the lanes Metal reads as constants (a channel the
// format lacks, through the swizzle), whether the function reads its residency or not, and a
// pixel fetch whose residency it reads zeroes its texel where its residency says it is
// unmapped, Metal's value; a sample's or gather's lanes that are no constants, and its word,
// stay the device's. A bicubic sample's fetches, and a level query, take neither. Elsewhere the
// texture's image holds Metal's unmapped value and its tile map answers exactly the texels
// Metal counts.
let texel_op = !matches!(op, SampleOp::Lod { .. } | SampleOp::QueryLevel { .. });
let unmapped = match image {
ImageRef::Slot(index) if sparse_images && texel_op && !fetches && !shape.depth => {
let named_texels = matches!(op, SampleOp::PixelFetch { .. })
|| footprint.is_some_and(|f| f.kind != super::footprint::Kind::Linear);
let named_texels = matches!(op, SampleOp::PixelFetch { .. });
if let Some(s) = cx.families.texture.slots.get_mut(&index) {
s.constant_lanes = true;
let slot = s.slot;
@@ -2087,10 +2086,14 @@ fn select_one(
}
}
let residency = observed && !fetches;
// Every sample and gather goes to the device's sampler: Metal's own on MoltenVK
// (`VkProperty::MetalSampler`), whose decode, filters, and comparisons are Metal's, and the
// device's own elsewhere (`VkProperty::DeviceSampling`), whose answers the module records.
if matches!(op, SampleOp::Sample { .. } | SampleOp::Gather { .. }) {
// Every sample, gather and level query goes to the device's sampler: Metal's own on MoltenVK
// (`VkProperty::MetalSampler`), whose decode, filters, levels and comparisons are Metal's, and
// the device's own elsewhere (`VkProperty::DeviceSampling`), whose answers the module records
// (a level query's level clamped by the device into the sampler's clamp, the descriptor's).
if matches!(
op,
SampleOp::Sample { .. } | SampleOp::Gather { .. } | SampleOp::Lod { .. }
) {
cx.families.sampler.device_sampling = true;
}
// An 8-bit sRGB texture the device reads through its own sRGB view, but under the slot's twin
@@ -2131,10 +2134,6 @@ fn select_one(
// A pixel sampler's gather (or a runtime sampler's, behind its word) and a linear pixel
// sample's footprint cell, snapped onto Metal's texels.
let snap = super::position::plan(cx, &op, stat, (shape, integer))?;
// Metal's texture unit reads a subnormal normalized coordinate as the zero of its sign before
// the address mode decides: the border axes of a constexpr sampler flush it, so the sample
// reads the texel Metal reads there (`position::subnormal_flush`).
let flush_subnormals = super::position::subnormal_flush(stat, shape)?;
if let SamplerArg::Static(SamplerRef::Slot(n), _) = sampler {
if let Some(s) = cx.families.sampler.slots.get_mut(&n) {
match snap.as_ref().map(|p| p.kind) {
@@ -2163,16 +2162,13 @@ fn select_one(
// slot's specialization then reads.
let one_texel = one_texel(&op, sampler, shape.dim == ImageDim::Cube)?;
// On a device that samples through Metal's own texture unit, the `half` routine reads an
// access's lanes only for a YCbCr field's one texel (`half::HalfFamilies::MetalSampler`): no
// sampler word decides them. A slot's texture of a YCbCr format on the grid `8192`
// (`TexelFormat::YCBCR_8192`) then rounds a sample of its one texel to nearest even, where
// Metal rounds it with ties away, noted where it is bound.
// access's lanes only for a YCbCr field's one texel (`texture::half`): no sampler word decides
// them. A slot's texture of a YCbCr format on the grid `8192` (`TexelFormat::YCBCR_8192`) then
// rounds a sample of its one texel to nearest even, where Metal rounds it with ties away,
// noted where it is bound.
let one_texel = match one_texel {
crate::lower::texture::OneTexel::Word(_)
if half
&& !raw
&& crate::lower::texture::half_families(cx)
== crate::lower::texture::half::HalfFamilies::MetalSampler =>
if half && !raw && !crate::lower::texture::device_texels(cx) =>
{
if let ImageRef::Slot(index) = image {
use crate::metal::texel_format::TexelFormat;
@@ -2196,9 +2192,9 @@ fn select_one(
if image.heap() && !shape.depth && !device {
cx.families.texture.heap_half = true;
cx.families.access.heap_class = true;
cx.families.texture.half_families = crate::lower::texture::half_families(cx);
}
crate::lower::texture::half_texels(cx, image, shape, one_texel, device, m)?
let sample = !matches!(op, SampleOp::Gather { .. });
crate::lower::texture::half_texels(cx, image, shape, sample, device, m)?
}
// A `float` texel that may be one texel's is the device's conversion of its codes: not an sRGB
// raw texel's (decoded exactly), a bicubic sample's, or an LOD query's; nor a depth
@@ -2229,35 +2225,12 @@ fn select_one(
}
}
}
// A binding sampling a cube with explicit gradients in the `Length` form through a sampler
// that may be anisotropic (a runtime or argument buffer's, or an anisotropic constexpr one, on
// a device whose route is not measured) makes it isotropic: the device filters the major axis
// the form hands it, Metal's isotropic footprint, where the emulation does not answer the
// sample, and the emulation's taps read explicit levels. An isotropic constexpr sampler's
// binding is the plain one, a sampler's elsewhere its state's or word's, and Metal's own
// gradients are Metal's footprint through any sampler.
let cube_gradient = match &op {
SampleOp::Sample {
lod: Lod::CubeGrad(_, _, form),
..
} => {
*form == CubeFootprint::Length
&& match sampler {
SamplerArg::Static(SamplerRef::Constexpr(words), _) => {
super::state_of(words)?.max_anisotropy > 1
}
SamplerArg::Static(SamplerRef::Slot(_), _) | SamplerArg::Heap(_) => true,
}
}
_ => false,
};
let source = match (image, sampler) {
(ImageRef::Slot(texture), SamplerArg::Static(sampler, _)) => {
let key = BindingKey {
texture,
sampler,
compare,
cube_gradient,
};
cx.families.sampler.combined.insert(key);
Source::Combined(key)
@@ -2267,20 +2240,13 @@ fn select_one(
group,
sampler,
compare,
cube_gradient,
};
cx.families.sampler.heap.insert(key);
Source::Heap { handle, key }
}
// An argument buffer's sampler is read from the sampler array of its use, whose class
// carries the cube-gradient bit, so the plan makes an anisotropic listed state isotropic
// for a cube's explicit gradients in the isotropic form there alone.
// An argument buffer's sampler is read from the sampler array of its use.
(ImageRef::Heap { group, handle }, SamplerArg::Heap(sampler)) => {
let key = HeapSamplerKey {
group,
compare,
cube_gradient,
};
let key = HeapSamplerKey { group, compare };
cx.families.sampler.heap_samplers.insert(key);
cubic_reach(cx);
Source::HeapSampler {
@@ -2334,15 +2300,13 @@ fn select_one(
_ => false,
};
// Metal's anisotropic filter emulated by the device's samples at explicit levels, where it
// reaches the sample; the device's anisotropic filter, recorded, where it does not. An
// isotropic cube's level too, where no exact path of its own answers it.
let answered = snap.is_some() || centred;
// reaches the sample; the device's anisotropic filter, recorded, where it does not.
let anisotropic = super::anisotropic::select(
cx,
&op,
(stat.map(|(r, _)| r), image, shape),
(integer, observed, cross.is_some(), swizzle, answered),
SamplerUse::new(compare, integer).with_cube_gradient(cube_gradient),
(integer, observed, cross.is_some(), swizzle),
SamplerUse::new(compare, integer),
m,
)?;
// A cube's explicit gradients handed to the device in a form other than Metal's own: the
@@ -2388,7 +2352,6 @@ fn select_one(
residency,
footprint,
snap,
flush_subnormals,
cube,
centred,
centre_word,
+3 -10
View File
@@ -1748,13 +1748,11 @@ fn finish(
})
}
/// The constant a [`NoteTest`] reads: a texture slot's `TexelFormat` class or a sampler slot's
/// `SamplerState` word, by the function's slot index, or a texture slot's `UnmeasuredTexels`
/// boolean, or the class of the format bound at a texture slot, which no constant carries
/// (`SpecKey::BoundTexelFormat`).
/// The constant a [`NoteTest`] reads: a sampler slot's `SamplerState` word, by the function's slot
/// index, or a texture slot's `UnmeasuredTexels` boolean, or the class of the format bound at a
/// texture slot, which no constant carries (`SpecKey::BoundTexelFormat`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum NoteOn {
Texel(u32),
Sampler(u32),
Unmeasured(u32),
Bound(u32),
@@ -1824,11 +1822,6 @@ pub(crate) fn any_of(tests: impl IntoIterator<Item = NoteTest>) -> Vec<NoteClaus
/// which the runtime takes from the bound texture.
fn declared(families: &FamilyPlans, t: NoteTest) -> Option<SpecTest> {
let key = match t.on {
NoteOn::Texel(index) => {
let s = families.texture.slots.get(&index)?;
s.declares_texel_format()
.then_some(SpecKey::TexelFormat(s.slot))?
}
NoteOn::Unmeasured(index) => {
let s = families.texture.slots.get(&index)?;
s.unmeasured.then_some(SpecKey::UnmeasuredTexels(s.slot))?
@@ -89,9 +89,13 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) {
.profile
.takes_driver_deviation(DriverDeviation::MetalColorWrites);
let storage = crate::lower::fragment::writes_through_storage(cx, color);
// A storage write the shader blends into a 16-bit float attachment stores the blend's `half`
// in every channel, which the device converts exactly, but for a NaN: no conversion of an
// output variable's bears on it, and its NaN is the storage image's store's ([`storage_nan`]).
// A storage write the shader blends into a 16-bit float attachment stores the blend's result:
// a `half` output's `half` in every channel, which the device converts exactly, and a `float`
// output's `float`, which the storage image's store rounds to `half` as Metal's blended write
// does where the profile takes `DriverDeviation::MetalHalfStorageWrites` (the module requires
// its property), else as the device rounds it (`PrecisionNote::DeviceColorConversion`). No
// conversion of an output variable's bears on it, and its NaN is the storage image's store's
// ([`storage_nan`]).
// One the shader blends into an 8-bit unorm attachment stores the code Metal's unorm rule
// gives the blend's result, which the shader rounds itself (`fetch::unorm8_blended`).
let shader_blended = crate::lower::fragment::blends_in_storage(cx, color);
@@ -104,6 +108,18 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) {
for (slot, rule) in lanes.iter_mut().zip(rules).take(usize::from(f.lanes)) {
let Some(rule) = rule else { continue };
nans |= !shader_blended && color_writes::half_float(rule) && !nan_kept(cx, rule, f);
if sixteen_blended && f.float_fmt() == Some(FloatFmt::F32) {
match cx
.profile
.takes_driver_deviation(DriverDeviation::MetalHalfStorageWrites)
{
true => {
relied.insert(VkProperty::MetalHalfStorageWrites);
}
false => device = true,
}
continue;
}
if metal && rule == color_writes::HALF {
continue;
}
+16 -70
View File
@@ -16,7 +16,7 @@ use crate::spirv::ir::{
MemAccess, MemoryOrder, Scope, Semantics, TexelMemory, Type as SType, UnOp,
};
use super::half::{HalfForm, TexelLanes, TexelOrigin};
use super::half::{TexelLanes, TexelOrigin};
use super::slice::Slice;
use super::{
Coord, ImageDecl, ImageRef, QueryKind, QueryOp, Read, TexelClass, TexelConv, TexelForm,
@@ -924,7 +924,7 @@ fn from_image(
let x = match half {
Some(h) => {
let lanes = TexelLanes::Texel.value(fb)?;
h.convert(fb, x, (HalfForm::Read, lanes), TexelOrigin::Image)?
h.convert(fb, x, lanes, TexelOrigin::Image)?
}
None => x,
};
@@ -1180,16 +1180,16 @@ enum ClassOf {
}
impl HalfClass {
/// The held `half` texel of image texel `x` (a `vec4` of `f32`) under access form `form`,
/// its lanes `lanes` (`half::TexelLanes::code`). An image instruction's texel (`origin`) of a
/// slot that declares `PlainHalfTexels` converts by the plain arm where the specialization
/// holds and by the routine where it does not, one selection construct on it, so
/// specialization keeps one of them (`half` module docs).
/// The held `half` texel of image texel `x` (a `vec4` of `f32`) of lanes `lanes`
/// (`half::TexelLanes::code`). An image instruction's texel (`origin`) of a slot that declares
/// `PlainHalfTexels` converts by the plain arm where the specialization holds and by the
/// routine where it does not, one selection construct on it, so specialization keeps one of
/// them (`half` module docs).
pub(crate) fn convert(
self,
fb: &mut FunctionBuilder<'_>,
x: SValue,
(form, lanes): (HalfForm, SValue),
lanes: SValue,
origin: TexelOrigin,
) -> BResult<SValue> {
let class = match self.class {
@@ -1201,7 +1201,7 @@ impl HalfClass {
let routine = self.routine;
let plain = match (origin, self.plain) {
(TexelOrigin::Image, Some(plain)) => plain,
_ => return super::half::convert(fb, routine, x, class, (form, lanes)),
_ => return super::half::convert(fb, routine, x, class, lanes),
};
let half = Form {
held: Held::Float(FloatFmt::Half),
@@ -1212,7 +1212,7 @@ impl HalfClass {
Ok(ArmEnd::FallThrough(vec![v]))
});
let other: ArmFn<'_, ()> = Box::new(move |fb, _| {
let v = super::half::convert(fb, routine, x, class, (form, lanes))?;
let v = super::half::convert(fb, routine, x, class, lanes)?;
Ok(ArmEnd::FallThrough(vec![v]))
});
let Merged(merged) = fb.if_(&mut (), plain, then, Some(other))?;
@@ -1351,19 +1351,17 @@ pub(crate) fn reinterpret(
/// bits, extended by the format's signedness), which the write then saturates to each
/// channel's range as every Metal integer write does ([`saturated`]);
/// - into a float format, a 32-bit lane's bits as a `float`, a 16-bit lane's as a `half`, which
/// the float class then writes as a `float` or `half` texel, but rounded to nearest even onto
/// a half-float channel (a finite value past 65504 to the infinity) and onto a small-float
/// channel (`RG11B10Float`, held at its largest finite value), where Metal's integer store
/// rounds so and a `float` one toward zero.
/// the float class then writes as a `float` or `half` texel, the device's store converting a
/// `float` onto a half-float or small-float channel (`RG11B10Float`) as it converts every
/// `float` write, where Metal's integer store rounds to nearest even
/// (`PrecisionNote::DeviceColorConversion`, `texture::half_storage_facts`).
pub(crate) fn cross_write(
fb: &mut FunctionBuilder<'_>,
c: super::CrossWrite,
native: TexelForm,
v: SValue,
) -> BResult<SValue> {
use crate::lower::arith::color_write;
use crate::lower::arith::legal::{FloatFmt, Form, Held};
use crate::vk::{Format as F, NumericFormat as N};
use crate::vk::NumericFormat as N;
let n = native.lanes;
let malformed =
|| crate::spirv::error::BuildError::Type(crate::spirv::error::TypeRule::FunctionSignature);
@@ -1415,17 +1413,7 @@ pub(crate) fn cross_write(
TexelConv::I16 { .. } => narrow::from_bits(fb, half.half(), v)?,
_ => return Err(malformed()),
};
let f = Form {
held: Held::Float(FloatFmt::F32),
lanes: n,
};
match c.format {
F::R16_SFLOAT | F::R16G16_SFLOAT | F::R16G16B16A16_SFLOAT => {
color_write::small_float(fb, f, x, crate::pipeline::color_writes::HALF_NEAREST)
}
F::B10G11R11_UFLOAT_PACK32 => small_floats_nearest(fb, f, x),
_ => Ok(x),
}
Ok(x)
}
// A 16-bit lane's bits as the `half` the float class writes.
TexelConv::F16 => match c.declared {
@@ -1545,48 +1533,6 @@ fn int_lanes(fb: &mut FunctionBuilder<'_>, elem: TypeId, lanes: &[u32]) -> BResu
fb.module().const_value(c)
}
/// `x` (`f32` lanes of form `f`) rounded to nearest even onto `RG11B10Float`'s channels, as
/// Metal's integer store rounds them: red and green to six fraction bits, blue to five, unsigned (a
/// negative value to 0), a finite value that rounds past the largest finite one held there (65024,
/// 64512), an infinity kept and a NaN quieted, whose store the device converts.
fn small_floats_nearest(
fb: &mut FunctionBuilder<'_>,
f: crate::lower::arith::legal::Form,
x: SValue,
) -> BResult<SValue> {
use crate::lower::arith::color_write;
use crate::pipeline::lower_inputs::ChannelWrite;
let n = f.lanes;
let u = u32_ty(fb)?;
let uvec = vec(fb, u, n)?;
let bits = fb.convert(ConvOp::Bitcast, x, uvec)?;
let abs = u32s(fb, n, 0x7FFF_FFFF)?;
let mag = fb.binary(BinOp::BitwiseAnd, bits, abs)?;
let inf = u32s(fb, n, 0x7F80_0000)?;
let finite = fb.binary(BinOp::ULessThan, mag, inf)?;
let rounded = |fb: &mut FunctionBuilder<'_>, mantissa: u8, largest: f32| {
let rule = ChannelWrite::FloatNearestEven {
mantissa,
signed: false,
};
let r = color_write::small_float(fb, f, x, rule)?;
let rb = fb.convert(ConvOp::Bitcast, r, uvec)?;
let past = fb.binary(BinOp::IEqual, rb, inf)?;
let held = fb.binary(BinOp::LogicalAnd, past, finite)?;
let top = f32s(fb, n, largest)?;
fb.select(held, top, r)
};
let wide = rounded(fb, 6, 65024.0)?;
if n <= 2 {
return Ok(wide);
}
let narrow = rounded(fb, 5, 64512.0)?;
match n {
3 => fb.vector_shuffle(wide, narrow, &[0, 1, 5]),
_ => fb.vector_shuffle(wide, narrow, &[0, 1, 6, 3]),
}
}
/// The image texel (a `vec4` of the image's sampled type) of held AIR texel `v`; an 8-bit sRGB
/// format's codes encoded through `srgb`, the module's sRGB table (`SrgbEncode`, [`srgb_codes`]),
/// a NaN told by `test`.
+69 -481
View File
@@ -1,109 +1,45 @@
//! Metal's conversion of a texel to a `half` result, by the treatment of the bound pixel format.
//! The conversion of a texel to a `half` result on a device that samples through Metal's own
//! texture unit (`VkProperty::MetalSampler`: MoltenVK on Apple's GPU).
//!
//! A read, gather, or sample with a `half` result of a texture slot reads the slot's
//! `SpecKey::TexelFormat` specialization (`metal::texel_format`: the bound format's
//! `BicubicTexels` bits where its conversion is measured, else 0), which the binder sets from the
//! bound format, and converts the image's `f32` texel (the device's, filtered where the access
//! filters) through one module routine, [`define`]: `fn(x: vec4, flags: u32, sample: bool,
//! channel: u32) -> vec4`, called with the slot's constant, so once a device specializes the
//! module and inlines the call, the other families' arms fold away. Measured on an Apple M3 Max (macOS 26.7; the
//! case `f8f81b81` and the probe cases):
//! A read, gather, or sample with a `half` result takes the device's `f32` texel (Metal's `float`
//! result of the same access there, filtered where the access filters) rounded to `half` to
//! nearest even by the module's rounding (`narrow::round_texel`), on every device: the device's
//! native conversion. Metal's own `half` result differs from it for a few classes, which the
//! module notes (`PrecisionNote::HalfTexelConversion`, `texture::half_texels`): a 32-bit float
//! texel's sample (Metal rounds toward zero, saturating at `±65504`), the 16-bit normalized grids
//! (Metal's `float` value of `65455 / 65535`, `65519 / 65535` and `32759 / 32767` rounds twice),
//! and a format whose conversion is not measured. Every other class's `float` result rounds to
//! Metal's `half` (`metal_float_steps_round_to_their_half`).
//!
//! - **Reads and gathers** ([`HalfForm::Read`]): the texel's value correctly rounded to nearest
//! even, whatever the texture type and access (`access::sample`, `access::read`,
//! `access::read_write`); a 32-bit float texel overflows to the infinity and keeps half
//! denormals.
//! - **Samples, nearest or linear** ([`HalfForm::Sample`]): a 32-bit float texel's (filtered)
//! value rounded toward zero, saturating at `±65504`; a half-float texture's linear sum to
//! nearest with ties away from zero; a normalized texel's value rounded onto its format's grid
//! (`1/4080`, `1/2032`, `1/65535`, `1/32767`) and then to nearest even, which for a single
//! texel is its read. The same in every form read: normalized coordinates and pixel ones, a
//! constant offset, an explicit level, a bias, gradients, every address mode probed, and 1D,
//! 1D array, 2D array, 3D, and cube textures.
//! **The routine** ([`define`]): `fn(x: vec4, flags: u32, channel: u32) -> vec4`, called with the
//! slot's `SpecKey::TexelFormat` class (`metal::texel_format`), keeps one more of Metal's rules: a
//! two-plane YCbCr format's one texel on the grid `8192` (`TexelFormat::YCBCR_8192`: a read or a
//! sample of one texel, `TexelLanes::Texel`, and a 2D gather's lanes, `Gathered`) rounds its step
//! with ties away from zero (`texel_round::f32_to_half_from_even`), as Metal's does (every channel
//! of five formats on the grid `8192`, and the gathers; measured on an Apple M3 Max, macOS 26.7).
//! Every other texel, a value that may be filtered among them (`TexelLanes::Filtered`), rounds to
//! nearest even.
//!
//! **How the routine computes**. Every family rounds one `f32` value, and every rounding to nearest
//! even is one sequence shared by the families, so the routine is short where a device inlines it
//! at every call before it specializes (MoltenVK: SPIRV-Cross writes each function inlined):
//!
//! - A normalized or packed family's value is put onto its grid `D` first: the step
//! `n = RoundEven(x · D)` (`texel_round::grid_step`), then `|n| / D` with the sign of `n` (`+0`
//! for `n = 0`). On the 8-bit grids (`4080`, `2032`) and the packed code scales (1, 3, 15, 31,
//! 63, 255, 1023) that is the `f32` product `|n| · RN(1 / D)`, whose rounding to `half` is
//! `|n| / D`'s for every step, whichever way the product rounds (both `f32` neighbours of the
//! exact product round to that `half`; `the_reciprocal_product_rounds_like_the_quotient`). On
//! the 16-bit grids (`65535`, `32767`) it is not, and the exact `half` comes from one integer
//! multiplication (`texel_round::ones_ratio_to_half`).
//! - That value is rounded to nearest even once by integer arithmetic on its bits, in every
//! rounding form: it is a normal `half`'s, or a `half` already. The texel itself, for the other
//! families, is rounded to nearest even once by the module's `half` rounding
//! (`narrow::round_texel`): Metal's where the device's is controlled or measured to be, else the
//! device's own within the module's native note. The grid's value is selected after that
//! rounding, so where a device specializes a grid class, no rounding of the texel is left.
//! - A sample of a float or half-float texel rounds toward zero saturating or to nearest with ties
//! away: from the module's rounding to nearest even, by stepping to its neighbour where the
//! directed mode differs (`texel_round::f32_to_half_from_even`).
//!
//! A format whose conversion is not measured (`TexelFormat::OTHER`) takes the exact rounding of
//! every other `half` texel (`narrow::round_texel`, to nearest, half subnormals and the decoded NaN
//! kept), which the module records (`PrecisionNote::HalfTexelConversion`).
//!
//! **Packed formats**. A packed format's class holds its `TexelFormat::PACKED` field: an access
//! that reads one texel (`TexelLanes::Texel` or `Gathered`) recovers each channel's code from the
//! device's value on its code scale and converts `c / (2^b - 1)` to `half` exactly
//! (`ratio_to_half`), and a small float's value rounds to nearest even (it is a `half` value
//! already, so exactly). A two-plane YCbCr format's one texel (`TexelLanes::Texel`: a read or a
//! sample of one texel; `PackedTexels::ycbcr`) and a 2D gather's lanes (`Gathered`) round its
//! value, a step of `1/2048` or `1/8192`, with ties away from zero (every channel of five formats
//! on the grid `8192`, and the gathers; a step of `1/2048` is a `half`). A value that may be
//! filtered (`TexelLanes::Filtered`: a sample the device filters, or a
//! cube gather's lanes, each one channel's) keeps the `OTHER` arm, even under a packed normalized
//! class's `EXACT` family (`TexelFormat::packed_exact`), whose grids are per channel; a small
//! float's takes the half-float family's. A linear filter the module computes by fetches (an
//! in-place YCbCr texture's, `lower::sampler::in_place`) rounds its own result and does not come
//! here.
//!
//! **On a device that samples through Metal's own texture unit**: where the device's `f32` texel is
//! Metal's `float` result of the same access (`VkProperty::MetalSampler`), the routine tells
//! apart only the families whose `half` result is not that `float` result rounded to nearest
//! even ([`HalfFamilies::MetalSampler`]): a 32-bit float texel's sample (toward zero), the 16-bit
//! normalized grids (their `f32` value rounds twice: `65455 / 65535`, `65519 / 65535` and `32759 /
//! 32767`), and a YCbCr field's one texel on the grid `8192` (ties away). Every other family's
//! `half` is the `OTHER` arm's rounding of the device's texel there: an 8-bit normalized step `n /
//! D` on `1/255`, `1/4080`, `1/127` or `1/2032`, a packed code's `c / S`, a YCbCr step on `1/2048`
//! and a filter grid's step, rounded to `f32` and then to `half`, is the step's own `half` (every
//! step checked, `metal_float_steps_round_to_their_half`), and a half-float or small-float texel's
//! value is a `half` already. So the module reads none of their bits, and their classes specialize
//! alike with a slot bound to nothing (`spirv::spec_bits`). The 16-bit grids' exact `half` is there
//! one product of the step by a factor whose every product rounds as the quotient does
//! (`texel_round::ones_ratio_factor`), rounded by the module, all float arithmetic: Metal's
//! compiler, which MoltenVK hands the routine inlined at every access, takes far less time over it
//! than over an integer form (about 2 s over a function of 311 such accesses).
//!
//! **The plain arm.** On such a device a slot's access whose texel an image instruction hands back
//! **The plain arm.** A slot's access whose texel an image instruction hands back
//! ([`TexelOrigin::Image`]) converts it under the slot's `SpecKey::PlainHalfTexels`
//! specialization, which states that the bound class takes the routine's rounding to nearest even
//! alone (`TexelFormat::plain_on_metal_sampler`): there by the device's conversion of the texel
//! itself (`narrow::round_texel`, which Metal's compiler may fold into the image instruction), else
//! by the routine, so specialization leaves one of them. The class stays push data, so only a slot
//! specialization, which states that the bound class has no such YCbCr field
//! (`TexelFormat::plain_on_metal_sampler`): there by the device's conversion of the texel itself
//! (`narrow::round_texel`, which Metal's compiler may fold into the image instruction), else by
//! the routine, so specialization leaves one of them. The class stays push data, so only a slot
//! that sees both kinds of class makes a second pipeline. A computed texel keeps the routine.
//!
//! A sample's filtered value is the device's where the device filters it: on MoltenVK, which
//! samples through Metal's own sampler (`VkProperty::MetalSampler`), that is Metal's `float`
//! result, on the format's grid (normalized formats) or the sum rounded to `f32` (32-bit float
//! formats), so the conversion of it is Metal's `half` result exactly. Elsewhere the device's own
//! sampler filters it, and the `half` is the device's `float` texel rounded to nearest even, not
//! this routine's (`texture::device_texels`).
//! Elsewhere the device's own sampler hands back its `float` texel, and the `half` is that texel
//! rounded to nearest even, no routine (`texture::device_texels`).
use crate::lower::arith::legal::{FloatFmt, Form, Held};
use crate::lower::arith::narrow;
use crate::lower::arith::ops::{elem_ty, fsplat, splat, ty};
use crate::lower::arith::ops::splat;
use crate::lower::arith::texel_round;
use crate::metal::bicubic::BicubicTexels;
use crate::metal::texel_format::{PackedTexels, TexelFormat};
use crate::metal::texel_format::TexelFormat;
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::{BResult, BuildError, OperandRule};
use crate::spirv::ids::{FuncId, TypeId, Value as SValue};
use crate::spirv::ir::{BinOp, ConstBits, Constant, ConvOp, GlslOp, Type as SType, UnOp};
use crate::spirv::ids::{FuncId, Value as SValue};
use crate::spirv::ir::{BinOp, ConstBits, Constant, Type as SType};
/// Where the texel a conversion takes comes from: what Metal's compiler may fold its conversion
/// to `half` into ([`narrow::round_texel`]).
@@ -116,18 +52,8 @@ pub enum TexelOrigin {
Computed,
}
/// Which of Metal's rules a texel access with a `half` result takes (module docs).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum HalfForm {
/// A read or a gather: the texel's value to nearest even.
Read,
/// A sample, nearest or linear: a 32-bit float value toward zero saturating, a half-float
/// sum to nearest with ties away from zero.
Sample,
}
/// Which lanes of an access's value hold which channel of one texel: what a packed format's
/// conversion recovers codes from.
/// Which lanes of an access's value hold which channel of one texel: whether a YCbCr field's one
/// texel is there to round with ties away (module docs).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TexelLanes {
/// One texel's channels, red to alpha: a read, or a sample whose sampler reads one texel of
@@ -167,9 +93,9 @@ pub const FILTERED_LANES: u32 = 5;
/// An upper estimate of the routine's words, counted once per module that defines it, and the bound
/// on its size in every `QuantizeForm`, which a device that inlines it at each call compiles once
/// per call (`the_half_texel_routine_words_bound_its_emission`).
pub const ROUTINE_WORDS: u64 = 1600;
pub const ROUTINE_WORDS: u64 = 400;
/// An upper estimate of one call's words: the call and its three constant arguments.
/// An upper estimate of one call's words: the call and its two constant arguments.
pub const CALL_WORDS: u32 = 16;
/// The census name of the routine.
@@ -190,402 +116,64 @@ fn hform() -> Form {
}
}
fn uform(lanes: u8) -> Form {
Form {
held: Held::Int {
bits: 32,
container: 32,
},
lanes,
}
}
/// Which families the routine tells apart (module docs).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum HalfFamilies {
/// Every measured family: the device's texel is its own value, filtered by its own filter.
#[default]
Every,
/// A device whose texel is Metal's `float` result and whose rounding to nearest even is
/// Metal's: only a 32-bit float sample, the 16-bit normalized grids and a YCbCr field's one
/// texel on the grid `8192` (module docs). The routine reads its `channel` for that field
/// alone.
MetalSampler,
}
/// Whether a module whose routine tells apart `families` converts an image instruction's texel of a
/// class that takes the rounding to nearest even alone by the plain arm (module docs): where the
/// routine is the Metal-sampler body ([`HalfFamilies::MetalSampler`]).
pub fn takes_plain_arm(families: HalfFamilies) -> bool {
families == HalfFamilies::MetalSampler
}
/// Define the routine `fn(x: vec4, flags: u32, sample: bool, channel: u32) -> vec4` in `mb`
/// (module docs; `channel` is [`TexelLanes::code`]), telling apart `families`.
pub fn define(mb: &mut ModuleBuilder, families: HalfFamilies) -> BResult<FuncId> {
/// Define the routine `fn(x: vec4, flags: u32, channel: u32) -> vec4` in `mb` (module docs;
/// `channel` is [`TexelLanes::code`]): a YCbCr field's one texel on the grid `8192` rounded to
/// nearest with ties away from zero, every other texel to nearest even (`narrow::round_texel`).
/// It reads the packed field's top bit ([`TexelFormat::YCBCR_8192`]) of the class, and `channel`.
pub fn define(mb: &mut ModuleBuilder) -> BResult<FuncId> {
let f32_ = mb.ty(SType::Float { width: 32 })?;
let u32_ = mb.ty(SType::Int {
width: 32,
signed: false,
})?;
let bool_ = mb.ty(SType::Bool)?;
let vf = mb.ty(SType::Vector { elem: f32_, len: 4 })?;
let vu = mb.ty(SType::Vector { elem: u32_, len: 4 })?;
let mut fb = mb.routine(vf)?;
let x = fb.param(vf)?;
let flags = fb.param(u32_)?;
let sample = fb.param(bool_)?;
let channel = fb.param(u32_)?;
let r = match families {
HalfFamilies::Every => body(&mut fb, x, flags, sample, channel, vu)?,
HalfFamilies::MetalSampler => metal_body(&mut fb, x, flags, sample, channel)?,
let u1 = |fb: &mut FunctionBuilder<'_>, v: u32| {
let s = Form {
held: Held::Int {
bits: 32,
container: 32,
},
lanes: 1,
};
splat(fb, s, u64::from(v))
};
let m = u1(&mut fb, TexelFormat::YCBCR_8192)?;
let z = u1(&mut fb, 0)?;
let field = fb.binary(BinOp::BitwiseAnd, flags, m)?;
let ycbcr = fb.binary(BinOp::INotEqual, field, z)?;
let texel_lanes = u1(&mut fb, TEXEL_LANES)?;
let single = fb.binary(BinOp::ULessThanEqual, channel, texel_lanes)?;
let ycbcr = fb.binary(BinOp::LogicalAnd, ycbcr, single)?;
let even = narrow::round_texel(&mut fb, hform(), x)?;
let b = fb.module().ty(SType::Bool)?;
let no = fb.module().constant(Constant::Scalar {
ty: b,
bits: ConstBits(0),
})?;
let toward_zero = fb.module().const_value(no)?;
let away = texel_round::f32_to_half_from_even(&mut fb, fform(), (x, even), toward_zero)?;
let r = fb.select(ycbcr, away, even)?;
fb.ret(Some(r))?;
fb.finish()
}
/// The constant of form `f` (four lanes) whose lanes hold `bits`.
fn lanes_of(fb: &mut FunctionBuilder<'_>, f: Form, bits: [u64; 4]) -> BResult<SValue> {
let e = elem_ty(fb, f.held)?;
let mut parts = Vec::with_capacity(4);
for b in bits {
parts.push(fb.module().constant(Constant::Scalar {
ty: e,
bits: ConstBits(b),
})?);
}
let t = ty(fb, f)?;
let c = fb.module().constant(Constant::Composite {
ty: t,
parts: parts.into(),
})?;
fb.module().const_value(c)
}
/// A per-channel table of a packed class ([`PackedField::lanes`]): the four lanes it holds for a
/// field's channel code scales, or for `None`, a field without scales.
type Table<'a> = &'a dyn Fn(&mut FunctionBuilder<'_>, Option<[u32; 4]>) -> BResult<SValue>;
/// A packed class's field (`TexelFormat::PACKED`) read once from a routine's `flags` and `channel`,
/// which selects each per-channel table the routine needs ([`PackedField::lanes`]).
struct PackedField {
/// Each field with scales: its scales, and whether it is the field.
fields: Vec<([u32; 4], SValue)>,
/// Whether the field states coded channels (a field with scales).
coded: SValue,
/// Whether the field's one texel rounds with ties away from zero, a two-plane YCbCr format's
/// or `RGB10A2Unorm_sRGB`'s (`PackedTexels::ties_away`).
ycbcr: SValue,
/// Whether the lanes are a gather's, each its channel's (`channel` below 4).
gathered: SValue,
/// The gathered channel (`channel`, at most 3).
channel: SValue,
}
impl PackedField {
fn read(fb: &mut FunctionBuilder<'_>, flags: SValue, channel: SValue) -> BResult<PackedField> {
let u1 = |fb: &mut FunctionBuilder<'_>, v: u32| splat(fb, uform(1), u64::from(v));
let shift = u1(fb, TexelFormat::PACKED)?;
let field = fb.binary(BinOp::ShiftRightLogical, flags, shift)?;
let four_bits = u1(fb, 0xF)?;
let field = fb.binary(BinOp::BitwiseAnd, field, four_bits)?;
let mut coded = splat(
fb,
Form {
held: Held::Bool,
lanes: 1,
},
0,
)?;
let mut ycbcr = coded;
let mut fields = Vec::with_capacity(PackedTexels::ALL.len());
for p in PackedTexels::ALL {
if !p.ties_away() && p.scales().is_none() {
continue;
}
let k = u1(fb, p as u32)?;
let is = fb.binary(BinOp::IEqual, field, k)?;
if p.ties_away() {
ycbcr = fb.binary(BinOp::LogicalOr, ycbcr, is)?;
}
let Some(s) = p.scales() else {
continue;
};
coded = fb.binary(BinOp::LogicalOr, coded, is)?;
fields.push((s, is));
}
let three = u1(fb, 3)?;
let gathered = fb.binary(BinOp::ULessThanEqual, channel, three)?;
let channel = fb.glsl(GlslOp::UMin, &[channel, three])?;
Ok(PackedField {
fields,
coded,
ycbcr,
gathered,
channel,
})
}
/// `table`'s lanes for the field (its `None` lanes for a field without scales), a gather's
/// lanes each its channel's.
fn lanes(&self, fb: &mut FunctionBuilder<'_>, table: Table<'_>) -> BResult<SValue> {
let mut lanes = table(fb, None)?;
for (s, is) in &self.fields {
let these = table(fb, Some(*s))?;
lanes = fb.select(*is, these, lanes)?;
}
// A gather's lanes are one channel's: its lane in every lane.
let one = fb.vector_extract_dynamic(lanes, self.channel)?;
let t = fb.value_ty(lanes)?;
let one = fb.composite_construct(t, &[one; 4])?;
fb.select(self.gathered, one, lanes)
}
}
/// The `f32` bits of `v` and of `RN(1 / v)`, the reciprocal correctly rounded to `f32`.
fn grid_bits(v: u32) -> (u64, u64) {
let d = v as f32;
(u64::from(d.to_bits()), u64::from((1.0 / d).to_bits()))
}
fn body(
fb: &mut FunctionBuilder<'_>,
x: SValue,
flags: SValue,
sample: SValue,
channel: SValue,
vu: TypeId,
) -> BResult<SValue> {
let f = fform();
let u = uform(4);
let ft = ty(fb, f)?;
let u1 = |fb: &mut FunctionBuilder<'_>, v: u32| splat(fb, uform(1), u64::from(v));
let f1 = |fb: &mut FunctionBuilder<'_>, bits: u64| {
let s = Form {
held: Held::Float(FloatFmt::F32),
lanes: 1,
};
splat(fb, s, bits)
};
let has = |fb: &mut FunctionBuilder<'_>, bit: u32| -> BResult<SValue> {
let m = u1(fb, bit)?;
let z = u1(fb, 0)?;
let and = fb.binary(BinOp::BitwiseAnd, flags, m)?;
fb.binary(BinOp::INotEqual, and, z)
};
let is_float = has(fb, BicubicTexels::LINEAR)?;
let is_half = has(fb, BicubicTexels::HALF)?;
let float_or_half = fb.binary(BinOp::LogicalOr, is_float, is_half)?;
// Normalized channels: the value onto the format's grid `D`, then `n / D` to nearest even. A
// packed normalized class (`TexelFormat::packed_exact`) sums on its field's grids, which a
// value that may be filtered does not name per lane (a cube gather's lanes are one channel's):
// it keeps the `OTHER` arm.
let wide = has(fb, BicubicTexels::WIDE16)?;
let signed = has(fb, BicubicTexels::SNORM)?;
let exact = has(fb, BicubicTexels::EXACT)?;
let packed = has(fb, TexelFormat::PACKED_MASK)?;
let own_grid = fb.unary(UnOp::LogicalNot, packed)?;
let norm_arm = fb.binary(BinOp::LogicalAnd, exact, own_grid)?;
let (g8, r8) = grid_bits(TexelFormat::GRID8);
let (g8s, r8s) = grid_bits(TexelFormat::GRID8S);
let (g16, _) = grid_bits(TexelFormat::GRID16);
let (g16s, _) = grid_bits(TexelFormat::GRID16S);
let (g8, g8s, g16, g16s) = (f1(fb, g8)?, f1(fb, g8s)?, f1(fb, g16)?, f1(fb, g16s)?);
let narrow_grid = fb.select(signed, g8s, g8)?;
let broad = fb.select(signed, g16s, g16)?;
let d = fb.select(wide, broad, narrow_grid)?;
let d = fb.composite_construct(ft, &[d; 4])?;
// The 16-bit grids' value is `ones_ratio_to_half`'s, not the product's.
let (r8, r8s) = (f1(fb, r8)?, f1(fb, r8s)?);
let rcp = fb.select(signed, r8s, r8)?;
let rcp = fb.composite_construct(ft, &[rcp; 4])?;
// A packed class's one texel: each channel's code recovered on its scale and its value `c / S`,
// or a small float's value (a `half` already) to nearest even. A value that may be filtered
// keeps the `OTHER` arm, but a small float's, the half-float family's.
let scale: Table<'_> = &|fb, s| {
let s = s.unwrap_or([1; 4]).map(|v| grid_bits(v).0);
lanes_of(fb, f, s)
};
let reciprocal: Table<'_> = &|fb, s| {
let s = s.unwrap_or([1; 4]).map(|v| grid_bits(v).1);
lanes_of(fb, f, s)
};
let packed_field = PackedField::read(fb, flags, channel)?;
let scales = packed_field.lanes(fb, scale)?;
let reciprocals = packed_field.lanes(fb, reciprocal)?;
let texel_lanes = u1(fb, TEXEL_LANES)?;
let single = fb.binary(BinOp::ULessThanEqual, channel, texel_lanes)?;
let coded = fb.binary(BinOp::LogicalAnd, packed_field.coded, single)?;
// A YCbCr format's one texel (a read or a sample of one texel) and a 2D gather's lanes, each
// one texel's channel: its value to nearest with ties away from zero, as a half-float texel's
// sample.
let ycbcr = fb.binary(BinOp::LogicalAnd, packed_field.ycbcr, single)?;
let d = fb.select(coded, scales, d)?;
let rcp = fb.select(coded, reciprocals, rcp)?;
// The step `n` on the grid, and `|n| / D` with the sign of `n` (`+0` for `n = 0`).
let neg_d = fb.unary(UnOp::FNegate, d)?;
let n = texel_round::grid_step(fb, f, x, d, neg_d)?;
let z = splat(fb, u, 0)?;
let negative = fb.binary(BinOp::SLessThan, n, z)?;
let m = fb.glsl(GlslOp::SAbs, &[n])?;
let mf = fb.convert(ConvOp::ConvertUToF, m, ft)?;
let product = fb.binary_no_contraction(BinOp::FMul, mf, rcp)?;
let (b15, b16) = (u1(fb, 15)?, u1(fb, 16)?);
let b = fb.select(signed, b15, b16)?;
let b = fb.composite_construct(vu, &[b; 4])?;
let ones = texel_round::ones_ratio_to_half(fb, u, m, b)?;
let sixteen = fb.binary(BinOp::LogicalAnd, norm_arm, wide)?;
let value = fb.select(sixteen, ones, product)?;
let bits = fb.convert(ConvOp::Bitcast, value, vu)?;
// The step's `half`, to nearest even by integer arithmetic on the bits: a nonzero step's
// product lies in `[2^-12, 1]`, within the normal halves, where the `half` keeps the top 11 of
// the `f32`'s 24 significand bits, so adding `0xFFF` plus the lowest kept bit and clearing the
// 13 bits below rounds it once; a carry raises the exponent, as it must. The 16-bit grids'
// value is a `half` already (normal or denormal), whose 13 low bits are clear, so it is kept; a
// zero step's `+0` too. No conversion: nothing for a device to fold.
let (k13, one) = (splat(fb, u, 13)?, splat(fb, u, 1)?);
let lsb = fb.binary(BinOp::ShiftRightLogical, bits, k13)?;
let lsb = fb.binary(BinOp::BitwiseAnd, lsb, one)?;
let half_ulp = splat(fb, u, 0xFFF)?;
let bias = fb.binary(BinOp::IAdd, half_ulp, lsb)?;
let bits = fb.binary(BinOp::IAdd, bits, bias)?;
let keep = splat(fb, u, 0xFFFF_E000)?;
let bits = fb.binary(BinOp::BitwiseAnd, bits, keep)?;
let sign = splat(fb, u, 0x8000_0000)?;
let sign = fb.select(negative, sign, z)?;
let bits = fb.binary(BinOp::BitwiseOr, bits, sign)?;
let on_grid = fb.convert(ConvOp::Bitcast, bits, ft)?;
let grid = fb.binary(BinOp::LogicalOr, coded, norm_arm)?;
let own = fb.unary(UnOp::LogicalNot, float_or_half)?;
let grid = fb.binary(BinOp::LogicalAnd, grid, own)?;
// Every other family's texel to nearest even, once; a sample of a 32-bit float texel toward
// zero saturating, of a half-float texel to nearest with ties away. The grid's `half` is
// selected after it, so a device that specializes a grid class drops the rounding of `x`
// whole.
// The module's rounding is every other family's, the `OTHER` arm's among them, so a sample's
// directed rounding follows from `even`.
let even = narrow::round_texel(fb, hform(), x)?;
let sampled = texel_round::f32_to_half_from_even(fb, f, (x, even), is_float)?;
let takes = fb.binary(BinOp::LogicalAnd, sample, float_or_half)?;
let takes = fb.binary(BinOp::LogicalOr, takes, ycbcr)?;
let rounded = fb.select(takes, sampled, even)?;
fb.select(grid, on_grid, rounded)
}
/// [`body`] on a device whose texel is Metal's `float` result ([`HalfFamilies::MetalSampler`]): the 16-bit normalized grids' exact `half`
/// ([`grid16_by_product`]), a 32-bit float sample toward zero and a YCbCr field's one texel on the
/// grid `8192` with ties away (`f32_to_half_from_even`), every other texel to nearest even
/// (`narrow::round_texel`). It reads the class's `LINEAR`, `SNORM` and `WIDE16` bits (a class
/// with `WIDE16` is `EXACT`'s, never packed) and the packed field's top bit
/// ([`TexelFormat::YCBCR_8192`]), and `channel` only where that bit is set.
fn metal_body(
fb: &mut FunctionBuilder<'_>,
x: SValue,
flags: SValue,
sample: SValue,
channel: SValue,
) -> BResult<SValue> {
let f = fform();
let ft = ty(fb, f)?;
let u1 = |fb: &mut FunctionBuilder<'_>, v: u32| splat(fb, uform(1), u64::from(v));
let f1 = |fb: &mut FunctionBuilder<'_>, bits: u64| {
let s = Form {
held: Held::Float(FloatFmt::F32),
lanes: 1,
};
splat(fb, s, bits)
};
let has = |fb: &mut FunctionBuilder<'_>, bit: u32| -> BResult<SValue> {
let m = u1(fb, bit)?;
let z = u1(fb, 0)?;
let and = fb.binary(BinOp::BitwiseAnd, flags, m)?;
fb.binary(BinOp::INotEqual, and, z)
};
let is_float = has(fb, BicubicTexels::LINEAR)?;
let wide = has(fb, BicubicTexels::WIDE16)?;
let signed = has(fb, BicubicTexels::SNORM)?;
// The 16-bit grids: the step `n` on the grid, and the `half` of `n / D` (`+0` for `n = 0`).
let (g16, _) = grid_bits(TexelFormat::GRID16);
let (g16s, _) = grid_bits(TexelFormat::GRID16S);
let (g16, g16s) = (f1(fb, g16)?, f1(fb, g16s)?);
let d = fb.select(signed, g16s, g16)?;
let d = fb.composite_construct(ft, &[d; 4])?;
let neg_d = fb.unary(UnOp::FNegate, d)?;
let on_grid = grid16_by_product(fb, x, (d, neg_d), signed)?;
// A YCbCr field's one texel on the grid `8192`: ties away from zero.
let ycbcr = has(fb, TexelFormat::YCBCR_8192)?;
let texel_lanes = u1(fb, TEXEL_LANES)?;
let single = fb.binary(BinOp::ULessThanEqual, channel, texel_lanes)?;
let ycbcr = fb.binary(BinOp::LogicalAnd, ycbcr, single)?;
let even = narrow::round_texel(fb, hform(), x)?;
let sampled = texel_round::f32_to_half_from_even(fb, f, (x, even), is_float)?;
let takes = fb.binary(BinOp::LogicalAnd, sample, is_float)?;
let takes = fb.binary(BinOp::LogicalOr, takes, ycbcr)?;
let rounded = fb.select(takes, sampled, even)?;
fb.select(wide, on_grid, rounded)
}
/// The `half` of a 16-bit normalized texel `x` (four `f32` lanes) on its grid `D` (`d` and
/// `neg_d`, `65535`, or `32767` where `signed`): its step `n` (`texel_round::grid_round`), and `n
/// / D` correctly rounded to `half` with the sign of `n`, `+0` for `n = 0`, as one product. The
/// magnitude `|n| · c`, for the grid's factor `c` (`texel_round::ones_ratio_factor`: every step's
/// product rounds to the `half` of its quotient, either way it rounds to `f32`), rounded to `half`
/// by the module's rounding ([`narrow::round`]), exact where that rounding is Metal's. The sign is
/// put back by a test of `n` below `-1/2`, so that a `-0` step gives `+0`. Every operation is a
/// float one: on MoltenVK, Metal's compiler takes about 2 s less over a function converting 311
/// such texels than over an integer multiplication, leading-bit search and shifts (the M3 Max,
/// macOS 27.0.1, MoltenVK's MSL of a guest's 270,000-word fragment function).
fn grid16_by_product(
fb: &mut FunctionBuilder<'_>,
x: SValue,
(d, neg_d): (SValue, SValue),
signed: SValue,
) -> BResult<SValue> {
let f = fform();
let ft = ty(fb, f)?;
let factor = |fb: &mut FunctionBuilder<'_>, b: u32| {
let s = Form {
held: Held::Float(FloatFmt::F32),
lanes: 1,
};
splat(
fb,
s,
u64::from(texel_round::ones_ratio_factor(b).to_bits()),
)
};
let (c15, c16) = (factor(fb, 15)?, factor(fb, 16)?);
let c = fb.select(signed, c15, c16)?;
let c = fb.composite_construct(ft, &[c; 4])?;
let n = texel_round::grid_round(fb, x, d, neg_d)?;
let m = fb.glsl(GlslOp::FAbs, &[n])?;
let p = fb.binary_no_contraction(BinOp::FMul, m, c)?;
let below = fsplat(fb, f, -0.5)?;
let negative = fb.binary(BinOp::FOrdLessThan, n, below)?;
let minus = fb.unary(UnOp::FNegate, p)?;
let v = fb.select(negative, minus, p)?;
narrow::round(fb, hform(), v)
}
/// The held `half` texel of image texel `x` (a `vec4` of `f32`), converted by `routine` under the
/// slot's treatment constant `flags` (its `TexelFormat` specialization), the access's `form`, and
/// `lanes`, its [`TexelLanes::code`] (a constant, or the shader's choice where a runtime
/// sampler's word decides whether a sample reads one texel).
/// slot's treatment constant `flags` (its `TexelFormat` specialization) and `lanes`, its
/// [`TexelLanes::code`] (a constant, or the shader's choice where a runtime sampler's word decides
/// whether a sample reads one texel).
pub fn convert(
fb: &mut FunctionBuilder<'_>,
routine: FuncId,
x: SValue,
flags: SValue,
(form, lanes): (HalfForm, SValue),
lanes: SValue,
) -> BResult<SValue> {
let b = fb.module().ty(SType::Bool)?;
let c = fb.module().constant(Constant::Scalar {
ty: b,
bits: ConstBits(u64::from(form == HalfForm::Sample)),
})?;
let sample = fb.module().const_value(c)?;
// Every call of the routine returns its texel.
fb.call(routine, &[x, flags, sample, lanes])?
fb.call(routine, &[x, flags, lanes])?
.ok_or(BuildError::Operand {
op: crate::spv::Op::FunctionCall,
rule: OperandRule::Callee,
+54 -137
View File
@@ -168,7 +168,7 @@ use crate::error::{DriverDeviation, Error, Feature, LowerFamily, Unsupported};
use crate::lower::arith::{FloatFmt, Form, Held};
use crate::lower::emit::EmitCx;
use crate::lower::sampler::Sampling;
use crate::lower::select::{both, FamilyPlans, NoteClause, NoteOn, NoteTest, Plan, SelectCx};
use crate::lower::select::{FamilyPlans, NoteClause, NoteOn, NoteTest, Plan, SelectCx};
use crate::lower::strategy::FamilyStrategy;
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::sym::{SampledType, SlotClass, SlotRef};
@@ -891,10 +891,6 @@ pub struct TexturePlan {
/// The guard conditions of the slice writes every invocation shares (`cooperative`): each
/// one's branch is taken by every invocation, so its condition is emitted as `true`.
pub cooperative: BTreeSet<ValueId>,
/// Which families the module's `half` routine tells apart ([`half_families`]): every
/// measured one, or on a device that samples through Metal's own texture unit only those
/// whose `half` is not Metal's `float` texel rounded to nearest even.
pub half_families: half::HalfFamilies,
/// The heap operations the function selects (texture and sampling): each masks its handle
/// where the handle-table search carries flags in it (`AccessPlan::lookup`).
pub heap_uses: u32,
@@ -976,8 +972,8 @@ pub struct Declared {
/// The module's routine of that conversion ([`half::define`]), defined once where a slot
/// takes it.
pub half_routine: Option<FuncId>,
/// The `PlainHalfTexels` specialization constant of each slot of those on a device whose
/// routine tells apart Metal's sampler's families alone (`half::HalfFamilies::MetalSampler`).
/// The `PlainHalfTexels` specialization constant of each of those slots: whether the bound
/// class converts by the plain arm (`half` module docs).
pub plain_half: BTreeMap<u32, SValue>,
/// The `TextureSwizzle` specialization constant of each texture buffer slot whose reads
/// apply the bound texture buffer's swizzle, and of each storage slot of
@@ -1195,9 +1191,9 @@ pub fn declare(
)?;
}
if s.half_format && d.half_routine.is_none() {
d.half_routine = Some(half::define(mb, plan.families.texture.half_families)?);
d.half_routine = Some(half::define(mb)?);
}
if s.half_format && half::takes_plain_arm(plan.families.texture.half_families) {
if s.half_format {
let b = mb.ty(SType::Bool)?;
let c = mb.spec(
crate::pipeline::sym::SpecKey::PlainHalfTexels(s.slot),
@@ -1282,7 +1278,7 @@ pub fn declare(
d.heap_classes = Some(declare_heap_classes(mb)?);
}
if plan.families.texture.heap_half && d.half_routine.is_none() {
d.half_routine = Some(half::define(mb, plan.families.texture.half_families)?);
d.half_routine = Some(half::define(mb)?);
}
Ok(d)
}
@@ -1490,34 +1486,33 @@ pub enum OneTexel {
Heap(ValueId),
}
/// A read, gather, or sample of `image`, of shape `shape`, with a `half` result, which reads one
/// texel where `one` says. On a slot of a color texture, a texture buffer's included (Metal reads a
/// texture buffer's texels as a texture's, measured on the P2a probe), it converts the texels by
/// the bound format's class (`half`), which the slot's `TexelFormat` specialization gives
/// (`RuntimeFact::TexelFormat`); a heap color texture's sample or gather by the class its handle
/// carries (its caller asks the routine), whose `OTHER` arm no specialization rules out; a heap
/// element's read and a depth texture's are rounded exactly (`narrow::round_texel`). The module
/// notes each heap and depth access as `PrecisionNote::HalfTexelConversion`: a format whose
/// conversion is not measured takes that rounding of the device's `f32` texel, which Metal's
/// conversion may not be. A slot's access notes it where its class names no measured family
/// ([`unmeasured_class`]), the conversion's `OTHER` arm, and, where the access reads one texel, no
/// packed field either: through a runtime sampler slot, where its word filters.
/// On a device that samples through Metal's own texture unit, an 8-bit sRGB format's class is
/// Metal's too ([`unconverted_class`]); where that device also rounds to `half` as Metal does
/// ([`half_families`]), every measured class's is, so the access notes it where the bound format's
/// class is unmeasured there, as the slot's `UnmeasuredTexels` specialization states, whatever the
/// access and its sampler.
/// A read, gather, or sample of `image`, of shape `shape`, with a `half` result, a sample where
/// `sample` (a sample's and a pixel fetch's form: not a read's or a gather's). Its `half` is the
/// device's `f32` texel rounded to nearest even (`narrow::round_texel`) on every device, recorded
/// as `PrecisionNote::HalfTexelConversion` where Metal's `half` result may differ from it.
///
/// Where the access's texel is the device's (`device`, [`device_texels`]), it is rounded exactly as
/// a heap element's, and noted alike.
/// Where the device's texel is its own (`device`, [`device_texels`]: off Metal's own texture unit)
/// the access records the note outright, a heap element's and a depth texture's too. On a device
/// that samples through Metal's own texture unit (MoltenVK on Apple's GPU, whose `f32` texel is
/// Metal's `float` result), a slot's color texture converts through the module's routine (`half`),
/// which keeps a YCbCr field's ties away from zero on the grid `8192`, by the bound format's class
/// (its `TexelFormat` specialization, `RuntimeFact::TexelFormat`); a heap color texture's sample or
/// gather by the class its handle carries (its caller asks the routine). The note holds there
/// where the bound class's `half` is not that `float` rounded to nearest even: a class measured in
/// none of the families (the slot's `UnmeasuredTexels` specialization), a 16-bit normalized grid
/// (`BicubicTexels::WIDE16`: three steps of each round twice), and a sample of a 32-bit float
/// texel (`BicubicTexels::LINEAR`: Metal rounds toward zero, saturating), tests of the bound
/// format the runtime announces at a draw or dispatch binding such a texture. A heap color
/// texture's and a depth texture's access records it outright.
pub(crate) fn half_texels(
cx: &mut SelectCx<'_>,
image: ImageRef,
shape: ImageShape,
one: OneTexel,
sample: bool,
device: bool,
m: &mut Meter,
) -> Result<(), Error> {
use crate::metal::bicubic::BicubicTexels as B;
let index = match image {
ImageRef::Slot(index) if !shape.depth && !device => index,
_ => {
@@ -1525,43 +1520,22 @@ pub(crate) fn half_texels(
return Ok(());
}
};
let families = half_families(cx);
cx.families.texture.half_families = families;
let when = match families {
half::HalfFamilies::MetalSampler => {
// The routine's `OTHER` arm is Metal's `half` of every measured class's texel: the
// note holds where the bound format's class is unmeasured there. The module requires
// the device's sampler to be Metal's.
cx.families.sampler.metal_sampler = true;
if let Some(s) = cx.families.texture.slots.get_mut(&index) {
s.unmeasured = true;
}
vec![[NoteTest::equal(NoteOn::Unmeasured(index), 1, 1)].into()]
}
half::HalfFamilies::Every => {
let unmeasured = [unconverted_class(cx, index)];
let unpacked: NoteClause = [NoteTest::equal(
NoteOn::Texel(index),
crate::metal::texel_format::TexelFormat::PACKED_MASK,
0,
)]
.into();
match one {
OneTexel::Always => both(&unmeasured, &[unpacked]),
OneTexel::Word(n) => {
let mut either = vec![unpacked];
either.extend(crate::lower::sampler::linear::word_filters(n));
both(&unmeasured, &either)
}
OneTexel::Never | OneTexel::Heap(_) => unmeasured.to_vec(),
}
}
};
// The module requires the device's sampler to be Metal's.
cx.families.sampler.metal_sampler = true;
if let Some(s) = cx.families.texture.slots.get_mut(&index) {
s.unmeasured = true;
}
let mut when = vec![
[NoteTest::equal(NoteOn::Unmeasured(index), 1, 1)].into(),
[NoteTest::differ(NoteOn::Bound(index), B::WIDE16, 0)].into(),
];
if sample {
when.push([NoteTest::differ(NoteOn::Bound(index), B::LINEAR, 0)].into());
}
cx.note_when(PrecisionNote::HalfTexelConversion, when, m)?;
let slot = slot_of(cx, index)?.slot;
if let Some(s) = cx.families.texture.slots.get_mut(&index) {
s.half_format = true;
s.half_filtered |= one != OneTexel::Always;
}
cx.facts
.insert(crate::pipeline::facts::RuntimeFact::TexelFormat { slot });
@@ -1627,73 +1601,6 @@ pub(crate) fn device_texels(cx: &SelectCx<'_>) -> bool {
.contains(&crate::device::requirements::VkProperty::MetalSampler)
}
/// The families the module's `half` routine tells apart (`half::HalfFamilies`): on a device whose
/// texel is Metal's `float` result of the access (`VkProperty::MetalSampler`) and whose rounding to
/// nearest even is Metal's (`QuantizeForm::Device`, `Converted` and `Controlled`), only those whose
/// `half` is not that texel rounded to nearest even ([`half::HalfFamilies::MetalSampler`]);
/// elsewhere every measured one. A function of the profile alone, so every access of a function
/// agrees.
pub(crate) fn half_families(cx: &SelectCx<'_>) -> half::HalfFamilies {
use crate::spirv::builder::QuantizeForm;
let metal = cx
.profile
.fields()
.enabled
.properties
.contains(&crate::device::requirements::VkProperty::MetalSampler);
let rounds = matches!(
crate::lower::arith::narrow::quantize_form(cx.profile),
QuantizeForm::Device | QuantizeForm::Converted | QuantizeForm::Controlled
);
match metal && rounds {
true => half::HalfFamilies::MetalSampler,
false => half::HalfFamilies::Every,
}
}
/// The clause of texture slot `index` bound in a format whose class names no measured family: its
/// `TexelFormat` specialization holds none of `LINEAR`, `HALF`, and `EXACT`, the value on which the
/// conversion routine and the emulated filters take the device's arm.
pub(crate) fn unmeasured_class(index: u32) -> NoteClause {
use crate::metal::bicubic::BicubicTexels as B;
[NoteTest::equal(
NoteOn::Texel(index),
B::LINEAR | B::HALF | B::EXACT,
0,
)]
.into()
}
/// The clause of texture slot `index` where its `half` conversion may not be Metal's
/// ([`half_texels`]): [`unmeasured_class`], and on a device that samples through Metal's own
/// texture unit (`VkProperty::MetalSampler`: MoltenVK on Apple's GPU) also no `SRGB` bit, the
/// module requiring the property there. That device's `f32` texel of an 8-bit sRGB format, its
/// own decode, is Metal's `float` value: a step on `1/4095` (a color channel's table step, or a
/// linear sum rounded onto its grid), `1/4080` (alpha's linear sum), or `1/255` (alpha's code),
/// rounded to nearest even (`metal::texel_format`). The conversion's `OTHER` arm rounds that to
/// `half` to nearest even, which is the step's own rounding to `half`, Metal's `half` value: on
/// those grids no step lies near enough a tie between halves for the `f32` rounding to move it
/// across (`metals_srgb_float_steps_round_to_their_half_steps`).
fn unconverted_class(cx: &mut SelectCx<'_>, index: u32) -> NoteClause {
use crate::metal::bicubic::BicubicTexels as B;
let metal = cx
.profile
.fields()
.enabled
.properties
.contains(&crate::device::requirements::VkProperty::MetalSampler);
if !metal {
return unmeasured_class(index);
}
cx.families.sampler.metal_sampler = true;
[NoteTest::equal(
NoteOn::Texel(index),
B::LINEAR | B::HALF | B::EXACT | B::SRGB,
0,
)]
.into()
}
/// The address-mode map constexpr sampler `words` samples texture slot `index` under: the map
/// of the texture the slot's variant binds there (`LoweringInputs::address_maps`), `None` for
/// the identity. The slot records `RuntimeFact::ConstexprSampled` with the sampler's modes,
@@ -2115,7 +2022,13 @@ pub const HEAP_CLASS_CENSUS: &str = "sampler.heap.texel_class";
/// may reach a half-float image ([`may_store_half`]), which the device converts whole. Its rounding
/// of each channel to `half` (Metal rounds toward zero, a finite value past 65504 to 65504) is
/// Metal's where the profile takes `DriverDeviation::MetalHalfStorageWrites` (the module requires
/// its property), else the device's (`PrecisionNote::DeviceColorConversion`). Its NaN is Metal's
/// its property), else the device's (`PrecisionNote::DeviceColorConversion`). A write of an
/// integer texel into a texture of the float class (`cross`, `emit::cross_write`), which Metal
/// stores rounded to nearest even onto a half-float or small-float channel, records the note
/// wherever it may reach one, the device's conversion rounding as it rounds a `float` write
/// (toward zero on every measured driver: within one unit in the last place of the channel's
/// Metal value, a finite value past 65504 stored as 65504 where Metal's `half` is the infinity).
/// Its NaN is Metal's
/// `0x7e00` where the profile takes `DriverDeviation::MetalHalfStorageNans` (the module requires its
/// property), else the device's encoding of it (`PrecisionNote::DeviceNanEncoding`). A write that
/// may reach a packed small float image ([`small_float_storage`]) stores its NaN as the device
@@ -2126,7 +2039,7 @@ pub const HEAP_CLASS_CENSUS: &str = "sampler.heap.texel_class";
pub(super) fn half_storage_facts(
cx: &mut SelectCx<'_>,
image: ImageRef,
class: StorageImageClass,
(class, cross): (StorageImageClass, bool),
m: &mut Meter,
) -> Result<(), Error> {
use crate::device::requirements::VkProperty;
@@ -2135,9 +2048,10 @@ pub(super) fn half_storage_facts(
_ => Vec::new(),
};
if !half.is_empty() {
if cx
.profile
.takes_driver_deviation(DriverDeviation::MetalHalfStorageWrites)
if !cross
&& cx
.profile
.takes_driver_deviation(DriverDeviation::MetalHalfStorageWrites)
{
cx.families
.texture
@@ -2159,6 +2073,9 @@ pub(super) fn half_storage_facts(
}
}
let small = small_float_storage(cx, image)?;
if cross {
cx.note_when(PrecisionNote::DeviceColorConversion, small.clone(), m)?;
}
cx.note_when(PrecisionNote::DeviceNanEncoding, small, m)
}
@@ -3011,7 +2928,7 @@ fn select_read_as(
// An extended-range texel is decoded exactly to `f32`, which a `half` result rounds to
// nearest even, as Metal answers. A read is one texel.
if texel.conv == TexelConv::F16 && !exact && extended.is_none() {
half_texels(cx, image, shape, OneTexel::Always, device_texels(cx), m)?;
half_texels(cx, image, shape, false, device_texels(cx), m)?;
half_texel_nans(cx, image, shape, m)?;
}
if texel.conv == TexelConv::F32 && !exact && extended.is_none() {
@@ -3257,7 +3174,7 @@ fn select_write(
// Its alpha in red where the class is `A8Unorm`'s and the device holds such a texture so.
let heap_alpha_red = heap_alpha_in_red(cx, image, shape, texel.conv);
if texel.conv == TexelConv::F32 {
half_storage_facts(cx, image, class, m)?;
half_storage_facts(cx, image, (class, cross.is_some()), m)?;
}
if texel.conv == TexelConv::F16 && extended.is_none() {
half_write_nans(cx, image)?;
@@ -299,7 +299,7 @@ pub(super) fn select(
let guard = slot::write_guard(cx, false);
let class = super::storage_class(cx, image)?;
if conv == TexelConv::F32 {
super::half_storage_facts(cx, image, class, m)?;
super::half_storage_facts(cx, image, (class, false), m)?;
}
if matches!(conv, TexelConv::F32 | TexelConv::F16) {
super::norm_storage_facts(cx, image, t.image, TexelForm { conv, lanes })?;
@@ -216,10 +216,6 @@ pub struct SlotPlan {
/// linear sample reads the bound format's channels from it (`RuntimeFact::TexelFormat`).
/// Implied by `half_format`.
pub texel_format: bool,
/// An access with a `half` result converts a value of the slot that may be filtered
/// (`half::TexelLanes::Filtered`), whose packed class takes the routine's `OTHER` arm: where
/// none does, the arm runs only for an unmeasured class without a packed field.
pub half_filtered: bool,
/// A `half` conversion of the slot on a device that samples through Metal's own texture unit
/// notes the bound format where its class is unmeasured there
/// (`TexelFormat::unmeasured_on_metal_sampler`): the slot declares its `UnmeasuredTexels`
@@ -265,7 +261,6 @@ impl SlotPlan {
sparse_writes: false,
half_format: false,
texel_format: false,
half_filtered: false,
unmeasured: false,
swizzle: false,
constant_lanes: false,
+56 -159
View File
@@ -105,31 +105,14 @@ pub struct SamplerUse {
/// The sampled texture has an integer format: border colors are then `INT_*`, and every
/// filter is nearest.
pub integer_texture: bool,
/// The shader samples a cube with explicit gradients through this use in the form a route
/// the device's description does not state takes, Metal's isotropic footprint (the major
/// axis alone), through a sampler that may be anisotropic: a runtime sampler's, or an
/// anisotropic constexpr one's. Its Vulkan sampler is isotropic ([`vk_sampler`]), so the
/// device filters that footprint (`PrecisionNote::CubeGradientFootprint`) where the function
/// does not emulate Metal's anisotropic filter, whose taps read explicit levels.
pub cube_gradient: bool,
}
impl SamplerUse {
/// A use with the given comparison and texture numeric type, without explicit cube
/// gradients.
/// A use with the given comparison and texture numeric type.
pub fn new(compare: bool, integer_texture: bool) -> SamplerUse {
SamplerUse {
compare,
integer_texture,
cube_gradient: false,
}
}
/// This use, sampling a cube with explicit gradients or not.
pub fn with_cube_gradient(self, cube_gradient: bool) -> SamplerUse {
SamplerUse {
cube_gradient,
..self
}
}
}
@@ -214,17 +197,6 @@ pub(crate) fn query_min_level(desc: &SamplerDescriptor) -> u32 {
}
}
/// Whether a sampler `desc` used as `use_` takes its level clamp on Metal's grid, so that a level
/// on that grid handed to it reads Metal's level and weight: a sampler of a texture whose texels
/// are filtered (not an integer one), with a nearest or linear mip filter, one filter for
/// minification and magnification (so the level's sign chooses nothing), and no anisotropy.
pub(crate) fn clamps_on_grid(desc: &SamplerDescriptor, use_: SamplerUse) -> bool {
!use_.integer_texture
&& desc.mip_filter != SamplerMipFilter::NotMipmapped
&& desc.min_filter == desc.mag_filter
&& desc.max_anisotropy <= 1
}
/// Whether a sampler of `shape` (the descriptor's facts, [`SamplerDescriptor::shape`]) used as
/// `use_` can be a Vulkan sampler on `profile`. The binder's plan checks the bound shape with this
/// at plan time for the binding's use; [`vk_sampler`] checks its descriptor with it, so the two
@@ -268,16 +240,14 @@ pub fn check_sampler(
/// [`check_sampler`] for a sampler an argument buffer lists, which a function reads without
/// knowing its state: anisotropy above 1 without `samplerAnisotropy` is refused too, since such a
/// function neither emulates Metal's anisotropic filter through it nor records the isotropic
/// filter its Vulkan sampler takes there (`lower::sampler::anisotropic`'s reach), but on a use with
/// explicit cube gradients, whose sampler is isotropic on every device
/// ([`SamplerUse::cube_gradient`]).
/// filter its Vulkan sampler takes there (`lower::sampler::anisotropic`'s reach).
pub(crate) fn check_argument_sampler(
shape: &SamplerShape,
use_: SamplerUse,
profile: &DeviceProfile,
) -> Result<(), Error> {
check_sampler(shape, use_, profile)?;
if shape.anisotropic && !use_.cube_gradient && !profile.fields().images.sampler_anisotropy {
if shape.anisotropic && !profile.fields().images.sampler_anisotropy {
return Err(Unsupported::needs(
Feature::SamplerAnisotropy,
Capability::Feature(VkFeature::SamplerAnisotropy),
@@ -325,19 +295,11 @@ pub(crate) fn vk_filtering(
/// filters its clamp is `[0, 0]`, where that sampler reads Metal's `NotMipmapped`. With filters
/// that differ there, no clamp reads Metal's answer (`docs/FAST-PATHS.md`, known gaps).
///
/// Its level clamp is Metal's on Metal's level grid for a texture whose texels it filters, with a
/// mip filter. Under a nearest mip filter each bound is the level the filter reads at it (Metal
/// truncates the level's fraction onto sixty-fourths and reads the next level past one half); under
/// a linear one each bound is truncated onto sixty-fourths. Metal's rule is monotone in the level,
/// so a level clamped into these bounds reads what Metal reads of the level clamped into the
/// descriptor's. A fragment function's `calculate_clamped_lod` answers the level so clamped for
/// every sampler, whatever its filters and anisotropy (on an M4), so the bounds are on the grid for
/// every such sampler, with one exception where the min and mag filters differ or the sampler is
/// anisotropic (`clamps_on_grid` false): a bound above 0 whose grid value is 0 stays as given,
/// since Vulkan reads the mag filter at a clamped level of 0 where Metal reads the min filter at a
/// level above 0. Every sample keeps the device's level, so the bounds on the grid are expected to
/// read closer to Metal's level, unmeasured. An integer texture's sampler
/// keeps the descriptor's clamp, its lower bound at least 0.
/// Its level clamp is the descriptor's, its lower bound at least 0: the device clamps its own level
/// into it and selects and blends levels at its own precision (`PrecisionNote::DeviceSampling` off
/// Metal's own sampler). Metal truncates the clamped level's fraction onto sixty-fourths and reads
/// a nearest mip filter's next level past one half; MoltenVK hands the clamp to Metal's sampler,
/// which does so itself.
///
/// Refusals are [`check_sampler`]'s, for the descriptor's shape and the use.
pub fn vk_sampler(
@@ -380,18 +342,6 @@ pub fn vk_sampler(
} else {
vk::SamplerMipmapMode::LINEAR
};
// The clamp is Metal's on its level grid: a nearest mip filter's bounds are the levels it reads
// at them, a linear one's are truncated onto sixty-fourths. Where the filters differ or the
// sampler is anisotropic (`clamps_on_grid` false), a bound above 0 whose grid value is 0 stays
// as given, so the device's level stays above 0 and keeps Metal's minification filter there.
let grid = clamps_on_grid(desc, use_);
let on_grid = |bound: f32, level: f32| {
if !grid && bound > 0.0 && level <= 0.0 {
bound
} else {
level
}
};
// Metal's own sampler (MoltenVK) handed anisotropy reads a sampler without a mip filter whose
// filters agree as Metal's `NotMipmapped` at the clamp `[0, 0]`, whatever the descriptor's
// clamps, and otherwise at none it takes: a bound of a sixty-fourth or more (`0.25` included)
@@ -414,20 +364,8 @@ pub fn vk_sampler(
let (min_lod, max_lod) = not_mipmapped_lods(lo, hi);
(vk::SamplerMipmapMode::NEAREST, min_lod, max_lod)
}
SamplerMipFilter::Nearest if use_.integer_texture => {
(vk::SamplerMipmapMode::NEAREST, lo.max(0.0), hi)
}
SamplerMipFilter::Nearest => (
vk::SamplerMipmapMode::NEAREST,
on_grid(lo, nearest_level(lo) as f32),
on_grid(hi, nearest_level(hi) as f32),
),
SamplerMipFilter::Linear if use_.integer_texture => (linear_mip, lo.max(0.0), hi),
SamplerMipFilter::Linear => (
linear_mip,
on_grid(lo, level_on_grid(lo)),
on_grid(hi, level_on_grid(hi)),
),
SamplerMipFilter::Nearest => (vk::SamplerMipmapMode::NEAREST, lo.max(0.0), hi),
SamplerMipFilter::Linear => (linear_mip, lo.max(0.0), hi),
};
let filter = |f| {
if use_.integer_texture {
@@ -461,9 +399,8 @@ pub fn vk_sampler(
/// Anisotropy is a quality bound in both APIs; Vulkan requires it within the limit. It is a
/// filter, so an integer texture has none. A sampler with a nearest min or mag filter is handed
/// its degree too: Vulkan leaves the anisotropic scheme to the implementation (ANV's filters a
/// nearest one linearly). A use with explicit cube gradients in the isotropic form
/// ([`SamplerUse::cube_gradient`]) is handed none, and so is every sampler on a device without
/// `samplerAnisotropy`, where the emulation's taps read the isotropic sampler
/// nearest one linearly). A sampler on a device without `samplerAnisotropy` is handed none, where
/// the emulation's taps read the isotropic sampler
/// (`VUID-VkSamplerCreateInfo-anisotropyEnable-01070`: "If the samplerAnisotropy feature is not
/// enabled, anisotropyEnable must be VK_FALSE").
pub(crate) fn device_anisotropy(
@@ -471,10 +408,7 @@ pub(crate) fn device_anisotropy(
use_: SamplerUse,
profile: &DeviceProfile,
) -> bool {
desc.max_anisotropy > 1
&& profile.fields().images.sampler_anisotropy
&& !use_.cube_gradient
&& !use_.integer_texture
desc.max_anisotropy > 1 && profile.fields().images.sampler_anisotropy && !use_.integer_texture
}
/// [`device_anisotropy`] of an anisotropic sampler under `use_` on `profile`, by the filters a
@@ -1629,15 +1563,13 @@ mod tests {
assert_eq!(s.max_anisotropy, None, "isotropic without the feature");
let s = vk_sampler(&aniso, SamplerUse::default(), all.profile()).unwrap();
assert_eq!(s.max_anisotropy, Some(16.0), "clamped to the device limit");
// An argument buffer's sampler needs the feature, but for a cube's explicit gradients.
// An argument buffer's sampler needs the feature.
let shape = aniso.shape();
let err = check_argument_sampler(&shape, SamplerUse::default(), none.profile());
assert_eq!(
feature(err.unwrap_err()),
needs(VkFeature::SamplerAnisotropy)
);
let gradients = SamplerUse::default().with_cube_gradient(true);
assert!(check_argument_sampler(&shape, gradients, none.profile()).is_ok());
assert!(check_argument_sampler(&shape, SamplerUse::default(), all.profile()).is_ok());
for (p, compare) in [(&none, false), (&none, true), (&all, false), (&all, true)] {
let s = vk_sampler(&minmax, SamplerUse::new(compare, false), p.profile()).unwrap();
@@ -2212,13 +2144,10 @@ mod tests {
);
}
/// A sampler's word holds the levels a nearest mip filter reads at its clamp (the default
/// clamp's are the word 0's), and a sampler taking one filter both ways, isotropic, of a
/// filtered texture, takes its clamp on Metal's grid: a nearest mip filter's those levels, a
/// linear one's the bounds truncated onto sixty-fourths. Every other sampler keeps its clamp as
/// given.
/// A sampler's word holds the levels a nearest mip filter reads at its clamp on Metal's grid
/// (the default clamp's are the word 0's).
#[test]
fn a_samplers_clamp_is_metals_on_its_level_grid() {
fn a_samplers_word_holds_metals_levels_on_its_grid() {
let levels = SamplerWord::LEVEL_MIN | SamplerWord::LEVEL_MAX;
assert_eq!(SamplerWord::of(&metal_default()).0 & levels, 0);
let below_33 = (33.0f32 / 64.0).next_down();
@@ -2242,7 +2171,6 @@ mod tests {
assert_eq!(level_on_grid(below_33), 0.5);
assert_eq!(level_on_grid(f32::MAX), f32::MAX);
let dev = device(&[VkFeature::SamplerAnisotropy], &[]);
let mut d = metal_default();
d.mip_filter = SamplerMipFilter::Nearest;
d.lod_min_clamp = 0.6;
@@ -2253,81 +2181,51 @@ mod tests {
LAST_WORD_LEVEL - ((w >> SamplerWord::LEVEL_MAX_SHIFT) & 0xf),
3
);
}
/// The device is handed the descriptor's level clamp, its lower bound at least 0, whatever the
/// mip filter, the filters, the anisotropy and the use: it clamps and selects its own level.
#[test]
fn a_samplers_clamp_is_the_descriptors() {
let dev = device(&[VkFeature::SamplerAnisotropy], &[]);
let lods = |d: &SamplerDescriptor, use_| {
let s = vk_sampler(d, use_, dev.profile()).unwrap();
(s.min_lod, s.max_lod)
};
assert_eq!(lods(&d, SamplerUse::default()), (1.0, 3.0));
d.mip_filter = SamplerMipFilter::Linear;
assert_eq!(lods(&d, SamplerUse::default()), (38.0 / 64.0, 172.0 / 64.0));
// Both filters linear alike; and with a comparison.
d.min_filter = SamplerMinMagFilter::Linear;
d.mag_filter = SamplerMinMagFilter::Linear;
assert_eq!(
lods(&d, SamplerUse::new(true, false)),
(38.0 / 64.0, 172.0 / 64.0)
);
// An integer texture's sampler keeps the clamp as given.
assert_eq!(lods(&d, SamplerUse::new(false, true)), (0.6, 2.7));
// Filters that differ, and anisotropy, take the grid too: Metal's fragment
// `calculate_clamped_lod` answers the level clamped on it through every sampler.
d.mag_filter = SamplerMinMagFilter::Nearest;
assert!(!clamps_on_grid(&d, SamplerUse::default()));
assert_eq!(lods(&d, SamplerUse::default()), (38.0 / 64.0, 172.0 / 64.0));
d.min_filter = SamplerMinMagFilter::Nearest;
d.max_anisotropy = 4;
assert_eq!(lods(&d, SamplerUse::default()), (38.0 / 64.0, 172.0 / 64.0));
d.mip_filter = SamplerMipFilter::Nearest;
d.lod_min_clamp = 2.505;
d.lod_max_clamp = f32::MAX;
assert_eq!(
lods(&d, SamplerUse::default()),
(2.0, LAST_WORD_LEVEL as f32)
);
assert!(!clamps_on_grid(&metal_default(), SamplerUse::default()));
}
/// Where the min and mag filters differ or the sampler is anisotropic, a bound above 0 whose
/// grid value is 0 stays as given, so the device's level stays above 0 (Vulkan's minification)
/// exactly where Metal's is; every other bound is on Metal's grid.
#[test]
fn a_bound_off_the_grid_keeps_metals_filter_choice() {
let dev = device(&[VkFeature::SamplerAnisotropy], &[]);
for (minf, magf, aniso) in [
(SamplerMinMagFilter::Linear, SamplerMinMagFilter::Nearest, 1),
(SamplerMinMagFilter::Nearest, SamplerMinMagFilter::Linear, 1),
(SamplerMinMagFilter::Linear, SamplerMinMagFilter::Linear, 4),
] {
for (mip, lo, hi, min_lod, max_lod) in [
(SamplerMipFilter::Linear, 0.01, f32::MAX, 0.01, f32::MAX),
(SamplerMipFilter::Linear, 0.01, 0.012, 0.01, 0.012),
for mip in [SamplerMipFilter::Nearest, SamplerMipFilter::Linear] {
for (minf, magf, aniso) in [
(
SamplerMipFilter::Linear,
1.3,
2.7,
83.0 / 64.0,
172.0 / 64.0,
SamplerMinMagFilter::Nearest,
SamplerMinMagFilter::Nearest,
1,
),
(SamplerMinMagFilter::Linear, SamplerMinMagFilter::Linear, 1),
(SamplerMinMagFilter::Linear, SamplerMinMagFilter::Nearest, 1),
(
SamplerMinMagFilter::Nearest,
SamplerMinMagFilter::Nearest,
4,
),
(SamplerMipFilter::Linear, 0.0, 0.3, 0.0, 19.0 / 64.0),
(SamplerMipFilter::Nearest, 0.3, 0.4, 0.3, 0.4),
(SamplerMipFilter::Nearest, 0.3, 2.7, 0.3, 3.0),
(SamplerMipFilter::Nearest, 2.5, 2.5, 2.0, 2.0),
(SamplerMipFilter::Nearest, 0.0, 0.5, 0.0, 0.5),
] {
let mut d = metal_default();
(d.min_filter, d.mag_filter, d.max_anisotropy) = (minf, magf, aniso);
(d.mip_filter, d.lod_min_clamp, d.lod_max_clamp) = (mip, lo, hi);
let s = vk_sampler(&d, SamplerUse::default(), dev.profile()).unwrap();
let what = format!("{minf:?}/{magf:?} x{aniso} {mip:?} [{lo}, {hi}]");
assert_eq!((s.min_lod, s.max_lod), (min_lod, max_lod), "{what}");
// The device's level at a level `l`: minification exactly where Metal's is.
for l in [-1.0f32, 0.0, 0.005, 0.25, 0.5, 1.0, 3.0] {
let device = l.clamp(s.min_lod, s.max_lod) > 0.0;
let metal = l.max(lo).min(hi) > 0.0;
assert_eq!(device, metal, "{what} at {l}");
for (lo, hi) in [(0.6, 2.7), (0.01, 0.012), (2.505, f32::MAX), (0.0, 0.3)] {
let mut d = metal_default();
(d.min_filter, d.mag_filter, d.max_anisotropy) = (minf, magf, aniso);
(d.mip_filter, d.lod_min_clamp, d.lod_max_clamp) = (mip, lo, hi);
let what = format!("{minf:?}/{magf:?} x{aniso} {mip:?} [{lo}, {hi}]");
for use_ in [
SamplerUse::default(),
SamplerUse::new(true, false),
SamplerUse::new(false, true),
] {
assert_eq!(lods(&d, use_), (lo, hi), "{what} {use_:?}");
}
}
}
}
let mut d = metal_default();
d.mip_filter = SamplerMipFilter::Linear;
d.lod_min_clamp = -1.0;
assert_eq!(lods(&d, SamplerUse::default()).0, 0.0);
}
#[test]
@@ -2403,9 +2301,8 @@ mod tests {
/// (`lower::sampler::anisotropic`'s `minified_level`): a runtime sampler's by the filters its
/// word states (`device_anisotropy_by_filters`), which must be `vk_sampler`'s own flag
/// (`anisotropyEnable`, `max_anisotropy` set) for every sampler a word of those filters
/// states, on every committed profile, for every use the emulation reaches (no comparison, no
/// integer texture, with or without explicit cube gradients in the isotropic form), whatever
/// the sampler's other fields.
/// states, on every committed profile, for the use the emulation reaches (no comparison, no
/// integer texture), whatever the sampler's other fields.
#[test]
fn the_word_filters_state_the_device_samplers_anisotropy() {
use SamplerMinMagFilter as F;
@@ -2415,8 +2312,8 @@ mod tests {
desc.features.insert(VkFeature::SamplerAnisotropy);
desc.limits.max_sampler_anisotropy_bits = 16f32.to_bits();
let dev = Device::new(desc, DevicePolicy::default()).unwrap();
for cube_gradient in [false, true] {
let use_ = SamplerUse::new(false, false).with_cube_gradient(cube_gradient);
{
let use_ = SamplerUse::new(false, false);
let (linear, nearest) = device_anisotropy_by_filters(use_, dev.profile());
for (min, mag) in [
(F::Nearest, F::Nearest),
+4 -15
View File
@@ -167,15 +167,6 @@ impl TexelFormat {
/// every treatment converts alike.
pub const OTHER: TexelFormat = TexelFormat(0);
/// The 8-bit unsigned normalized grid, `16 · 255`.
pub const GRID8: u32 = 16 * 255;
/// The 8-bit signed normalized grid, `16 · 127`.
pub const GRID8S: u32 = 16 * 127;
/// The 16-bit unsigned normalized grid, `65535`.
pub const GRID16: u32 = 65535;
/// The 16-bit signed normalized grid, `32767`.
pub const GRID16S: u32 = 32767;
/// Bits `CORNER` to `CORNER + 3`: the [`CubeCorner`] of a format outside the measured
/// families whose cube gather's tap past both edges of a face is measured (module docs), else
/// 0. No other access reads them: such a format's class is otherwise [`OTHER`](Self::OTHER)'s.
@@ -222,13 +213,11 @@ impl TexelFormat {
/// Whether, on a device that samples through Metal's own texture unit, every access's `half`
/// result of the class is the device's `float` texel rounded to nearest even
/// (`SpecKey::PlainHalfTexels`): the class has no 32-bit float channels
/// ([`BicubicTexels::LINEAR`], whose samples round toward zero), no 16-bit normalized grid
/// ([`BicubicTexels::WIDE16`]) and no YCbCr field on the grid `8192`
/// ([`TexelFormat::YCBCR_8192`], ties away): the arms of the routine's Metal-sampler body
/// other than its rounding to nearest even (`lower::texture::half`).
/// (`SpecKey::PlainHalfTexels`): the class has no YCbCr field on the grid `8192`
/// ([`TexelFormat::YCBCR_8192`], ties away), the routine's one arm other than its rounding to
/// nearest even (`lower::texture::half`).
pub fn plain_on_metal_sampler(self) -> bool {
self.0 & (BicubicTexels::LINEAR | BicubicTexels::WIDE16 | TexelFormat::YCBCR_8192) == 0
self.0 & TexelFormat::YCBCR_8192 == 0
}
/// The families whose texels decode to no NaN: normalized channels, signed or not
@@ -1116,7 +1116,6 @@ mod bind_serde_round_trips {
class: crate::pipeline::sym::HandleClass::Sampler {
compare: false,
integer: false,
cube_gradient: false,
},
element: 5,
source: HeapSource::Used(3),
+70 -61
View File
@@ -794,21 +794,20 @@ pub enum PrecisionNote {
/// a texture that is not sparse is resident, inside it or outside; a read outside any texture
/// is resident; and an access of a sparse texture is not resident where a texel it counts is
/// unmapped, which reads zero memory (the out-of-bounds texel: zero, alpha 1 where the format
/// has none). The module answers all of that exactly for reads, on every device, and for a
/// sample or gather inside Metal's measured footprint rule (a constexpr sampler) the word too.
/// A pixel fetch, and a nearest sample or a gather inside the rule, read Metal's value too:
/// where the bound texture is a sparse image, a texel the word says is unmapped reads zero, and
/// the lanes Metal reads as constants (a channel the format lacks, through the texture's
/// swizzle) are set after the access (`SpecKey::ConstantLanes`); none of them is noted. What
/// stays the device's is noted: a filtered sample's lanes that are no constants over a texel in
/// a block of a sparse image that holds no mapped tile (zero on a device with
/// `residencyNonResidentStrict`; any value elsewhere, which the runtime announces as
/// `non-strict-residency`), and outside the footprint rule (a runtime sampler, mip levels,
/// repeat or mirrored addressing, an offset) the word, the device's `OpImageSparse*` residency,
/// whose footprint may count a texel of zero weight Metal does not (Vulkan's linear 2x2
/// footprint does, measured on lavapipe), and those lanes of a fetch-like access. Where the
/// profile does not enable `shaderResourceResidency` nothing is noted: the bound image holds
/// Metal's unmapped value, and the accesses its tile map answers are exact.
/// has none). The module answers all of that exactly for reads, on every device. A pixel
/// fetch reads Metal's value too: where the bound texture is a sparse image, a texel the word
/// says is unmapped reads zero, and the lanes Metal reads as constants (a channel the format
/// lacks, through the texture's swizzle) are set after every access (`SpecKey::ConstantLanes`);
/// none of them is noted. A sample's or gather's residency is the device's, noted: the word is
/// the device's `OpImageSparse*` residency, whose footprint may count a texel of zero weight
/// Metal does not (Vulkan's linear 2x2 footprint does, measured on lavapipe), and its lanes
/// that are no constants over a texel in a block of a sparse image that holds no mapped tile
/// are the device's non-resident value (zero on a device with `residencyNonResidentStrict`;
/// any value elsewhere, which the runtime announces as `non-strict-residency`). Where the
/// profile does not enable `shaderResourceResidency` the device has no residency of its own and
/// nothing is noted: the bound image holds Metal's unmapped value, and the slot's tile map
/// answers the word, by Metal's measured footprint rule for a sample or gather through a
/// constexpr sampler (`lower::sampler::footprint`), exactly.
SparseResidency,
/// A `float` NaN result's bit pattern follows the device: Metal answers the canonical
/// `0x7fc00000` for the NaN results of its float arithmetic and functions, and Vulkan states no
@@ -879,15 +878,11 @@ pub enum PrecisionNote {
/// select another level or filter than Metal's. A runtime or argument buffer's sampler takes
/// the form its word's anisotropy states.
///
/// Not recorded where the module takes Metal's footprint itself through a constexpr sampler
/// (`lower::sampler::anisotropic`, on a device without Metal's own sampler and on one whose
/// stage's cube-gradient route is not measured): Metal's level, and an anisotropic sampler's
/// taps (`PrecisionNote::AnisotropicFilter`). Where the route is not measured
/// (`CubeGradientRoute::Unmeasured`), every other sample hands the isotropic form, which
/// every measured route reads alike but on a `y` face under macOS 27, through a sampler made
/// isotropic for that use (`metal::sampler::SamplerUse::cube_gradient`): an anisotropic
/// sampler's footprint is then Metal's isotropic one, its major axis's, but where a runtime
/// sampler slot's variant takes Metal's taps.
/// Not recorded where the module takes Metal's footprint itself through an anisotropic
/// constexpr sampler on a device without `samplerAnisotropy` (`lower::sampler::anisotropic`):
/// Metal's level and taps (`PrecisionNote::AnisotropicFilter`). A driver whose route is not
/// measured takes Vulkan's rule's form (`CubeGradientRoute::Vulkan`), its reading of it the
/// device's own, recorded here.
///
/// Through MoltenVK's graphics route under macOS 27 (`CubeGradientRoute::AppleProjected`),
/// SPIRV-Cross's `spvGradientCube` hands Metal an `x` or `z` face's gradients as Metal's own,
@@ -910,37 +905,37 @@ pub enum PrecisionNote {
/// gradient's projection by at most `2^-24` of the major component's relative change: within
/// Vulkan's own level-of-detail approximation, but able to cross a level or filter boundary.
CubeGradientFootprint,
/// The module reads, gathers, or samples a texture with a `half` result. Metal converts the
/// texel to `half` by the bound format: measured for the 32-bit float, half-float, and 8- and
/// 16-bit normalized formats, which a texture slot converts exactly by its `TexelFormat`
/// specialization (`metal::texel_format`); a read, nearest sample, or gather of a slot bound in
/// an 8-bit sRGB format the device holds as its UNORM twin decodes the code exactly instead,
/// and a bicubic sample sums the codes' steps exactly, under the slot's `SrgbTexture` variant,
/// and records nothing. A texture buffer converts by its bound format the same way (Metal reads
/// a texture buffer's texels as a texture's: the P2a probe). A texture bound in another format
/// (sRGB otherwise, packed, depth, and the rest) and a heap element keep the exact rounding of
/// the device's `f32` texel to nearest even (`narrow::round_texel`), which Metal's conversion
/// may not be: Metal rounds a 32-bit float sample toward zero, and an 8- or 16-bit normalized
/// one onto its format's grid first. What a filtered sample converts is the filter's value
/// ([`PrecisionNote::HalfSampleFilter`]). Recorded wherever such an access is lowered;
/// validation derives no tolerance from it.
/// The module reads, gathers, or samples a texture with a `half` result, which is the device's
/// `f32` texel rounded to nearest even (`narrow::round_texel`) on every device, where Metal
/// converts the texel to `half` by the bound format. A read, nearest sample, or gather of a
/// slot bound in an 8-bit sRGB format the device holds as its UNORM twin decodes the code
/// exactly instead, and a bicubic sample sums the codes' steps exactly, under the slot's
/// `SrgbTexture` variant, and records nothing. What a filtered sample converts is the filter's
/// value ([`PrecisionNote::HalfSampleFilter`]). Validation derives no tolerance from it.
///
/// Native device sampling (a texel conversion): off Apple's GPUs (`VkProperty::MetalSampler`
/// keeps the conversion), every slot's access with a `half` result takes that rounding too,
/// and records this note. The recorded bound: the device's
/// `float` texel (within [`PrecisionNote::DeviceTexelConversion`]'s bound of Metal's) rounded
/// to nearest even is within one `half` ulp of Metal's `half` result (Metal rounds a 32-bit
/// float sample toward zero, a half-float linear sum with ties away from zero, and a normalized
/// value onto its grid first), but for a 32-bit float texel's sample past `±65504`, which Metal
/// saturates to `±65504` and the rounding takes to the infinity of its sign; a NaN is the
/// device's decode ([`PrecisionNote::DeviceNanEncoding`]).
/// Native device sampling (a texel conversion): off Apple's GPUs (without
/// `VkProperty::MetalSampler`) every access with a `half` result records this note. The
/// recorded bound: the device's `float` texel (within
/// [`PrecisionNote::DeviceTexelConversion`]'s bound of Metal's) rounded to nearest even is
/// within one `half` ulp of Metal's `half` result (Metal rounds a 32-bit float sample toward
/// zero, a half-float linear sum with ties away from zero, and a normalized value onto its grid
/// first), but for a 32-bit float texel's sample past `±65504`, which Metal saturates to
/// `±65504` and the rounding takes to the infinity of its sign; a NaN is the device's decode
/// ([`PrecisionNote::DeviceNanEncoding`]).
///
/// On a device that samples through Metal's own sampler, a sample with a `half` result
/// through a runtime sampler slot bound to a two-plane YCbCr texture on the grid `8192`
/// (the `_sRGB` twins, the unpacked 12-bit and the extended-range formats): where its word
/// reads one texel, the texel's step rounds to nearest even, where Metal rounds it with ties
/// away from zero, one `half` unit in the last place apart at a tie. The runtime announces it
/// at a draw or dispatch that binds such a texture there.
/// On a device that samples through Metal's own sampler the `f32` texel is Metal's `float`
/// result, and its nearest even `half` is Metal's `half` but for the classes the note is
/// recorded under, by the slot's bound format (`SpecKey::TexelFormat`): a 32-bit float
/// texel's sample, which Metal rounds toward zero (within one `half` ulp, but past `±65504` the
/// infinity of its sign where Metal saturates to `±65504`); a 16-bit normalized texel, whose
/// `float` steps `65455 / 65535`, `65519 / 65535` and `32759 / 32767` round twice (one `half`
/// ulp); and a format whose conversion is not measured (unbounded). A heap element and a depth
/// texture record it wherever they are accessed. A two-plane YCbCr texture on the grid `8192`
/// (the `_sRGB` twins, the unpacked 12-bit and the extended-range formats) keeps Metal's
/// rounding of one texel's step with ties away from zero, but in a sample through a runtime
/// sampler slot: where its word reads one texel, the step rounds to nearest even, one `half`
/// ulp apart at a tie, announced by the runtime at a draw or dispatch that binds such a texture
/// there.
HalfTexelConversion,
/// The module samples a texture with a `half` result through a filter (linear minification
/// or magnification, a linear mip filter, anisotropy, or a runtime sampler) that Metal's own
@@ -1066,6 +1061,15 @@ pub enum PrecisionNote {
/// `MetalHalfStorageWrites`; a 1-bit alpha on a device measured to store every other
/// normalized channel's): Metal stores each normalized channel's exact product rounded with a
/// tie away from zero (a 1-bit channel 1 only above one half) and a half rounded toward zero.
/// An integer texel a function writes to a storage texture of the float class that may hold a
/// half-float or small-float format (`RG11B10Float`), its lanes' bits as the `float` written,
/// records it on every device: Metal's integer store rounds such a channel to nearest even,
/// the device's store as it rounds a `float` write (toward zero on every measured driver:
/// within one unit in the last place of the channel's value, a finite value past 65504 stored
/// as 65504 where Metal's `half` is the infinity). So does a fragment function's `float` output
/// blended in the shader into a 16-bit float attachment it renders through a storage image (the
/// pixel interlock's fetch), whose `half` the store rounds, on a profile without
/// `DriverDeviation::MetalHalfStorageWrites`.
///
/// Also: a blend into a packed 16-bit unorm attachment (`B5G6R5Unorm`, `A1BGR5Unorm`,
/// `ABGR4Unorm`, `BGR5A1Unorm`) reads what the device's attachment holds, its channels' codes,
@@ -1340,10 +1344,8 @@ pub enum PrecisionNote {
/// tap the device's isotropic filter: a sample without comparison of a 2D texture or 2D array
/// at the fragment's implicit level or with explicit gradients, or of a cube or cube array with
/// explicit gradients, through a constexpr sampler of `maxAnisotropy` above 1, or through a
/// runtime sampler slot whose word states anisotropy (under that word alone). A cube's sample
/// is emulated on Metal's own sampler too where the stage's cube-gradient route is not measured
/// (`CubeGradientRoute::Unmeasured`), its taps Metal's own samples at explicit levels. A device
/// with the feature samples with its own anisotropic filter. Metal's footprint (its gradient lengths,
/// runtime sampler slot whose word states anisotropy (under that word alone). A device with
/// the feature samples with its own anisotropic filter. Metal's footprint (its gradient lengths,
/// piecewise-linear `log2`, level, tap count, tap weights and direction) is reproduced as
/// measured on an Apple M4 (the M3 Max answering identically), with this residue:
/// - the level is off by `1/256` of a level on about 1% of anisotropic samples;
@@ -1481,11 +1483,18 @@ pub enum PrecisionNote {
/// Validation derives no tolerance from it; C3 takes a row it leaves unbounded as showing
/// the fast-math regrouping cause.
HalfOutputFastMathBlend,
/// Native device sampling: the module hands a sample, gather or comparison to the device's
/// own sampler on a device whose sampler is not Metal's (the module requires
/// Native device sampling: the module hands a sample, gather, comparison or level query to
/// the device's own sampler on a device whose sampler is not Metal's (the module requires
/// `VkProperty::DeviceSampling`). Its filter, footprint, level selection, anisotropy, decode
/// and comparison are the device's. A device that samples through Metal's own sampler
/// (MoltenVK on Apple's GPU) never records it.
/// and comparison are the device's. So are its level clamp, the sampler descriptor's
/// `lodMinClamp` and `lodMaxClamp` as given, which Metal holds on its `1/64` grid
/// (`metal::sampler::vk_sampler`), a nearest mip filter's level at a clamp halfway between two
/// levels (Metal reads the lower, `ceil(λ + 0.5) - 1`; Vulkan lets the device round either
/// way, and lavapipe reads the upper at `lodMinClamp` 1.5), and its reading of a subnormal normalized coordinate, which
/// Metal's texture unit reads as the zero of its sign before the address mode decides (a
/// clamp-to-zero axis then reads texel 0 just outside the level, measured on an Apple M3 Max
/// on `R32Float`). A device that samples through Metal's own sampler (MoltenVK on Apple's GPU)
/// never records it.
///
/// The recorded bound, measured against an Apple M4 on 2D textures of one level (the deviation
/// probe: 4,096 coordinates per case, a third near the 1/256 grid, under clamp to edge, repeat,
@@ -5,10 +5,12 @@
//! float written to a normalized attachment as the exact product with the format's maximum code
//! rounded to nearest, to an 8-bit sRGB one through its twelve-bit encode, and to a half-float one
//! rounded toward zero (`metal::format::write_conversion`, probes on an Apple M3 Max and an M4).
//! Vulkan's drivers round the `f32` product with ties to even, encode sRGB by their own
//! approximations, and round a half to nearest, so near a tie they may store another code
//! (`runtime_lane::color_writes`: ANV, RADV, NVIDIA and lavapipe); only MoltenVK on Apple's GPUs
//! stores Metal's (`VkProperty::MetalColorWrites`). The map names each channel's rule so the
//! Vulkan's drivers round the `f32` product with ties to even and encode sRGB by their own
//! approximations, so near a tie they may store another code (`runtime_lane::color_writes`: ANV,
//! RADV, NVIDIA and lavapipe). Their half-float and small-float channels round toward zero as
//! Metal's do where measured (`DriverDeviation::MetalSmallFloatColorWrites`: RADV on the Radeon
//! 780M, ANV on the Iris Xe and the UHD 770, NVIDIA on the RTX 3090, NaNs aside); only MoltenVK on
//! Apple's GPUs stores Metal's codes for every format (`VkProperty::MetalColorWrites`). The map names each channel's rule so the
//! fragment function can record where the device's conversion is not measured to be Metal's
//! (`PrecisionNote::DeviceColorConversion`); it rounds none of them. On MoltenVK the map keeps the
//! half-float channels alone, which record the device's NaN encoding of a `half` output.
+40 -79
View File
@@ -241,7 +241,6 @@ pub enum HandleClass {
Sampler {
compare: bool,
integer: bool,
cube_gradient: bool,
},
/// The visible-function tables an argument buffer can name: a read-only storage buffer of
/// one table's words (`pipeline::table`) per element.
@@ -254,21 +253,15 @@ impl HandleClass {
HandleClass::Sampler {
compare: use_.compare,
integer: use_.integer_texture,
cube_gradient: use_.cube_gradient,
}
}
/// The sampler use of a sampler class, `None` for an image class.
pub fn sampler_use(self) -> Option<crate::metal::sampler::SamplerUse> {
match self {
HandleClass::Sampler {
compare,
integer,
cube_gradient,
} => Some(
crate::metal::sampler::SamplerUse::new(compare, integer)
.with_cube_gradient(cube_gradient),
),
HandleClass::Sampler { compare, integer } => {
Some(crate::metal::sampler::SamplerUse::new(compare, integer))
}
HandleClass::Image(_) | HandleClass::FunctionTable => None,
}
}
@@ -491,68 +484,45 @@ pub struct CombinedSampler {
pub compare: bool,
/// The texture's sampled type is an integer type.
pub integer: bool,
/// The shader samples a cube with explicit gradients through this binding in the isotropic
/// form a route its device's description does not state takes, through a sampler that may be
/// anisotropic (a runtime one, or an anisotropic constexpr one): the sampler is made isotropic
/// for it (`metal::sampler::SamplerUse::cube_gradient`). Elsewhere a sampler's footprint
/// follows its anisotropy.
pub cube_gradient: bool,
}
impl CombinedSampler {
/// Sampler `sampler` used with `compare` on a texture that is `integer` or not, without
/// explicit cube gradients.
/// Sampler `sampler` used with `compare` on a texture that is `integer` or not.
pub fn new(sampler: SamplerRef, compare: bool, integer: bool) -> CombinedSampler {
CombinedSampler {
sampler,
compare,
integer,
cube_gradient: false,
}
}
/// This use, sampling a cube with explicit gradients or not.
pub fn with_cube_gradient(self, cube_gradient: bool) -> CombinedSampler {
CombinedSampler {
cube_gradient,
..self
}
}
/// The use as a heap sampler symbol's index, or a separate sampler's: bit 0 comparison, bit 1
/// an integer texel, bit 2 explicit cube gradients.
/// an integer texel.
pub fn heap_index(&self) -> u32 {
u32::from(self.compare)
| (u32::from(self.integer) << 1)
| (u32::from(self.cube_gradient) << 2)
u32::from(self.compare) | (u32::from(self.integer) << 1)
}
/// Sampler `sampler` with the use a heap or separate sampler symbol's index `index` states
/// ([`CombinedSampler::heap_index`]).
pub fn from_heap_index(sampler: SamplerRef, index: u32) -> CombinedSampler {
CombinedSampler::new(sampler, index & 1 != 0, index & 2 != 0)
.with_cube_gradient(index & 4 != 0)
}
/// The use's rank in a separate texture symbol's index: comparison, then an integer texel, then
/// explicit cube gradients, from the most significant bit down, so the ranks order as the
/// uses' fields do in `CombinedSampler`'s derived order.
/// The use's rank in a separate texture symbol's index: comparison, then an integer texel,
/// from the most significant bit down, so the ranks order as the uses' fields do in
/// `CombinedSampler`'s derived order.
fn use_rank(&self) -> u32 {
(u32::from(self.compare) << 2)
| (u32::from(self.integer) << 1)
| u32::from(self.cube_gradient)
(u32::from(self.compare) << 1) | u32::from(self.integer)
}
/// Sampler `sampler` with the use of rank `rank` ([`CombinedSampler::use_rank`]).
fn from_use_rank(sampler: SamplerRef, rank: u32) -> CombinedSampler {
CombinedSampler::new(sampler, rank & 4 != 0, rank & 2 != 0)
.with_cube_gradient(rank & 1 != 0)
CombinedSampler::new(sampler, rank & 2 != 0, rank & 1 != 0)
}
/// The use the binder (and link, for a constexpr sampler) builds the `VkSampler` for.
pub fn sampler_use(&self) -> crate::metal::sampler::SamplerUse {
crate::metal::sampler::SamplerUse::new(self.compare, self.integer)
.with_cube_gradient(self.cube_gradient)
}
}
@@ -784,9 +754,8 @@ pub enum SpecKey {
UnmeasuredTexels(SlotRef),
/// Boolean: on a device that samples through Metal's own texture unit, the texture bound to
/// the slot converts every texel an image instruction hands back to a `half` result as that
/// `float` texel rounded to nearest even (default true): its class has no 32-bit float
/// channels (whose samples round toward zero), no 16-bit normalized grid and no YCbCr field on
/// the grid `8192` (`metal::texel_format::TexelFormat::plain_on_metal_sampler`). A slot bound
/// `float` texel rounded to nearest even (default true): its class has no YCbCr field on the
/// grid `8192` (`metal::texel_format::TexelFormat::plain_on_metal_sampler`). A slot bound
/// to nothing takes true: its zero texel converts alike under every class. Where it holds, such
/// an access converts the instruction's own texel by the device's conversion, which Metal's
/// compiler may fold into the image instruction (`lower::texture::half`), and specialization
@@ -1156,13 +1125,9 @@ mod tests {
for words in [[0, 0], [u64::MAX >> 1, 7]] {
for compare in [false, true] {
for integer in [false, true] {
for cube_gradient in [false, true] {
let c =
CombinedSampler::new(SamplerRef::Constexpr(words), compare, integer)
.with_cube_gradient(cube_gradient);
let s = ResourceSlot::heap_sampler(Stage::Fragment, c);
assert_eq!(s.heap_sampler_use(), Some(c));
}
let c = CombinedSampler::new(SamplerRef::Constexpr(words), compare, integer);
let s = ResourceSlot::heap_sampler(Stage::Fragment, c);
assert_eq!(s.heap_sampler_use(), Some(c));
}
}
}
@@ -1191,35 +1156,31 @@ mod tests {
] {
for compare in [false, true] {
for integer in [false, true] {
for cube_gradient in [false, true] {
let c = CombinedSampler::new(sampler, compare, integer)
.with_cube_gradient(cube_gradient);
assert_eq!(
ResourceSlot::separate_sampler(Stage::Fragment, c)
.separate_sampler_use(),
Some(c)
);
for texture in [0, 1, 127, (1 << 28) - 1] {
let s = ResourceSlot::separate_texture(Stage::Fragment, texture, c)
.expect("a slot the index holds");
assert_eq!(s.separate_texture_of(), Some((texture, c)));
let combined = ResourceSlot {
stage: Stage::Fragment,
kind: ResourceKind::CombinedTextureSampler(c),
index: texture,
};
assert_eq!(combined.separate_texture_of(), None);
pairs.push((combined, s));
}
assert_eq!(
ResourceSlot::separate_texture(Stage::Fragment, 1 << 28, c),
None
);
assert_eq!(
ResourceSlot::separate_texture(Stage::Fragment, u32::MAX, c),
None
);
let c = CombinedSampler::new(sampler, compare, integer);
assert_eq!(
ResourceSlot::separate_sampler(Stage::Fragment, c).separate_sampler_use(),
Some(c)
);
for texture in [0, 1, 127, (1 << 28) - 1] {
let s = ResourceSlot::separate_texture(Stage::Fragment, texture, c)
.expect("a slot the index holds");
assert_eq!(s.separate_texture_of(), Some((texture, c)));
let combined = ResourceSlot {
stage: Stage::Fragment,
kind: ResourceKind::CombinedTextureSampler(c),
index: texture,
};
assert_eq!(combined.separate_texture_of(), None);
pairs.push((combined, s));
}
assert_eq!(
ResourceSlot::separate_texture(Stage::Fragment, 1 << 28, c),
None
);
assert_eq!(
ResourceSlot::separate_texture(Stage::Fragment, u32::MAX, c),
None
);
}
}
}
@@ -1082,6 +1082,112 @@ fn integer_writes_saturate_to_the_bound_formats_channels() {
assert_eq!(checked, (11 * 2 + 5) * 2);
}
/// An `int` or `uint` write into a texture of the float class in a half-float or small-float
/// format stores the `float` of each lane's bits as written: the device's store converts it, as
/// it converts every `float` write, where Metal's integer store rounds to nearest even, so the
/// module records `PrecisionNote::DeviceColorConversion` (and requires no
/// `VkProperty::MetalHalfStorageWrites`, whose rounding is Metal's `float` write's). A 32-bit
/// float format's needs no conversion, and records nothing. On the interpreter the image holds the
/// written `f32` itself.
#[test]
fn integer_writes_into_narrow_floats_take_the_devices_conversion() {
use crate::device::requirements::VkProperty;
use crate::pipeline::lower_inputs::{StorageImageChoice, StorageImageClass};
use crate::vk::Format as F;
let cases = [
(Ty::Uint, F::R16G16B16A16_SFLOAT, true),
(Ty::Int, F::R16G16B16A16_SFLOAT, true),
(Ty::Uint, F::B10G11R11_UFLOAT_PACK32, true),
(Ty::Int, F::R32G32B32A32_SFLOAT, false),
];
let mut checked = 0;
for stem in ["lavapipe", "moltenvk-m3"] {
let p = profile(stem, DevicePolicy::default()).expect("profile");
for (ty, format, narrow) in cases {
let what = format!("write {ty:?} over {format:?} on {stem}");
let Some(bc) = assemble(&what, &write_kernel(ty)) else {
return;
};
let mut inputs = LowerInputs::new();
inputs.cross_class.insert(TEXTURE, SampledType::Float);
inputs.storage_images.insert(
TEXTURE,
StorageImageChoice::new(format, StorageImageClass::Identity),
);
validate(&bc, &inputs, &p, &what);
let consts = FunctionConstantValues::defaults();
let a = compile_bitcode(
&bc,
EntryRef::Name("k"),
&consts,
&p,
&inputs,
&mut meter(),
SPIRV_WORDS,
)
.unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(
a.precision.contains(&PrecisionNote::DeviceColorConversion),
narrow,
"{what}: {:?}",
a.precision
);
assert!(
!a.requirements
.properties
.contains(&VkProperty::MetalHalfStorageWrites),
"{what}"
);
let (plan, m) =
typed_module_with(&bc, "k", &p, &inputs).unwrap_or_else(|e| panic!("{what}: {e}"));
let push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)];
let lane = |n: u32, c: usize| WORDS[(n as usize * 4 + c) * 7 % WORDS.len()];
let src: Vec<u8> = (0..SIDE * SIDE)
.flat_map(|n| (0..4).flat_map(move |c| lane(n, c).to_le_bytes()))
.collect();
let mut spec = BTreeMap::new();
for axis in [Axis::X, Axis::Y, Axis::Z] {
spec.insert(SpecKey::LocalSize(axis), 1);
}
spec.insert(SpecKey::FlatLocalSize, 1);
let res = Resources {
buffers: vec![Buffer {
slot: Some(ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Buffer,
index: 0,
}),
address: None,
bytes: src,
}],
push,
spec,
};
let img = Image::new(resource(&m), [SIDE, SIDE, 1], 1, 1, 1);
let cfg = Config {
workgroups: [SIDE, SIDE, 1],
..Config::default()
};
let (_, images) = run_with_images(&m, &cfg, res, vec![img])
.unwrap_or_else(|e| panic!("{what}: interpreter: {e:?}"));
let img = images.into_iter().next().expect("image");
for n in 0..SIDE * SIDE {
let at = img.index(0, 0, 0, [n % SIDE, n / SIDE, 0]).expect("texel");
for c in 0..4 {
assert_eq!(
img.texels[at][c],
lane(n, c),
"{what}: texel {n} lane {c} stored {:#x}",
img.texels[at][c]
);
}
}
checked += 1;
}
}
assert_eq!(checked, 8);
}
/// A kernel's state for [`write_kernel`]: texture slot 0 bound in `pf` (shader write), buffer 0.
fn write_state(pf: PixelFormat) -> BindState {
let mut s = state(pf);
@@ -29,7 +29,9 @@ use std::path::Path;
use std::sync::Arc;
use crate::budget::Budget;
use crate::device::requirements::VkProperty;
use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile};
use crate::error::DriverDeviation;
use crate::library::{FunctionArtifact, Library};
use crate::metal::{BlendFactor, BlendOperation, ColorWriteMask, PixelFormat};
use crate::pipeline::artifact::PrecisionNote;
@@ -282,6 +284,24 @@ fn a_narrow_output_blends_a_fetched_sixteen_bit_float_attachment() {
a.facts
);
assert!(!a.precision.contains(&note), "{what}: {:?}", a.precision);
// A `float2` output's blend result is the storage image's store's to round to
// `half`: Metal's where the profile takes `MetalHalfStorageWrites`, whose property
// the module requires, else the device's, noted. A `half2` output's is a `half`.
let float = entry == "fbl_narrow_float2";
let metal = p.takes_driver_deviation(DriverDeviation::MetalHalfStorageWrites);
assert_eq!(
a.requirements
.properties
.contains(&VkProperty::MetalHalfStorageWrites),
float && metal,
"{what}"
);
assert_eq!(
a.precision.contains(&PrecisionNote::DeviceColorConversion),
float && !metal,
"{what}: {:?}",
a.precision
);
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
took = true;
checked += 1;
@@ -2093,14 +2093,15 @@ fn out_of_bounds_alpha_follows_the_bound_format() {
/// `a2_sparse_status` observes the residency of a sample and a gather of texture 0 through a
/// nearest, clamp-to-edge constexpr sampler, and of a read of texture 1. Each slot states
/// `RuntimeFact::SparseTexture`. On every device, with `shaderResourceResidency` or without, both
/// slots have the tile-map arm, slot 0's sample and gather through Metal's footprint: each slot's
/// `SparseTexture` specialization, which the plan sets from the bound texture's `sparse`
/// (`MTLTexture.isSparse`), and a `ResourceKind::TileMap` binding the plan writes as the slot's
/// `WriteSource::TileMap` (read by the kernel) for a sparse texture and as the zero buffer
/// otherwise.
/// `RuntimeFact::SparseTexture`, its `SparseTexture` specialization, which the plan sets from the
/// bound texture's `sparse` (`MTLTexture.isSparse`). Slot 1's read has the tile-map arm on every
/// device, and so has slot 0 where the device has no `shaderResourceResidency`, its sample and
/// gather through Metal's footprint: a `ResourceKind::TileMap` binding the plan writes as the
/// slot's `WriteSource::TileMap` (read by the kernel) for a sparse texture and as the zero buffer
/// otherwise. Where the device has residency, slot 0's sample and gather are the device's sparse
/// accesses (the sparse arm), with no tile map.
#[test]
fn a_sparse_texture_is_answered_from_its_tile_map_on_every_device() {
fn a_sparse_texture_is_answered_from_its_tile_map_where_the_device_has_no_residency() {
use crate::device::requirements::VkFeature;
use crate::pipeline::facts::RuntimeFact;
let Some(bc) = fixture("a2_sparse_status") else {
@@ -2124,11 +2125,11 @@ fn a_sparse_texture_is_answered_from_its_tile_map_on_every_device() {
.features
.contains(&VkFeature::ShaderResourceResidency);
let slots = [0, 1].map(|i| slot(Stage::Kernel, SlotClass::Texture, i));
for s in slots {
for (s, sampled) in slots.into_iter().zip([true, false]) {
let fact = RuntimeFact::SparseTexture {
slot: s,
sparse_arm: false,
tile_map: true,
sparse_arm: sampled && residency,
tile_map: !(sampled && residency),
};
assert!(
p.dependencies.iter().any(|d| d.fact == fact),
@@ -2173,12 +2174,16 @@ fn a_sparse_texture_is_answered_from_its_tile_map_on_every_device() {
"{stem}"
);
// Each sparse slot's tile map bound and read.
assert_eq!(tile_maps(&plan), [slots[0]], "{stem}");
let mapped: &[SlotRef] = match residency {
true => &slots[1..],
false => &slots,
};
assert_eq!(tile_maps(&plan), mapped[..mapped.len() - 1], "{stem}");
let both = p
.plan(&dev, &state(true, true).shape())
.unwrap_or_else(|e| panic!("{stem}: sparse slots: {e}"));
assert_eq!(tile_maps(&both), slots, "{stem}");
for s in slots {
assert_eq!(tile_maps(&both), mapped, "{stem}");
for &s in mapped {
assert!(
both.uses
.iter()
@@ -2213,12 +2218,13 @@ fn opcodes(words: &[u32]) -> BTreeSet<u32> {
/// `sps2_residency_probes` observes the residency of nearest and linear samples and a gather
/// through clamp-to-zero constexpr samplers at level 0, every one inside Metal's measured footprint
/// rule. On every device the module answers them from the texels Metal counts, through the tile map
/// of both slots, which bind a sparse texture: no sparse access. `PrecisionNote::SparseResidency`
/// stays only where the device has residency: there a sparse texture is a sparse image, whose
/// blocks that hold no mapped tile a filtered sample reads as the device does.
/// rule. Where the device has no `shaderResourceResidency` the module answers them from the texels
/// Metal counts, through the tile map of both slots, which bind a sparse texture: no sparse
/// access, and no note. Where it has, each is the device's sparse access, its residency the
/// device's, recorded as `PrecisionNote::SparseResidency`, and the sampled slot has no tile map;
/// the slot read alone keeps its own.
#[test]
fn a_sample_with_metals_footprint_is_answered_on_every_device() {
fn a_sample_with_metals_footprint_is_answered_where_the_device_has_no_residency() {
use crate::device::requirements::VkFeature;
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::facts::RuntimeFact;
@@ -2243,11 +2249,12 @@ fn a_sample_with_metals_footprint_is_answered_on_every_device() {
.enabled
.features
.contains(&VkFeature::ShaderResourceResidency);
for i in [0, 1] {
// Slot 1 is read alone, from its tile map on every device.
for (i, sampled) in [(0, true), (1, false)] {
let fact = RuntimeFact::SparseTexture {
slot: slot(Stage::Kernel, SlotClass::Texture, i),
sparse_arm: false,
tile_map: true,
sparse_arm: sampled && residency,
tile_map: !(sampled && residency),
};
assert!(
p.dependencies.iter().any(|d| d.fact == fact),
@@ -2255,9 +2262,14 @@ fn a_sample_with_metals_footprint_is_answered_on_every_device() {
);
}
let ops = opcodes(&p.stage.spirv);
assert!(!ops.contains(&SPARSE_SAMPLE_EXPLICIT_LOD), "{stem}");
assert!(!ops.contains(&SPARSE_GATHER), "{stem}");
assert!(!ops.contains(&SPARSE_FETCH), "{stem}");
assert_eq!(
ops.contains(&SPARSE_SAMPLE_EXPLICIT_LOD),
residency,
"{stem}"
);
assert_eq!(ops.contains(&SPARSE_GATHER), residency, "{stem}");
// The sampled slot's read through its sparse arm: one texel's residency, exact.
assert_eq!(ops.contains(&SPARSE_FETCH), residency, "{stem}");
assert_eq!(
p.stage
.precision_notes
@@ -2236,9 +2236,8 @@ fn a_heap_texture_samples_through_a_runtime_sampler() {
/// A cube's explicit gradients through a sampler loaded from an argument buffer: the sample takes
/// Metal's footprint as a slot's does (`PrecisionNote::CubeGradientFootprint`), the isotropic or
/// the anisotropic form by its table entry's word, through the set-1 sampler array of its own use.
/// Every committed profile's route is measured, so the class carries no cube-gradient bit and the
/// plan takes an anisotropic listed sampler for it (`engine_heap_binder`). On a driver that
/// the anisotropic form by its table entry's word, through the set-1 sampler array of its own use,
/// and the plan takes an anisotropic listed sampler for it (`engine_heap_binder`). On a driver that
/// hands a compute pipeline's cube gradients to Metal's `gradientcube` (`CubeGradientRoute::Metal`)
/// the kernel hands Metal's own, exactly, through any sampler: no note. Every profile with the
/// sampled heap compiles it and passes L3; it was `ArgumentBufferTextures NotImplemented` before.
@@ -2309,7 +2308,6 @@ declare { <4 x float>, i8 } @air.sample_texture_cube_grad.v4f32(ptr addrspace(1)
vec![HandleClass::Sampler {
compare: false,
integer: false,
cube_gradient: false,
}],
"{stem}"
);
@@ -4215,20 +4213,14 @@ fn argument_samplers_fixture() -> Option<Vec<u8>> {
}
}
/// The sampler uses `(compare, integer)` of the set-1 sampler arrays a module declares; none of
/// the fixture's entries samples a cube with explicit gradients.
/// The sampler uses `(compare, integer)` of the set-1 sampler arrays a module declares.
fn sampler_arrays(a: &FunctionArtifact) -> Vec<(bool, bool)> {
let mut out: Vec<(bool, bool)> = a
.interface
.descriptors
.iter()
.filter_map(|d| match d.slot.kind {
ResourceKind::Heap(HandleClass::Sampler {
compare,
integer,
cube_gradient,
}) => {
assert!(!cube_gradient, "a cube-gradient sampler array");
ResourceKind::Heap(HandleClass::Sampler { compare, integer }) => {
Some((compare, integer))
}
_ => None,
@@ -57,7 +57,7 @@ use crate::memory::handles::{
use crate::memory::leaf::k32;
use crate::memory::views;
use crate::metal::format::storage_image_choice;
use crate::metal::sampler::{OpaqueBlackBorder, SamplerUse, SamplerWord};
use crate::metal::sampler::SamplerWord;
use crate::metal::{
PixelFormat, RenderStages, SamplerAddressMode, SamplerBorderColor, SamplerMinMagFilter,
TextureType, TextureUsage,
@@ -1282,7 +1282,6 @@ fn a_runtime_heap_sampler_is_written_with_the_bound_sampler() {
slot: s0,
compare: false,
integer: false,
cube_gradient: false,
opaque_black: crate::metal::sampler::OpaqueBlackBorder::Stated,
}]
);
@@ -1953,12 +1952,7 @@ fn sampler_layout(p: &ComputePipeline) -> (Vec<SamplerArray>, (u32, u32)) {
.bindings
.iter()
.filter_map(|b| match b.source {
BindingSource::Heap(HandleClass::Sampler {
compare,
integer,
cube_gradient,
}) => {
assert!(!cube_gradient, "the fixture samples no cube with gradients");
BindingSource::Heap(HandleClass::Sampler { compare, integer }) => {
assert_eq!(b.ty, vk::DescriptorType::SAMPLER);
assert_eq!(b.flags, super::engine_handles::heap_flags(&p.requirements));
Some((b.binding, (compare, integer)))
@@ -2069,7 +2063,6 @@ fn argument_samplers_fill_their_arrays_and_tables() {
index: e as u32 - 1,
compare: false,
integer: false,
cube_gradient: false,
}
);
}
@@ -2134,7 +2127,6 @@ fn argument_samplers_fill_their_arrays_and_tables() {
index: 0,
compare: use_.0,
integer: use_.1,
cube_gradient: false,
},
"{entry}"
);
@@ -2181,14 +2173,10 @@ declare { <4 x float>, i8 } @air.sample_texture_cube_grad.v4f32(ptr addrspace(1)
/// A cube's explicit gradients through an argument buffer's sampler take their footprint by the
/// sampler's table entry word, so the plan takes every listed sampler for that use, an anisotropic
/// one included: its array has no cube-gradient bit, and an isotropic sampler plans with the
/// array's `ArgumentSampler` writes, as an anisotropic one does. On a driver whose cube-gradient
/// route is not measured (`moltenvk-m3` without its measured route) the kernel keeps the isotropic
/// form, its array carries the bit, and the plan takes an anisotropic listed sampler there too,
/// made isotropic for that use (where the refusal was): the array's writes carry the bit, and
/// `sampler_desc` makes the `VkSampler` of a write with it isotropic. It takes the same sampler for
/// a use without cube gradients (`argument_sampler_sample`). Run on every committed profile that
/// compiles the use, and the unmeasured description.
/// one included: an isotropic sampler plans with the array's `ArgumentSampler` writes, as an
/// anisotropic one does. A driver whose cube-gradient route is not measured (`moltenvk-m3` without
/// its measured route) takes Vulkan's rule, the device's reading, alike. Run on every committed
/// profile that compiles the use, and the unmeasured description.
#[test]
fn a_cube_gradient_use_takes_an_anisotropic_argument_sampler_by_its_word() {
let Some(bc) = assemble("argument_sampler_cube_grad", CUBE_GRADIENT) else {
@@ -2218,7 +2206,7 @@ fn a_cube_gradient_use_takes_an_anisotropic_argument_sampler_by_its_word() {
)
.expect("device");
devices.push(("unmeasured".to_string(), unmeasured));
let (mut taken_on, mut isotropic_on) = (0, 0);
let (mut taken_on, mut unmeasured_on) = (0, 0);
for (stem, dev) in devices {
let lib = Library::from_air(&bc).expect("library");
let f = lib.function("argument_sampler_cube_grad").expect("entry");
@@ -2230,9 +2218,10 @@ fn a_cube_gradient_use_takes_an_anisotropic_argument_sampler_by_its_word() {
);
continue;
};
let isotropic = dev.profile().fields().cube_gradients.compute
== crate::device::profile::CubeGradientRoute::Unmeasured;
assert_eq!(isotropic, stem == "unmeasured", "{stem}");
let route = dev.profile().fields().cube_gradients.compute;
if stem == "unmeasured" {
assert_eq!(route, crate::device::profile::CubeGradientRoute::Vulkan);
}
let arrays: Vec<(u32, HandleClass)> = pipe.layout.sets[1]
.bindings
.iter()
@@ -2244,7 +2233,6 @@ fn a_cube_gradient_use_takes_an_anisotropic_argument_sampler_by_its_word() {
let cube_class = HandleClass::Sampler {
compare: false,
integer: false,
cube_gradient: isotropic,
};
assert_eq!(arrays.len(), 1, "{stem}");
assert_eq!(arrays[0].1, cube_class, "{stem}");
@@ -2270,78 +2258,26 @@ fn a_cube_gradient_use_takes_an_anisotropic_argument_sampler_by_its_word() {
d.max_anisotropy = 4;
d
};
let plan = pipe
.plan(&dev, &cube_state(vec![argument_sampler(linear, C)]).shape())
.unwrap_or_else(|e| panic!("{stem}: an isotropic sampler plans: {e}"));
let writes = sampler_writes(&plan, arrays[0].0);
assert_eq!(
writes[1],
WriteSource::ArgumentSampler {
index: 0,
compare: false,
integer: false,
cube_gradient: isotropic,
},
"{stem}"
);
let planned = pipe.plan(
&dev,
&cube_state(vec![argument_sampler(anisotropic, C)]).shape(),
);
if !isotropic {
let plan = planned.unwrap_or_else(|e| panic!("{stem}: by its word: {e}"));
let write = WriteSource::ArgumentSampler {
index: 0,
compare: false,
integer: false,
};
for (what, desc) in [("isotropic", linear), ("anisotropic", anisotropic)] {
let plan = pipe
.plan(&dev, &cube_state(vec![argument_sampler(desc, C)]).shape())
.unwrap_or_else(|e| panic!("{stem}: an {what} sampler plans: {e}"));
assert_eq!(
sampler_writes(&plan, arrays[0].0)[1],
WriteSource::ArgumentSampler {
index: 0,
compare: false,
integer: false,
cube_gradient: false,
},
"{stem}"
write,
"{stem} {what}"
);
taken_on += 1;
continue;
}
let plan = planned
.unwrap_or_else(|e| panic!("{stem}: an anisotropic sampler, made isotropic: {e}"));
let write = sampler_writes(&plan, arrays[0].0)[1].clone();
assert_eq!(
write,
WriteSource::ArgumentSampler {
index: 0,
compare: false,
integer: false,
cube_gradient: true,
},
"{stem}"
);
// The binder's `VkSampler` of that write (the runtime's and the executor's) is isotropic;
// the same sampler for a use without the bit keeps its anisotropy.
let made = |cube_gradient| {
let use_ = SamplerUse::new(false, false).with_cube_gradient(cube_gradient);
crate::bind::sampler_desc(&dev, &anisotropic, use_, OpaqueBlackBorder::Stated, None)
.unwrap_or_else(|e| panic!("{stem}: {e}"))
.max_anisotropy
};
assert_eq!(made(true), None, "{stem}");
assert!(made(false).is_some(), "{stem}");
isotropic_on += 1;
let Some(plain) = argument_sampler_pipeline(&dev, "argument_sampler_sample") else {
return;
};
plain
.plan(
&dev,
&sampler_state(vec![argument_sampler(anisotropic, C)]).shape(),
)
.unwrap_or_else(|e| panic!("{stem}: the same sampler without cube gradients: {e}"));
taken_on += 1;
unmeasured_on += usize::from(stem == "unmeasured");
}
assert!(taken_on > 0, "no profile took the anisotropic sampler");
assert_eq!(
isotropic_on, 1,
"the unmeasured description takes it isotropic"
);
assert_eq!(unmeasured_on, 1, "the unmeasured description takes it");
}
/// A plan depends on the argument samplers only through their shape (`ArgumentSamplersShape`: the
@@ -412,15 +412,13 @@ fn an_anisotropic_constexpr_sampler_takes_metals_cube_gradient_footprint() {
}
/// An unmeasured route: `moltenvk-m3` without its measured compute cube-gradient route (as a
/// MoltenVK release no measurement covers) takes Metal's footprint in the shader, where the
/// refusal was: `unk_cube_grad_lod`'s isotropic sampler Metal's level and one tap (each texture's
/// routine queries the level count; no loop, no note), the same kernel through an anisotropic
/// constexpr sampler Metal's level and taps (a loop of taps per routine, `AnisotropicFilter`),
/// neither with
/// `CubeGradientFootprint`. The measured description hands Metal's own gradients: no level query,
/// MoltenVK release no measurement covers) takes Vulkan's rule, the device's own reading of the
/// form handed to it: `unk_cube_grad_lod` through its isotropic sampler and through an anisotropic
/// constexpr one queries no level count, loops over no taps and records `CubeGradientFootprint`,
/// not `AnisotropicFilter`. The measured description hands Metal's own gradients: no level query,
/// no note.
#[test]
fn an_unmeasured_cube_gradient_route_takes_metals_footprint_in_the_shader() {
fn an_unmeasured_cube_gradient_route_takes_the_devices_reading() {
use crate::device::profile::CubeGradients;
use crate::error::DriverDeviation;
let path = engine_dir().join("unk_cube_grad_lod.ll");
@@ -457,7 +455,7 @@ fn an_unmeasured_cube_gradient_route_takes_metals_footprint_in_the_shader() {
unmeasured.fields().cube_gradients,
CubeGradients {
graphics: CubeGradientRoute::AppleProjected,
compute: CubeGradientRoute::Unmeasured,
compute: CubeGradientRoute::Vulkan,
}
);
for (bc, taps) in [(&iso, false), (&aniso, true)] {
@@ -465,24 +463,15 @@ fn an_unmeasured_cube_gradient_route_takes_metals_footprint_in_the_shader() {
let u = artifact(bc, "unk_cube_grad_lod", "unmeasured", &unmeasured).expect(what);
let samples = uses(&u, "sampler.sample_cube_grad") as usize;
assert!(samples > 0, "{what}");
assert_eq!(
count(&u, OP_IMAGE_QUERY_LEVELS),
CUBE_GRAD_TEXTURES,
"{what}"
);
assert_eq!(
count(&u, OP_LOOP_MERGE),
if taps { CUBE_GRAD_TEXTURES } else { 0 },
"{what}"
);
assert_eq!(
u.precision.contains(&PrecisionNote::AnisotropicFilter),
taps,
assert_eq!(count(&u, OP_IMAGE_QUERY_LEVELS), 0, "{what}");
assert_eq!(count(&u, OP_LOOP_MERGE), 0, "{what}");
assert!(
!u.precision.contains(&PrecisionNote::AnisotropicFilter),
"{what}: {:?}",
u.precision
);
assert!(
!u.precision.contains(&PrecisionNote::CubeGradientFootprint),
u.precision.contains(&PrecisionNote::CubeGradientFootprint),
"{what}: {:?}",
u.precision
);
@@ -502,8 +491,8 @@ fn an_unmeasured_cube_gradient_route_takes_metals_footprint_in_the_shader() {
/// On the Apple M3 Max's identity (`moltenvk-m3`'s capture) a fragment function's explicit cube
/// gradients through an anisotropic constexpr sampler take SPIRV-Cross's fixup in its projected
/// form (`AppleProjected`), exact on an `x` or `z` face and a near-equivalent on a `y` face, with
/// `CubeGradientFootprint`. Without the route's measurement the same fragment takes Metal's level
/// and taps in the shader, with `AnisotropicFilter` and without `CubeGradientFootprint`, while the
/// `CubeGradientFootprint`. Without the route's measurement the same fragment takes Vulkan's rule,
/// the device's reading, with `CubeGradientFootprint` and without `AnisotropicFilter`, while the
/// kernel route stays Metal's and the kernel of the same samples compiles. The cover vertex
/// function compiles on each.
#[test]
@@ -542,7 +531,7 @@ fn the_graphics_cube_route_is_the_measured_projected_form() {
.clone();
assert_eq!(
unmeasured.fields().cube_gradients.graphics,
CubeGradientRoute::Unmeasured
CubeGradientRoute::Vulkan
);
let a = artifact(&fragment, "rtl_cube_grad_fragment", "moltenvk-m3", &m3_27).expect("m3");
assert!(
@@ -558,12 +547,12 @@ fn the_graphics_cube_route_is_the_measured_projected_form() {
)
.expect("an unmeasured graphics route");
assert!(
a.precision.contains(&PrecisionNote::AnisotropicFilter),
!a.precision.contains(&PrecisionNote::AnisotropicFilter),
"{:?}",
a.precision
);
assert!(
!a.precision.contains(&PrecisionNote::CubeGradientFootprint),
a.precision.contains(&PrecisionNote::CubeGradientFootprint),
"{:?}",
a.precision
);
@@ -605,17 +594,14 @@ declare { <4 x float>, i8 } @air.sample_texture_cube_grad.v4f32(ptr addrspace(1)
/// word on every profile whose route is measured and not Metal's: the slot's `SamplerState`
/// specialization reads `SamplerWord::ANISOTROPIC`, the module computes the isotropic form
/// (Metal's length per gradient, two `FMax` each; macOS 26.7's fixup a `Length` instead) beside
/// the anisotropic one, records `CubeGradientFootprint`, and its combined binding carries no
/// cube-gradient bit, so the plan takes an anisotropic sampler there. On a driver that hands a
/// compute pipeline's cube gradients to Metal's `gradientcube`, the kernel hands Metal's own: no
/// word read, no note. On `moltenvk-m3` without its measured route (unmeasured) the kernel keeps
/// the isotropic form without reading the word (a variant naming the slot takes Metal's taps),
/// and its binding carries the bit, which makes an anisotropic sampler isotropic where it is
/// bound.
/// the anisotropic one and records `CubeGradientFootprint`, so the plan takes an anisotropic
/// sampler there. On a driver that hands a compute pipeline's cube gradients to Metal's
/// `gradientcube`, the kernel hands Metal's own: no word read, no note. `moltenvk-m3` without its
/// measured route (unmeasured) takes Vulkan's rule, by the word too.
#[test]
fn a_runtime_samplers_cube_gradients_take_their_footprint_by_its_word() {
use crate::metal::sampler::SamplerWord;
use crate::pipeline::sym::{ResourceKind, SpecKey};
use crate::pipeline::sym::SpecKey;
let Some(bc) = assemble_text("runtime_cube_grad", RUNTIME_CUBE_GRAD) else {
return;
};
@@ -644,41 +630,24 @@ fn a_runtime_samplers_cube_gradients_take_their_footprint_by_its_word() {
_ => None,
});
let reads = fields.is_some_and(|f| f & SamplerWord::ANISOTROPIC != 0);
let bits: Vec<bool> = a
.interface
.descriptors
.iter()
.filter_map(|d| match d.slot.kind {
ResourceKind::CombinedTextureSampler(c) => Some(c.cube_gradient),
_ => None,
})
.collect();
let noted = a.precision.contains(&PrecisionNote::CubeGradientFootprint);
let lengths = glsl(&a, GLSL_FMAX) >= 4 || glsl(&a, GLSL_LENGTH) >= 2;
match route {
CubeGradientRoute::Metal => {
assert!(!reads, "{stem}: {fields:?}");
assert!(!noted, "{stem}");
assert_eq!(bits, vec![false], "{stem}");
handed += 1;
}
CubeGradientRoute::Unmeasured => {
assert!(!reads, "{stem}: {fields:?}");
assert!(glsl(&a, GLSL_FMAX) >= 4, "{stem}");
assert!(noted, "{stem}");
assert_eq!(bits, vec![true], "{stem}");
}
CubeGradientRoute::Vulkan => {
assert!(reads, "{stem}: {fields:?}");
assert!(lengths, "{stem}");
assert!(noted, "{stem}");
assert_eq!(bits, vec![false], "{stem}");
by_word += 1;
}
CubeGradientRoute::AppleProjected => panic!("{stem}: a kernel's route {route:?}"),
}
}
assert!(by_word >= 4, "{by_word}");
assert!(by_word >= 5, "{by_word}");
assert!(handed > 0, "no profile hands Metal's gradients");
}
@@ -289,7 +289,6 @@ fn the_binder_writes_a_runtime_separate_sampler_and_its_textures() {
slot: s0,
compare: false,
integer: false,
cube_gradient: false,
opaque_black: crate::metal::sampler::OpaqueBlackBorder::Stated,
},
),
@@ -6,9 +6,9 @@
//! `residencyNonResidentStrict` reads any value. A sampler's access whose residency the function
//! reads there, and every read or access through a sampler whose residency it does not read, sets
//! the lanes Metal reads as constants (a channel the format lacks, through the texture's swizzle)
//! from the slot's `SpecKey::ConstantLanes`, and a pixel fetch, a nearest sample, or a gather of
//! Metal's footprint whose residency the function reads, naming its texels, reads zero for each
//! of them the tile map says is unmapped. The CPU interpreter fetches but does not sample, so a
//! from the slot's `SpecKey::ConstantLanes`, and a pixel fetch whose residency the function reads,
//! naming its texel, reads zero where its residency says it is unmapped; a sample's and a gather's
//! are the device's own sparse access. The CPU interpreter fetches but does not sample, so a
//! read and a pixel sampler's fetch run here and the sample and gather are checked by their facts,
//! notes and specializations.
@@ -382,7 +382,6 @@ fn a_pixel_fetch_reads_metals_value_of_an_unmapped_texel() {
sampler: SamplerRef::Constexpr([PIXEL_NEAREST, 0]),
compare: false,
integer: false,
cube_gradient: false,
}),
index: 0,
};
@@ -440,37 +439,22 @@ fn a_pixel_fetch_reads_metals_value_of_an_unmapped_texel() {
assert!(legs.iter().all(|n| *n > 0), "legs {legs:?}");
}
/// A nearest sample and a gather of Metal's footprint, and a linear sample, through clamp-to-zero
/// constexpr samplers whose residency the function reads, each answered from the slot's tile map on
/// every profile. Where the profile's sparse textures are sparse images the stage states
/// `ConstantLanes` and specializes on it, and only the linear sample, whose lanes that are no
/// constants the device filters, notes `SparseResidency`; elsewhere neither.
/// A nearest sample, a gather and a linear sample through clamp-to-zero constexpr samplers whose
/// residency the function reads. Where the profile's sparse textures are sparse images
/// (`shaderResourceResidency`), each is the device's own sparse access, its word the device's
/// residency code: the slot takes the sparse arm and no tile map, the stage states
/// `ConstantLanes` and specializes on it, and notes `SparseResidency`. Elsewhere the slot's tile
/// map answers each by Metal's footprint, noting nothing.
#[test]
fn a_nearest_sample_and_a_gather_note_nothing_a_filtered_sample_notes_its_lanes() {
fn a_sparse_device_answers_a_samples_residency_itself() {
let cases = [
(
"nearest",
kernel(NEAREST_ZERO, &sample("%uv"), SAMPLE_DECL),
false,
),
(
"gather_x",
kernel(NEAREST_ZERO, &gather(0), GATHER_DECL),
false,
),
(
"gather_w",
kernel(NEAREST_ZERO, &gather(3), GATHER_DECL),
false,
),
(
"linear",
kernel(LINEAR_ZERO, &sample("%uv"), SAMPLE_DECL),
true,
),
("nearest", kernel(NEAREST_ZERO, &sample("%uv"), SAMPLE_DECL)),
("gather_x", kernel(NEAREST_ZERO, &gather(0), GATHER_DECL)),
("gather_w", kernel(NEAREST_ZERO, &gather(3), GATHER_DECL)),
("linear", kernel(LINEAR_ZERO, &sample("%uv"), SAMPLE_DECL)),
];
let mut legs = [0; 2];
for (name, text, filtered) in cases {
for (name, text) in cases {
let Some(bc) = assemble(name, &text) else {
return;
};
@@ -484,7 +468,7 @@ fn a_nearest_sample_and_a_gather_note_nothing_a_filtered_sample_notes_its_lanes(
assert_eq!(a.facts.contains(&fact), images, "{what}");
assert_eq!(
a.precision.contains(&PrecisionNote::SparseResidency),
images && filtered,
images,
"{what}"
);
let keys = a.interface.read_keys();
@@ -496,10 +480,11 @@ fn a_nearest_sample_and_a_gather_note_nothing_a_filtered_sample_notes_its_lanes(
assert!(
a.facts.contains(&RuntimeFact::SparseTexture {
slot: texture_slot(0),
sparse_arm: false,
tile_map: true,
sparse_arm: images,
tile_map: !images,
}),
"{what}"
"{what}: {:?}",
a.facts
);
legs[usize::from(images)] += 1;
}
@@ -614,7 +599,6 @@ fn an_access_that_does_not_read_its_residency_reads_metals_constant_lanes() {
sampler: SamplerRef::Constexpr([PIXEL_NEAREST, 0]),
compare: false,
integer: false,
cube_gradient: false,
}),
index: 0,
}
@@ -1151,13 +1151,12 @@ fn an_astc_srgb_slot_samples_the_devices_decode() {
}
/// A `half` sample the device decodes and filters (a linear one with a linear mip filter)
/// 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 decode and filter are Metal's own texture unit's,
/// that `f32` is Metal's `float` value, whose rounding to `half` is Metal's
/// (`metals_srgb_float_steps_round_to_their_half_steps`): the pipeline takes no
/// `PrecisionNote::HalfTexelConversion` under the format and requires `VkProperty::MetalSampler`,
/// and the note holds under a format of no measured family. On lavapipe, whose decode and
/// conversion are the device's, the note holds under every format.
/// rounds the device's `f32` texel to nearest even. On MoltenVK, whose decode and filter are
/// Metal's own texture unit's, that `f32` is Metal's `float` value, whose rounding to `half` is
/// Metal's (`metals_srgb_float_steps_round_to_their_half_steps`): the pipeline requires
/// `VkProperty::MetalSampler`, no clause of `PrecisionNote::HalfTexelConversion` holds of an 8-bit
/// sRGB format bound there, and the note holds under a format of no measured family. On
/// lavapipe, whose decode and conversion are the device's, the note holds under every format.
#[test]
fn metals_own_srgb_decode_converts_to_half_as_metal_does() {
use crate::device::requirements::VkProperty;
@@ -1186,12 +1185,21 @@ fn metals_own_srgb_decode_converts_to_half_as_metal_does() {
for pf in [PixelFormat::RGBA8UnormSRGB, PixelFormat::BGRA8UnormSRGB] {
let plan = p.plan(&dev, &state(Some(pf)).shape()).expect("plan");
assert!(plan.variant.srgb_textures.is_empty(), "{stem} {pf:?}");
// On MoltenVK the note's clauses test the bound format, which the runtime reads at
// the dispatch: none holds of an 8-bit sRGB format.
let notes = p.stage.precision_notes_under(&plan.specialization);
assert_eq!(
notes.contains(&PrecisionNote::HalfTexelConversion),
!metal,
"{stem} {pf:?}: {notes:?}"
);
let bound = p
.stage
.bound_format_clauses(PrecisionNote::HalfTexelConversion, &|_| {
Some(bound_texel_format(pf))
});
match metal {
true => assert!(bound.is_empty(), "{stem} {pf:?}: {bound:?}"),
false => assert!(
notes.contains(&PrecisionNote::HalfTexelConversion),
"{stem} {pf:?}: {notes:?}"
),
}
}
if !metal {
assert!(
@@ -545,14 +545,12 @@ fn short_texels_sign_extend_and_half_reads_round() {
assert!(ran > 0);
}
/// A `half` read on a profile with Metal's own sampler (`VkProperty::MetalSampler`) converts its
/// texel by the bound format's class, the slot's `TexelFormat` specialization: a 32-bit float
/// texel to nearest even, half denormals kept; a 16-bit normalized texel's code value `c / 65535`
/// correctly rounded, where rounding the `f32` value would round twice (`65455` and `65519`); a
/// format whose conversion is not measured (the default) takes every other `half` texel's exact
/// rounding, which keeps a half denormal. On any other profile the read is the device's conversion
/// of its `f32` texel, to nearest even here, with no class. Both record
/// `PrecisionNote::HalfTexelConversion`. On a profile without `shaderFloat16` the rounding is the
/// A `half` read rounds its `f32` texel to nearest even, half denormals kept, on every profile: on
/// one with Metal's own sampler (`VkProperty::MetalSampler`) whatever the bound format's class,
/// the slot's `TexelFormat` specialization, a 16-bit normalized texel's `f32` value of `65455 /
/// 65535` and `65519 / 65535` too, which rounds twice there (one `half` unit in the last place
/// above Metal's correctly rounded `c / 65535`, noted under the bound format); on any other
/// profile with no class. Both record `PrecisionNote::HalfTexelConversion`. On a profile without `shaderFloat16` the rounding is the
/// device's quantize alone (`PrecisionNote::NativeHalfQuantize`), whose result below the smallest
/// normal half the interpreter gives as the zero of its sign.
#[test]
@@ -583,7 +581,7 @@ fn half_reads_convert_by_the_bound_format() {
(
Some(texel_format(PixelFormat::RGBA16Unorm).0),
[unorm16(65455), unorm16(65519), unorm16(1), unorm16(65535)],
[0x3BFD, 0x3BFF, 0x0100, 0x3C00],
[0x3BFE, 0x3C00, 0x0100, 0x3C00],
),
];
let mut ran = 0;
+4 -8
View File
@@ -3956,7 +3956,6 @@ field metal2vulkan::metal::format::YCbCrFormat.packed pub packed: bool
field metal2vulkan::metal::format::YCbCrFormat.reads pub reads: YCbCrReads
field metal2vulkan::metal::format::YCbCrFormat.subsampling pub subsampling: ChromaSubsampling
field metal2vulkan::metal::sampler::SamplerUse.compare pub compare: bool
field metal2vulkan::metal::sampler::SamplerUse.cube_gradient pub cube_gradient: bool
field metal2vulkan::metal::sampler::SamplerUse.integer_texture pub integer_texture: bool
field metal2vulkan::metal::state::DepthBias.clamp pub clamp: f32
field metal2vulkan::metal::state::DepthBias.constant_factor pub constant_factor: f32
@@ -4022,7 +4021,6 @@ field metal2vulkan::pipeline::ColorGroup.group pub group: u32
field metal2vulkan::pipeline::ColorGroup.present pub present: Vec<u32>
field metal2vulkan::pipeline::ColorGroup.width pub width: u32
field metal2vulkan::pipeline::CombinedSampler.compare pub compare: bool
field metal2vulkan::pipeline::CombinedSampler.cube_gradient pub cube_gradient: bool
field metal2vulkan::pipeline::CombinedSampler.integer pub integer: bool
field metal2vulkan::pipeline::CombinedSampler.sampler pub sampler: SamplerRef
field metal2vulkan::pipeline::CommandWrites.operations pub operations: u32
@@ -8878,7 +8876,6 @@ method metal2vulkan::metal::sampler::AddressModeMap::mode pub fn mode(&self, fro
method metal2vulkan::metal::sampler::AddressModeMap::sampler pub fn sampler(&self, mut desc: SamplerDescriptor) -> SamplerDescriptor
method metal2vulkan::metal::sampler::AddressModeMap::with pub fn with(mut self, from: SamplerAddressMode, to: SamplerAddressMode) -> AddressModeMap
method metal2vulkan::metal::sampler::SamplerUse::new pub fn new(compare: bool, integer_texture: bool) -> SamplerUse
method metal2vulkan::metal::sampler::SamplerUse::with_cube_gradient pub fn with_cube_gradient(self, cube_gradient: bool) -> SamplerUse
method metal2vulkan::metal::sampler::SamplerWord::exact_fetch pub fn exact_fetch(plane: u8, integer: bool) -> u32
method metal2vulkan::metal::sampler::SamplerWord::of pub fn of(desc: &SamplerDescriptor) -> SamplerWord
method metal2vulkan::pipeline::AliasView::new pub fn new(image_format: vk::Format) -> AliasView
@@ -8899,7 +8896,6 @@ method metal2vulkan::pipeline::CombinedSampler::from_heap_index pub fn from_heap
method metal2vulkan::pipeline::CombinedSampler::heap_index pub fn heap_index(&self) -> u32
method metal2vulkan::pipeline::CombinedSampler::new pub fn new(sampler: SamplerRef, compare: bool, integer: bool) -> CombinedSampler
method metal2vulkan::pipeline::CombinedSampler::sampler_use pub fn sampler_use(&self) -> crate::metal::sampler::SamplerUse
method metal2vulkan::pipeline::CombinedSampler::with_cube_gradient pub fn with_cube_gradient(self, cube_gradient: bool) -> CombinedSampler
method metal2vulkan::pipeline::CommandWrites::is_empty pub const fn is_empty(self) -> bool
method metal2vulkan::pipeline::CommandWrites::may pub const fn may(self, bits: u32) -> bool
method metal2vulkan::pipeline::CommandWrites::may_draw_primitive_type pub const fn may_draw_primitive_type(self, raw: u32) -> bool
@@ -12154,7 +12150,7 @@ variant metal2vulkan::bind::RewriteSource::Indirect Indirect { arguments: Indire
variant metal2vulkan::bind::RewriteSource::IndirectVertices IndirectVertices { arguments: IndirectRef }
variant metal2vulkan::bind::SamplerSource::Immutable Immutable
variant metal2vulkan::bind::SamplerSource::Neutral Neutral(NeutralResource)
variant metal2vulkan::bind::SamplerSource::Slot Slot { slot: SlotRef, compare: bool, integer: bool, cube_gradient: bool, opaque_black: OpaqueBlackBorder }
variant metal2vulkan::bind::SamplerSource::Slot Slot { slot: SlotRef, compare: bool, integer: bool, opaque_black: OpaqueBlackBorder }
variant metal2vulkan::bind::ShadowMergeRead::B8G8R8A8Unorm B8G8R8A8Unorm
variant metal2vulkan::bind::ShadowMergeRead::R8G8B8A8Unorm R8G8B8A8Unorm
variant metal2vulkan::bind::ShadowMergeRead::Words Words(ShadowTexelView)
@@ -12199,7 +12195,7 @@ variant metal2vulkan::bind::UsedClass::Buffer Buffer
variant metal2vulkan::bind::UsedClass::Heap Heap
variant metal2vulkan::bind::UsedClass::Texture Texture(TextureShape)
variant metal2vulkan::bind::WriteSource::AccelerationStructure AccelerationStructure { slot: SlotRef, level: AccelerationStructureLevel }
variant metal2vulkan::bind::WriteSource::ArgumentSampler ArgumentSampler { index: u32, compare: bool, integer: bool, cube_gradient: bool }
variant metal2vulkan::bind::WriteSource::ArgumentSampler ArgumentSampler { index: u32, compare: bool, integer: bool }
variant metal2vulkan::bind::WriteSource::ArgumentTable ArgumentTable { stage: Stage, bytes_len: u32 }
variant metal2vulkan::bind::WriteSource::Attachment Attachment { color_index: u32 }
variant metal2vulkan::bind::WriteSource::Buffer Buffer { slot: SlotRef }
@@ -12219,7 +12215,7 @@ variant metal2vulkan::bind::WriteSource::MeshRecords MeshRecords
variant metal2vulkan::bind::WriteSource::MeshWork MeshWork
variant metal2vulkan::bind::WriteSource::Neutral Neutral(NeutralResource)
variant metal2vulkan::bind::WriteSource::PatchIndices PatchIndices { min_bytes: u32 }
variant metal2vulkan::bind::WriteSource::Sampler Sampler { slot: SlotRef, compare: bool, integer: bool, cube_gradient: bool, opaque_black: OpaqueBlackBorder }
variant metal2vulkan::bind::WriteSource::Sampler Sampler { slot: SlotRef, compare: bool, integer: bool, opaque_black: OpaqueBlackBorder }
variant metal2vulkan::bind::WriteSource::ShadowStencil ShadowStencil
variant metal2vulkan::bind::WriteSource::SnapshotTexels SnapshotTexels { slot: u32 }
variant metal2vulkan::bind::WriteSource::StencilStandIn StencilStandIn
@@ -13389,7 +13385,7 @@ variant metal2vulkan::pipeline::FactorLane::Output Output(u8)
variant metal2vulkan::pipeline::FactorLane::Zero Zero
variant metal2vulkan::pipeline::HandleClass::FunctionTable FunctionTable
variant metal2vulkan::pipeline::HandleClass::Image Image(ImageHandleClass)
variant metal2vulkan::pipeline::HandleClass::Sampler Sampler { compare: bool, integer: bool, cube_gradient: bool }
variant metal2vulkan::pipeline::HandleClass::Sampler Sampler { compare: bool, integer: bool }
variant metal2vulkan::pipeline::ImageAccess::Sampled Sampled
variant metal2vulkan::pipeline::ImageAccess::Storage Storage
variant metal2vulkan::pipeline::ImageDim::Buffer Buffer
Can't render this file because it is too large.
+29 -13
View File
@@ -2738,7 +2738,11 @@ bound.
color lane, `1/4080` alpha).
- `metal2vulkan-degrade-sparse-residency` (precision). `PrecisionNote::SparseResidency`: A stage
samples or gathers a texture whose residency it observes (`sparse_color::resident()`) through the
slot's sparse form, which the module has where the profile enables `shaderResourceResidency`.
slot's sparse form, which the module has where the profile enables `shaderResourceResidency`:
the word is the device's `OpImageSparse*` residency, whose footprint may count a texel of zero
weight Metal does not, and an unmapped texel's lanes the device's non-resident value. Where the
device has no residency of its own, the slot's tile map answers Metal's footprint rule exactly,
unrecorded.
- `metal2vulkan-degrade-device-nan-encoding` (precision). `PrecisionNote::DeviceNanEncoding`: A
`float` NaN result's bit pattern follows the device: Metal answers the canonical `0x7fc00000` for
the NaN results of its float arithmetic and functions, and Vulkan states no encoding, so a device
@@ -2752,18 +2756,21 @@ bound.
off MoltenVK the sample takes the device's logarithm of Metal's footprint and, if anisotropic,
the device's taps, so a level or blend near a boundary can differ from Metal's. Where the shader
takes Metal's level and taps itself (`PrecisionNote::AnisotropicFilter`) this note is not
recorded. On a MoltenVK release or
GPU whose cube-gradient route is not measured, such an out-of-reach anisotropic sample is
filtered isotropically, at Metal's major axis. Through MoltenVK's vertex and fragment stages
recorded. On a MoltenVK release or GPU whose cube-gradient route is not measured the sample
takes Vulkan's rule's form, the device's reading of it. Through MoltenVK's vertex and fragment stages
under macOS 27, an isotropic sample is Metal's, but an anisotropic sample on a cube's `+Y` or
`-Y` face loses the gradients' `z` component to SPIRV-Cross's `spvGradientCube`, so its ellipse
lies on the face's diagonal (docs/FAST-PATHS.md's known gaps). A kernel's samples through
MoltenVK are Metal's own, with no note.
- `metal2vulkan-degrade-half-texel-conversion` (precision). `PrecisionNote::HalfTexelConversion`:
The module reads, gathers, or samples a texture with a `half` result. On MoltenVK, also
announced at a draw that binds a two-plane YCbCr texture on
the grid `8192` at a slot sampled through a runtime sampler: a sample of one texel rounds to
nearest even, one `half` ulp from Metal's ties-away rounding at a tie.
The module reads, gathers, or samples a texture with a `half` result, the device's `float` texel
rounded to nearest even on every device: within one `half` ulp of Metal's, but a 32-bit float
texel's sample past `±65504`, the infinity where Metal saturates. On MoltenVK, whose `float`
texel is Metal's, announced at a draw or dispatch that binds a texture of a class whose Metal
`half` differs from it (a 32-bit float texel's sample, a 16-bit normalized texel, a format not
measured) and a two-plane YCbCr texture on the grid `8192` at a slot sampled through a runtime
sampler (a sample of one texel rounds to nearest even, one `half` ulp from Metal's ties-away
rounding at a tie); a heap element or a depth texture wherever it is accessed.
- `metal2vulkan-degrade-half-sample-filter` (precision). `PrecisionNote::HalfSampleFilter`: The
module samples a texture with a `half` result through a filter (linear minification or
magnification, or a runtime sampler) that Metal's own sampler (MoltenVK) answers otherwise than
@@ -2805,7 +2812,13 @@ bound.
floats). Near a tie between two codes the device may store the other one. Also a `float` texel a
function writes to a storage texture that may hold a normalized or half-float format, or
`ARGB8Unorm`, on a device not measured to store Metal's codes (or a 1-bit alpha, on one measured
to store every other normalized channel's). Also a render pass's clear of a normalized, sRGB,
to store every other normalized channel's); an integer texel written into a storage texture of
the float class that may hold a half-float or small-float format, which Metal rounds to nearest
even and the device's store as it rounds a `float` (toward zero on every measured driver, one
unit in the last place, a finite value past 65504 stored as 65504); and a fragment function's
`float` blend into a 16-bit float attachment through the pixel interlock on a device not
measured to round a `half` store as Metal does.
Also a render pass's clear of a normalized, sRGB,
packed 16-bit, half or small-float color attachment to a color whose conversion is in question
(a normalized channel within 1/1024 of a midpoint between two codes, an sRGB channel inside its
range, a value the format does not hold exactly): the device converts the clear color, where
@@ -2919,8 +2932,7 @@ bound.
module samples a texture through an anisotropic sampler with Metal's anisotropic filter emulated
by the device's samples at explicit levels (`lower::sampler::anisotropic`), on a device without
`samplerAnisotropy`, every Vulkan sampler being isotropic there, each tap the device's isotropic
filter, and for a cube's explicit gradients through MoltenVK where its cube-gradient route is not
measured: a sample without comparison of a 2D texture or 2D array at the fragment's implicit
filter: a sample without comparison of a 2D texture or 2D array at the fragment's implicit
level or with explicit gradients, or of a cube or cube array with explicit gradients, through a
constexpr sampler of `maxAnisotropy` above 1, or through a runtime sampler slot whose word states
anisotropy (under that word alone). A device with the feature samples with its own anisotropic
@@ -2969,8 +2981,12 @@ bound.
(every factor, operation, write mask and blend color it builds), which Metal reads the output
into clamped, folding none of it.
- `metal2vulkan-degrade-device-sampling` (precision). `PrecisionNote::DeviceSampling`: Native device
sampling: the module hands a sample, gather or comparison to the device's own sampler on a device
whose sampler is not Metal's (the module requires `VkProperty::DeviceSampling`). That includes a
sampling: the module hands a sample, gather, comparison or level query to the device's own
sampler on a device whose sampler is not Metal's (the module requires
`VkProperty::DeviceSampling`), its level clamp the descriptor's as given (Metal holds it on a
`1/64` grid, and its nearest mip filter reads the lower level at a clamp halfway between two,
where the device may read the upper) and a subnormal coordinate the device's to read (Metal reads it as a zero before
addressing). That includes a
linear sample of a two-plane YCbCr texture, whose texels hold Metal's reads exactly: the device's
filter of them lands within 1.183 codes (1/255) of Metal's sum on the format's grid, so a draw
binding such a texture makes no pipeline of its own.
+6 -1
View File
@@ -44,7 +44,7 @@ Its limits, measured rather than asserted:
| committed recordings | 1122 |
| distinct SDK items the Metal leg reaches, of any status | 800 |
| of those, reached only where this cannot name the family | 2 |
| ledger rows (a case whose gap is recorded) | 931 |
| ledger rows (a case whose gap is recorded) | 936 |
| declared crossings of the option space (pairs put to Metal at once) | 26 |
| declared crossings that are no pair of it (a boolean or numeric field, or one type in two slots) | 30 |
@@ -3133,4 +3133,9 @@ A case whose difference from Metal is recorded rather than compared away. The le
| `compressed-blits-rgb9e5f` | Metal's blit through the lossless compression it keeps this `RGB9E5Float` texture in lowers each texel's shared exponent to the least that holds its value, and … |
| `compressed-blits-rgb9e5f` | Metal's blit through the lossless compression it keeps this `RGB9E5Float` texture in lowers each texel's shared exponent to the least that holds its value, and … |
| `compressed-blits-rgb9e5f` | Metal's blit through the lossless compression it keeps this `RGB9E5Float` texture in lowers each texel's shared exponent to the least that holds its value, and … |
| `sampler-mip-nearest` | Under a nearest mip filter and `lodMinClamp` 1.5 Metal reads level 1 (`ceil(clamp + 0.5) - 1`, the case's table); the device's own sampler takes the descriptor'… |
| `sampler-mip-filter-pairs-nearest` | Under a nearest mip filter and `lodMinClamp` 1.5 Metal reads level 1 (`ceil(clamp + 0.5) - 1`, the case's table); the device's own sampler takes the descriptor'… |
| `sampler-mip-filter-pairs-nearest` | Under a nearest mip filter and `lodMinClamp` 1.5 Metal reads level 1 (`ceil(clamp + 0.5) - 1`, the case's table); the device's own sampler takes the descriptor'… |
| `sampler-mip-filter-pairs-nearest` | Under a nearest mip filter and `lodMinClamp` 1.5 Metal reads level 1 (`ceil(clamp + 0.5) - 1`, the case's table); the device's own sampler takes the descriptor'… |
| `sampler-mip-filter-pairs-nearest` | Under a nearest mip filter and `lodMinClamp` 1.5 Metal reads level 1 (`ceil(clamp + 0.5) - 1`, the case's table); the device's own sampler takes the descriptor'… |
+2 -20
View File
@@ -59,9 +59,9 @@ known. The rest of the differences are docs/API.md section 9's precision notes.
| Fast-math sums, differences and products group, and a multiply contracts into an addition, as the device's compiler groups and fuses them, on every device, MoltenVK included: each operation is emitted in the AIR's order, one carrying both `contract` and `reassoc` undecorated and any other `NoContraction`. Metal's compiler takes its own grouping (its rank order of a sum's leaves, its pairing of a product's lane-uniform factors) and its own fusion pairs. | The device's grouping is the contract: what the AIR's flags allow, the device's compiler chooses; nothing reproduces Metal's choice. | Unbounded relative to the result where a sum of mixed signs is grouped otherwise, or a multiply-add is fused on one side alone; each operation kept apart is exact as written. `FastMathRewrites` (`fast-math-rewrites`) |
| Off MoltenVK a `float` multiply, and a fused multiply-add by `OpFmaKHR`, round before Metal's flush: Metal flushes a result whose exact value lies below `2^-126` before rounding it, so a result whose exact value lies within half a unit below `2^-126` answers `2^-126` of its sign where Metal answers the zero of its sign. | Every device measured off MoltenVK (RADV, ANV, NVIDIA, lavapipe) rounds first; its multiply is the contract. | Announced once per device as it is made: `float-tininess-after-rounding` |
| `f32` denormals in a `float` operation on a device not measured to read them as Metal does (`DriverDeviation::MetalFloatDenormals`: lavapipe, and every unmeasured device), in `floor` and `ceil` on every device, in the maths functions and the device's order of the rows above, and in a conversion to or from `double`. Metal reads them as zero and flushes a denormal result. | The device's reading is the contract: Vulkan lets each device keep or flush them, and Metal runs no `double`, so its reading of a conversion is not measured. | `DeviceDenormals` (`device-denormals`) |
| Samples, gathers and depth comparisons are the device's own sampler's on every device whose sampler is not Metal's (every device but MoltenVK): its filter, footprint, level, anisotropy, sRGB decode and comparison. A two-plane YCbCr texture's linear sample is the device's filter of its texels (the device's own Y′CbCr conversion's where it converts the format, next row; Metal's reads exactly elsewhere); where the device's memory is the host's, a sample that reads the planes in place is Metal's filter exactly. An 8-bit sRGB format the device cannot sample (`R8_SRGB` on lavapipe, `R8G8_SRGB` on lavapipe, ANV and NVIDIA) is held as its UNORM twin, the device lacking its decode: a read, a nearest sample, a fetch, a gather and a bicubic tap decode the twin's codes through Metal's table, exactly, and a filtered sample is the device's filter of the codes, decoded through the table. | The device's sampler is the contract. | Linear filter within one code (1/255) on the measured devices, sRGB within 1.83, a two-plane YCbCr texture's within 1.183; levels, anisotropy, cubes, 3D, gathers and comparisons unmeasured. A twin's filtered sample: exact for one texel and for a blend of two adjacent codes, up to 0.286 off for a blend of codes 0 and 255 (`SrgbTexelDecode`). `DeviceSampling` (`device-sampling`) |
| Samples, gathers, depth comparisons and level queries are the device's own sampler's on every device whose sampler is not Metal's (every device but MoltenVK): its filter, footprint, level, anisotropy, sRGB decode and comparison, its level clamp (the descriptor's as given, which Metal holds on a `1/64` grid) and its reading of a subnormal coordinate (which Metal reads as the zero of its sign before addressing). A sample's or gather's residency on a device with `shaderResourceResidency` is the device's `OpImageSparse*` word and non-resident value (`SparseResidency`); Metal's footprint rule answers it only where the device has no residency and the slot's tile map does. A two-plane YCbCr texture's linear sample is the device's filter of its texels (the device's own Y′CbCr conversion's where it converts the format, next row; Metal's reads exactly elsewhere); where the device's memory is the host's, a sample that reads the planes in place is Metal's filter exactly. An 8-bit sRGB format the device cannot sample (`R8_SRGB` on lavapipe, `R8G8_SRGB` on lavapipe, ANV and NVIDIA) is held as its UNORM twin, the device lacking its decode: a read, a nearest sample, a fetch, a gather and a bicubic tap decode the twin's codes through Metal's table, exactly, and a filtered sample is the device's filter of the codes, decoded through the table. | The device's sampler is the contract. | Linear filter within one code (1/255) on the measured devices, sRGB within 1.83, a two-plane YCbCr texture's within 1.183; levels, anisotropy, cubes, 3D, gathers and comparisons unmeasured. A twin's filtered sample: exact for one texel and for a blend of two adjacent codes, up to 0.286 off for a blend of codes 0 and 255 (`SrgbTexelDecode`). `DeviceSampling` (`device-sampling`) |
| A two-plane YCbCr texture's texels are the device's own sampler Y′CbCr conversion of its planes where the device converts their format (`ycbcr_device.rs`): unpacked 8- or 10-bit codes of a 4:2:0, 4:2:2 or 4:4:4 layout over plane 0 that form one image (no chroma codes 0, no rows past the buffer; a 4:4:4 layout read as codes aside, whose identity conversion converts nothing), on a device that enables `samplerYcbcrConversion` (a 4:4:4 layout also needs Vulkan 1.3 or `VK_EXT_ycbcr_2plane_444_formats`), reports the multi-planar format's conversion and, for a 4:2:0 or 4:2:2 layout, Metal's reconstruction (midpoint chroma through a linear chroma filter), and has no defect in the format; the planes are copied into an image of it and sampled once per texel into the texture's image (`bind::ycbcr_sample_module`), through the refresh's indirect arguments. The conversion takes the surface's matrix and range (the identity model for the code-reading formats), and Metal's reconstruction of a subsampled layout; a device's cosited or nearest reconstruction would move what the codes mean to Metal (cosited, up to 1340/2048 of random planes on lavapipe), a capability it lacks, so such a layout converts through Metal's arithmetic. A render pass's load stays Metal's arithmetic, which our store inverts, so a loaded texel no draw changes keeps its codes, as `MTLLoadActionLoad` keeps the attachment's contents. lavapipe (Mesa 26.0.8) converts the 8-bit 4:4:4 layout (its 4:2:0 and 4:2:2 ones are cosited only, and it reads 10-bit codes as 16-bit words, `RuntimeDriverDefect::TenBitCodesReadAsWords`); MoltenVK 1.4.2 converts none (its 4:2:0 and 4:2:2 reconstruction is misplaced, `RuntimeDriverDefect::TwoPlaneChromaMisplaced`, and it reports no 4:4:4 two-plane format). Elsewhere, and for packed codes, chroma codes 0 and plane 1, Metal's fixed-point conversion stays as capability (`WorkCounts::ycbcr_device_conversions`). | The device's conversion is the contract: Vulkan states the reconstruction's weights and the model's matrices, the precision of each step at least the format's, and the clamp of the result into `[0, 1]` the implementation's. | Each channel within 0.04/2048 of Vulkan's conversion past the `half` its image stores on lavapipe's 8-bit 4:4:4 layout; of Metal's read within 6/2048 where the result lies in `[0, 1]`, and unclamped outside it (random planes, every texel, `tests/ycbcr_device.rs`). `YCbCrFilterNotExact` (`ycbcr-filter-not-exact`) |
| A texel's `float` value is the device's conversion of its codes, and a `half` result the device's `float` texel rounded to nearest even, on every device whose texture unit is not Metal's (every device but MoltenVK). An sRGB texel (the 8-bit sRGB formats, and the sRGB forms of BC1 to BC3, BC7, PVRTC, ETC2, EAC and ASTC, a decoded twin's through its `R8G8B8A8_SRGB` view) is the device's sRGB decode through the texture's sRGB view, in every read, sample, gather, bicubic tap and input-attachment read, where Metal decodes each code through its twelve-bit table. | The device's conversion is the contract. | One `f32` ulp for 8- and 16-bit codes, 0.18 of a code for 5- and 6-bit packed channels; `half` within one ulp; NaN bits the device's. An sRGB decode: lavapipe's within 5.25 steps of Metal's table (0.00128) at every code, MoltenVK's Metal's at every code (`runtime_lane::srgb_decode`); Vulkan sets no precision for it, and other devices are not measured. `DeviceTexelConversion` (`device-texel-conversion`), `HalfTexelConversion` (`half-texel-conversion`, also recorded for heap textures and unmeasured formats), `SrgbTexelDecode` (`srgb-texel-decode`, under the bound format) |
| A texel's `float` value is the device's conversion of its codes on every device whose texture unit is not Metal's (every device but MoltenVK), and a `half` result the device's `float` texel rounded to nearest even on every device: on MoltenVK the `float` texel is Metal's, whose `half` Metal rounds otherwise for a 32-bit float texel's sample (toward zero, saturating at `±65504`) and the 16-bit normalized grids (three steps round twice through `float`); a two-plane YCbCr field on the grid `8192` keeps Metal's ties away from zero in one texel's read, sample and gather. An sRGB texel (the 8-bit sRGB formats, and the sRGB forms of BC1 to BC3, BC7, PVRTC, ETC2, EAC and ASTC, a decoded twin's through its `R8G8B8A8_SRGB` view) is the device's sRGB decode through the texture's sRGB view, in every read, sample, gather, bicubic tap and input-attachment read, where Metal decodes each code through its twelve-bit table. | The device's conversion is the contract. | One `f32` ulp for 8- and 16-bit codes, 0.18 of a code for 5- and 6-bit packed channels; `half` within one ulp, but a 32-bit float texel's sample past `±65504` the infinity of its sign where Metal saturates (MoltenVK included); NaN bits the device's. An sRGB decode: lavapipe's within 5.25 steps of Metal's table (0.00128) at every code, MoltenVK's Metal's at every code (`runtime_lane::srgb_decode`); Vulkan sets no precision for it, and other devices are not measured. `DeviceTexelConversion` (`device-texel-conversion`), `HalfTexelConversion` (`half-texel-conversion`, also recorded for heap textures and unmeasured formats), `SrgbTexelDecode` (`srgb-texel-decode`, under the bound format) |
| A texture of a BC format (`BC1_RGBA` to `BC7_RGBAUnorm_sRGB`) is the device's decode of its own BC image on every device: where its driver is not measured to decode the format as Metal does (BC1 to BC3 off MoltenVK and RADV on the 780M; BC4 and BC5 off MoltenVK; BC7 on lavapipe), its reads, samples and gathers answer the device's interpolation of the blocks, where Metal's weights are 6-bit (an sRGB form's code then through the device's sRGB decode, the texel-conversion row). No BC texture keeps a decoded twin. | The device has the format: its decode is the contract. | A BC1 to BC3 channel within 3/255 of Metal's on NVIDIA (BC3's alpha 6/255) and lavapipe, 1/255 on ANV; a BC4 or BC5 channel within 7.3/255 (signed 0.064) on NVIDIA, 1.3/255 (signed 0.013) on ANV, 2.4/255 (signed 0.022) on lavapipe, a signed one with an endpoint of -128 within 1.7/255 on RADV; a BC7 channel a `float` ulp on lavapipe; other drivers unmeasured. `CompressedTexelDecode` (`compressed-texel-decode`) |
| A vertex attribute that fixed-function vertex input fetches is the device's conversion of its format: a normalized one (`UCharNormalized` through `Short4Normalized` of either sign, `UChar4Normalized_BGRA`, `Int1010102Normalized`, `UInt1010102Normalized`) through its own Vulkan `UNORM` or `SNORM` vertex format, where Metal divides each code by its maximum correctly rounded (an `Int1010102Normalized` 10-bit field it multiplies by `float(1 / 511)` in `float`) and rounds the quotient once to a `half` attribute; a narrow float's (a `half` format, `FloatRG11B10`) read as `float` by the device's widening, NaNs included. The format is `VertexAttribute` state that no instruction names, so every format the device fetches shares one module, and the render pipeline's link notes the conversion on its vertex stage (`pipeline::link::vertex`). **Exempt:** a normalized attribute on a profile that takes `DriverDeviation::MetalNormalizedVertexFetch`, MoltenVK on Apple's GPUs of the Apple M3 Max's macOS 27 identity, which hands the format to Metal's own fetch and was measured to answer Metal's `float` at every code of all 19 normalized formats, per vertex and per instance (`runtime_lane::normalized_vertex_fetch`): its pipeline records no note and requires `VkProperty::MetalNormalizedVertexFetch`, but for a 16-bit format read as `half`, whose `float` the module rounds to `half` again. | The device's conversion is the contract. | One `f32` ulp at some codes on a driver that multiplies by the reciprocal: llvmpipe, read at every code (Mesa 26.0.8 on LLVM 21.1.8, arm64), is within one ulp per vertex at every normalized format (127/255 as `0x3EFEFF00` where Metal reads `0x3EFEFEFF`; `Int1010102Normalized` Metal's), and per instance reads the most negative code of an 8- or 16-bit signed format unclamped (-128/127, -32768/32767) where Metal reads -1; RADV's unsigned formats are Metal's at the sites measured. A 16-bit format read as `half`: one `half` ulp at codes 65455 and 65519 unsigned, 32759 and -32759 signed, on a device whose `float` is Metal's (the quotient rounded to `half` twice). The signed formats are **unaudited** on RADV, ANV and NVIDIA. A narrow float's NaN is the device's widening's, where Metal answers `0x7fc00000`. `DeviceVertexConversion` (`device-vertex-conversion`), `DeviceNanEncoding` (`device-nan-encoding`) |
| 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, which its slots read through the twin's `R8G8B8A8_SRGB` view, the device's sRGB decode (the texel-conversion row). 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 device lacks the format; the twin's codes are the compact form the device samples. | 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 |
@@ -434,15 +434,6 @@ driver's. Each is open work.
`sparse-mapping-a-slice-past-the-textures` holds every side of the difference visible, with its
four rows of `crates/metal2vulkan-conformance/known-gaps.tsv`.
- **An extended-range format's sample through a constexpr clamp-to-zero sampler at a subnormal
coordinate**: Metal's texture unit reads a subnormal normalized coordinate as the zero of its
sign before the address mode decides, so a border axis reads texel 0 just outside the level.
A sample of a 32-bit float texture flushes it as Metal does
(`lower::sampler::position::subnormal_flush`, measured on an Apple M3 Max); the extended-range
strategy (`lower::sampler::extended`), which fetches and addresses its taps itself, keeps the
coordinate as given and reads the border there. Expected and unmeasured: the measurement is on
`R32Float`, and Metal's flush on an extended-range format is not probed.
- **A two-plane YCbCr texture over plane 1 of a three-plane surface** (`y420`, `v0a8`): Metal
reads plane 2's pairs as its chroma; the surface's facts (`IoSurfaceYCbCr`) name plane 1 alone,
so the runtime reads chroma codes 0 there, as over plane 1 of a two-plane surface.
@@ -602,15 +593,6 @@ driver's. Each is open work.
(`cube-gradient-footprint`). A kernel's samples are Metal's own. A form exact inside the face,
sampling a `y` face through a 2D-array view of the cube, needs a second binding of each such cube
from the binder and the runtime; it is not built.
- **An anisotropic cube sample out of the shader's reach through MoltenVK where its cube-gradient
route is not measured** (`CubeGradientRoute::Unmeasured`). The shader takes Metal's level and taps
wherever its emulation reaches (a cube or cube array of `float` or `half` texels, without
comparison, through a constexpr sampler or a runtime sampler slot under its variant). A depth or
comparison sample, one whose residency the function reads, an argument buffer's texture or
sampler, or a slot of another class or swizzled storage takes Metal's isotropic footprint through
a sampler made isotropic for that use, where Metal filters an ellipse, announced as
`CubeGradientFootprint`. An argument buffer's sampler needs its degree in its table entry; it is
not built.
- **A group operation in a branch arm whose speculation no probe covers.** Metal's backend runs a
branch's short arms of plain computation in every lane of the branch's block; the module does the
same for the arm shapes measured on Apple's GPU (`air::canon::speculate`). A branch of another