Sampler: Metal's own sampler and the cube-gradient routes go

DriverDeviation::MetalSampler, CubeGradientRoute and GraphicsCubeGradientTangents, with
VkProperty::MetalSampler and its codec tag, were never taken: Device::from_queries enables no
Metal* property and always inserts VkProperty::DeviceSampling, and no committed profile carries
a Metal* property. ProfileFields::cube_gradients, with CubeGradients and CubeGradientRoute, had
one reachable value (Vulkan's rule for both stages), so it goes too. The forms only they reached
go with them:
- Cube gradients: CubeFootprint::Metal and ::Projected (MoltenVK's gradientcube and its
  graphics fixup); a cube's explicit gradients take Length, Face or Word by the sampler's
  anisotropy alone, and CubeGradientFootprint is raised wherever the shader does not take
  Metal's level and taps itself.
- The sampler requirement: SamplerFamily::metal_sampler merges into device_sampling. Every
  sample, gather and LOD query, the hoisted no-bias samples and BiasReach::Metal's included,
  requires VkProperty::DeviceSampling and records DeviceSampling, as on every real device.
- The half-texel routine (lower/texture/half.rs) and everything only it read: HalfClass,
  half_class and heap_half_class, TexelLanes and TexelOrigin, the texel argument of texel_value
  and held_value, sample_lanes and word_reads_one, Sampling::one_texel's word forms (one_texel
  now answers whether an access may read one texel, which float_texel_notes reads) and
  half_texel, SamplerSlot::texels, SlotPlan::half_format and unmeasured, TexturePlan::heap_half,
  the declarations half_format, half_routine and plain_half, the module's table of heap texel
  classes (AccessPlan::heap_class, declare_heap_classes, heap_texel_class, HEAP_CLASS_WORDS, and
  texel_format::heap_classes, whose tests now read the layout itself),
  texel_round::f32_to_half_from_even, NoteOn::Unmeasured, SpecKey::UnmeasuredTexels and
  PlainHalfTexels with their plan answers, TexelFormat::YCBCR_8192, MEASURED_ON_METAL_SAMPLER,
  unmeasured_on_metal_sampler and plain_on_metal_sampler, and the identity-domain refusal of a
  heap half sample that only a Metal-sampler profile met.
- The Metal sampler's YCbCr filter note (linear::filter_note and metal_filtered_ycbcr), with
  NoteOn::HeapYCbCr and ArgumentSamplers, SpecKey::HeapYCbCrTextures and
  FilteringArgumentSampler, their plan answers and TexelFormat::two_plane_ycbcr.
- The anisotropic not-mipmapped clamp [0, 0] (vk_sampler's own_anisotropic) and its note's
  source (anisotropic::own_not_mipmapped); PrecisionNote::NotMipmappedAnisotropicFilter, its
  codec tag, conformance Degradation and validation allowance go with its only source.
- The rest: device_texels, device_decode's and fragment/color.rs's Metal decode,
  bind::plan::resources' swizzled_packed profile test, and border_read's metal_sampler (and
  device_opaque_black's format argument, which nothing then read).

Rule 1, per note the commits stop raising: every one is case (b), no difference goes silent.
- filter_note's HalfSampleFilter and FloatSampleFilter (slot clauses on a bound two-plane YCbCr
  format and the bound sampler word, heap clauses on HeapYCbCrTextures and
  FilteringArgumentSampler): raised only on a profile with VkProperty::MetalSampler, so on no
  real device. Such a filtered sample goes to the device's own sampler, and every sample,
  gather and LOD query sets device_sampling, so the stage records DeviceSampling, whose entry
  covers the device's filter of a two-plane texture. The in-place Y'CbCr model's
  HalfSampleFilter and FloatSampleFilter stay as they were.
- NotMipmappedAnisotropicFilter: raised only under own_not_mipmapped, which needed
  MetalSampler. An anisotropic sample on a device with samplerAnisotropy goes to the device's
  sampler (DeviceSampling, its not-mipmapped clamp [0, 0.25] the device's footprint), and one
  without it keeps AnisotropicFilter or DeviceAnisotropicFilter, as on every real device.
- The rest only widen: HalfTexelConversion (now outright at every half read, sample and gather,
  where the Metal-sampler profile tested the bound class), DeviceTexelConversion, SrgbTexelDecode
  and CubeGradientFootprint, each withheld only on a Metal-sampler or Metal-route profile.
The precision-note catalogue loses NotMipmappedAnisotropicFilter alone; the docs of
GradFromBias, HalfTexelConversion, HalfSampleFilter, SrgbTexelDecode, FloatSampleFilter,
DeviceSampling and DeviceTexelConversion lose their Metal-sampler clauses (docs/API.md's entries
already stated the one rule).

Validation: comparison.rs's allowance list loses NotMipmappedAnisotropicFilter (unbounded),
which no device raised; its HalfSampleFilter and FloatSampleFilter reasons now name the in-place
model, their class unchanged (unbounded). No validation file names a deleted DriverDeviation.

Also, from the planner: the citation of VUID-RuntimeSpirv-NonUniform-06274, which spec 1.4.366
no longer has, becomes VUID-RuntimeSpirv-None-10148 and VUID-RuntimeSpirv-subgroupSize-10149 in
spirv/builder/ops/memory.rs, spirv/ir/module.rs (twice), spirv/serialize/mod.rs and the doc of
non_uniform_elements_are_decorated_through_what_carries_them. Comments only.

Tests: each deleted form's tests go with it: lower/arith/tests/half_texel.rs (the routine, its
plain arm, and the steps that bounded the Metal-sampler note) with arith/tests.rs'
quantize_flush_of, which only it read,
f32_to_half_from_even_is_exact_on_every_tie, the projected-footprint test and the swizzle
helper of face/tests/anisotropic.rs, texel_format's ycbcr_8192, wide16 and
metal_sampler_s_read_bits tests, the format version 326 round trip, and the routes' asserts in
engine_handles, engine_heap_binder and engine_sampler_unk. The rest assert the device's sampler
on every profile: half_reads_round_their_texel_to_nearest_even (was
half_reads_convert_by_the_bound_format), heap_half_texels_round_the_device_s_texel (was
heap_half_texels_convert_by_the_handle_s_class), heap_linear_samples_are_the_device_s (no
FloatSampleFilter, outright or specialized), engine_sample_coordinates' requires_the_sampler,
engine_bias_reach, engine_graphics_binder's border test, engine_srgb_decode, engine_sampler,
the routines test, the merged-members round trip, and metal/sampler.rs' and
format/tests.rs' opaque-black calls.

SEMANTICS_VERSION 2239, ARTIFACT_FORMAT_VERSION 577 (placeholders; main renumbers). SEMANTICS:
the profile's fingerprint and the notes of the same input change form. ARTIFACT: the codec loses
the VkProperty, the PrecisionNote and four SpecKey tags. RUNTIME_VERSION stays: the pinned
sources' edits (device/, bind/plan/resources.rs and slots.rs, metal/sampler.rs, cache/codec.rs)
remove forms and keys no profile reached, so no run changes; runtime-sources.sha256 takes the new
hash. api_signatures is blessed; docs/REFUSALS.md and the coverage are unchanged.

Consumer check (consumer-uses.sh, consumer development 2040502291, 62 refs): CubeGradientRoute,
GraphicsCubeGradientTangents, CubeGradients, cube_gradients, FilteringArgumentSampler,
HeapYCbCrTextures, PlainHalfTexels and UnmeasuredTexels 0 hits (code). MetalSampler and
NotMipmappedAnisotropicFilter: 0 hits on development (its answer.rs names neither, and it has no
gpu/rgbx.rs); named in crates/reims-vgpu-vulkan/src/answer.rs and gpu/rgbx.rs on 36 of the
consumer's steelbrain/* branches younger than a day.

Verified: m3-max-61441 (msi-laptop, this tree): fmt, clippy (all features, --cfg m2v_gpu,
--cfg m2v_cpu_icd), Rustdoc green; tests 5861 of 5863 passed. The two failures:
golden_hashes_match_the_table, every one of its 29536 cells under a changed profile fingerprint
(re-blessed on development at a named pin), and the_old_render_descriptor_key_keeps_its_value,
left unpinned until the next named pin.

Rebased onto development d10a14d5af: the SEMANTICS placeholder is one above its 2235 in stack order
(ARTIFACT_FORMAT_VERSION is already above its 574). The checks above ran at the old base acc706ca47;
the rebased stack's tip is checked by m3-max-61756 (msi-laptop), at the stack rebased on d6d56b8a7c
(tip 5c74fad38d, whose diff from its base is this stack's diff from d10a14d5af): fmt, clippy (all
features, --cfg m2v_gpu, --cfg m2v_cpu_icd) and Rustdoc green; nextest of metal2vulkan,
metal2vulkan-validation, metal2vulkan-conformance and metal2vulkan-runtime ran 5877 tests, 5870
passed. Of the 7 failures, the old render descriptor key's test is unpinned; golden_hashes and
engine inventory parts 4, 5, 7 and 8 are bless due (the profiles' fingerprints changed); and
metal::state's encoder_raster_state_needs_its_features fails the same way at development d10a14d5af
itself (m3-max-61802, where runtime-floor gained depthBiasClamp in a529fb658e), as inventory parts
3, 4, 5 and 8 do there. The stack as rebased on 72e1754218 (tip 090d544208: the same product
changes, without the test-only push sweep fix) played 36 distinct streams over 61 runs on five nodes
with 0 refused (player m3-max-61537; plays m3-max-61548, 61549, 61550, 61559 and 61569).
This commit is contained in:
Anees Iqbal committed 2026-11-20 22:07:19 -08:00
1 parent efa911bc00
commit 305d85a2a2
66 files changed
+435 -2866

No files matched your search

@@ -292,7 +292,7 @@ impl Case for BorderSwizzles {
fn allowances(&self) -> Vec<Allowance> {
// The sample goes to the device's own sampler and the texel's `float` value is the
// device's conversion of its codes, which the runtime announces as `device-sampling` and
// `device-texel-conversion` off Metal's own texture unit: native notes the suite declares
// `device-texel-conversion`: native notes the suite declares
// for every case, which loosen no word. A word the device's conversion moves is a
// `known-gaps-rt.tsv` row of the venue.
//
@@ -50,7 +50,7 @@
//! 515 texels -- and no finite, zero, denormal or infinite texel differs anywhere.
//!
//! **Where the payload goes.** Our `half` access reads the image as a `vec4` of `f32` and converts
//! it (`lower::texture::half`, through `narrow::round_texel`), and this chip's decode of a 16-bit
//! it (`narrow::round_texel`), and this chip's decode of a 16-bit
//! float texel into `f32` canonicalizes the NaN, so the sign and the payload are gone before the
//! conversion sees them -- which is why all twelve codes, of both signs, collapse onto one value,
//! and why the `widened` column, where Metal canonicalizes too, is exact. Metal's `texture2d<half>`
@@ -288,7 +288,7 @@ const NAMES: [&str; 16] = [
];
/// The site an argument buffer's pixel sampler answers at, and the site its normalized control
/// answers at: the two a device without Metal's own sampler may differ at.
/// answers at: the two a device's own sampler may differ at.
const ARGUMENT_SITE: &str = "arg";
const CONTROL_SITE: &str = "norm";
@@ -159,8 +159,6 @@ pub enum Degradation {
TessellationTriangleOrder,
/// `metal2vulkan-degrade-unmeasured-group-speculation`.
UnmeasuredGroupSpeculation,
/// `metal2vulkan-degrade-not-mipmapped-anisotropic-filter`.
NotMipmappedAnisotropicFilter,
/// `metal2vulkan-degrade-device-sample-level`.
DeviceSampleLevel,
/// `metal2vulkan-degrade-coverage-reads-rounded-alpha`.
@@ -262,7 +260,6 @@ impl Degradation {
Degradation::DevicePackConversion,
Degradation::TessellationTriangleOrder,
Degradation::UnmeasuredGroupSpeculation,
Degradation::NotMipmappedAnisotropicFilter,
Degradation::DeviceSampleLevel,
Degradation::CoverageReadsRoundedAlpha,
Degradation::DeviceAlphaCoverage,
@@ -389,9 +386,6 @@ impl Degradation {
Degradation::UnmeasuredGroupSpeculation => {
"metal2vulkan-degrade-unmeasured-group-speculation"
}
Degradation::NotMipmappedAnisotropicFilter => {
"metal2vulkan-degrade-not-mipmapped-anisotropic-filter"
}
Degradation::DeviceSampleLevel => "metal2vulkan-degrade-device-sample-level",
Degradation::CoverageReadsRoundedAlpha => {
"metal2vulkan-degrade-coverage-reads-rounded-alpha"
@@ -486,9 +480,6 @@ impl Degradation {
PrecisionNote::DevicePackConversion => Degradation::DevicePackConversion,
PrecisionNote::TessellationTriangleOrder => Degradation::TessellationTriangleOrder,
PrecisionNote::UnmeasuredGroupSpeculation => Degradation::UnmeasuredGroupSpeculation,
PrecisionNote::NotMipmappedAnisotropicFilter => {
Degradation::NotMipmappedAnisotropicFilter
}
PrecisionNote::DeviceSampleLevel => Degradation::DeviceSampleLevel,
PrecisionNote::CoverageReadsRoundedAlpha => Degradation::CoverageReadsRoundedAlpha,
PrecisionNote::DeviceAlphaCoverage => Degradation::DeviceAlphaCoverage,
@@ -461,8 +461,8 @@ pub fn reads_opaque_black_border(spec: &crate::case::SamplerSpec) -> bool {
/// `half-texel-conversion`, `srgb-texel-decode`, the device's fixed-function conversion of a
/// normalized vertex attribute (`device-vertex-conversion`), `device-color-conversion`;
/// - **sampling and filtering**: `device-sampling`, `device-sample-level`, the device's filter of a
/// generated mipmap chain (`device-filtered-mipmaps`), and Metal's own sampler filtering a
/// two-plane texture on MoltenVK (`half-sample-filter`, `float-sample-filter`);
/// generated mipmap chain (`device-filtered-mipmaps`), and Vulkan's Y′CbCr model filtering a
/// two-plane texture's planes read in place (`half-sample-filter`, `float-sample-filter`);
/// - **blending**: the device's arithmetic of the blend a function computes into an extended-range
/// attachment, whose raw codes no blend unit reads (`extended-range-blend-source`,
/// `extended-range-float-blend-source`: `S·Fs op D·Fd` in `float`, where Metal's compiler rounds
-3
View File
@@ -2519,9 +2519,6 @@ or does not check is rebuilt from the generations' names, with young counted ful
invocations): the translator test
`an_argument_buffer_textures_sample_in_a_form_not_lowered_is_refused_naming_it` asserts the
text;
- a sample or gather of an argument buffer's color texture with a `half` result on a device
that samples through Metal's own sampler (`VkProperty::MetalSampler`), which no device's
derivation states: no test;
- a bicubic sample at pixel coordinates ("a bicubic filter at pixel coordinates") and one of a
1D texture ("a bicubic filter of a 1D texture"): the translator test
`a_bicubic_kernel_reads_each_slots_format_treatment_from_its_pushed_field` asserts each text;
@@ -1 +1 @@
9c0db9f87ef306400bae2334e3749350c1a68c875d2a5d5b1f5e9ffb93c17e7a
3e75ca833c8e7995ca4942629762554302d5d860ba96dd0ee33978d2d87a5cf7
@@ -153,8 +153,6 @@ impl UlpTable {
/// whole primitives, not lanes.
/// - `UnmeasuredGroupSpeculation`: unbounded: a quad or simdgroup operation answering over other
/// lanes reads another lane's value, which differs from Metal's by any amount.
/// - `NotMipmappedAnisotropicFilter`: unbounded: another anisotropic footprint reads other texels,
/// which differ from Metal's by up to the texture's range.
/// - `DeviceSampleLevel`: unbounded: another level or filter near a boundary reads other texels,
/// which differ from Metal's by up to the texture's range, and an LOD query answers the device's
/// level.
@@ -190,17 +188,15 @@ impl UlpTable {
/// - `HalfTexelConversion`: unbounded: a format whose conversion to `half` is not measured keeps
/// the device's quantize of its `f32` texel, so a lane can differ from Metal's by any amount (an
/// sRGB texel's decode).
/// - `HalfSampleFilter`: unbounded: a filtered `half` sample of a two-plane YCbCr texture through
/// Metal's own sampler (MoltenVK) filters the converted texels as an `RGBA16Float` or
/// `RGBA32Float` texture's, off the format's grid; one step of the grid was measured on one chip
/// and format, which no tolerance is derived from.
/// - `HalfSampleFilter`: unbounded: a filtered `half` sample of a two-plane YCbCr texture whose
/// planes the function reads in place blends the codes by Vulkan's Y′CbCr model, off Metal's
/// sum on the format's grid, which no tolerance is derived from.
/// - `SrgbTexelDecode`: unbounded: an 8-bit sRGB texel the device decodes where Metal decodes its
/// raw code through a twelve-bit table; Vulkan bounds the device's decode only by its precision
/// rules, and Metal's `float` gathers of sRGB texels are not measured.
/// - `FloatSampleFilter`: unbounded: a filtered `float` sample of a two-plane YCbCr texture through
/// Metal's own sampler (MoltenVK) filters the converted texels as an `RGBA16Float` or
/// `RGBA32Float` texture's, off the format's grid; one step of the grid was measured on one chip
/// and format, which no tolerance is derived from.
/// - `FloatSampleFilter`: unbounded: a filtered `float` sample of a two-plane YCbCr texture whose
/// planes the function reads in place blends the codes by Vulkan's Y′CbCr model, off Metal's
/// sum on the format's grid, which no tolerance is derived from.
/// - `QuadsCountedBeforeDiscard`: unbounded: a non-quad simdgroup operation before a discard, in a
/// shape whose placement by Metal's compiler is not known, takes, among its lanes, the quads the
/// discard drops, which moves a count, a ballot, or a reduction by whole lanes.
@@ -284,7 +280,6 @@ pub fn allowance(note: PrecisionNote) -> Allowance {
| N::TessellationFractionalSpacing
| N::TessellationTriangleOrder
| N::UnmeasuredGroupSpeculation
| N::NotMipmappedAnisotropicFilter
| N::DeviceSampleLevel
| N::UnmeasuredFetchBlend
| N::Fp8Value
+6 -48
View File
@@ -1358,14 +1358,13 @@ impl ResourcePlanner<'_> {
// move onto another channel's lane before the function converts it, so its
// class would drop the field and a read, gather or one-texel sample keep the
// device's widening of a 4-, 5- or 6-bit code (NVIDIA's and ANV's replicate its
// bits, where Metal answers `c / (2^b - 1)`): on a device
// that does not sample through Metal's own sampler, the function converts the
// bits, where Metal answers `c / (2^b - 1)`): the function converts the
// unswizzled texel by the format's whole class and swizzles it, under the same
// variant, and the view takes none.
let reads_packed = !storage
&& extended.is_none()
&& (t.access.read || t.access.sample)
&& swizzled_packed(self.profile, pixel_format, swizzle);
&& swizzled_packed(pixel_format, swizzle);
let decodes_srgb = !storage
&& (t.access.read || t.access.sample)
&& self.swizzles_decoded_srgb(slot, pixel_format, swizzle);
@@ -1841,7 +1840,7 @@ impl ResourcePlanner<'_> {
// variant (`texture_write`'s `reads_packed`): its sampler reads the
// unswizzled texture's border texel, which the function swizzles.
let shader_swizzle = !swizzle.is_default()
&& (swizzled_packed(self.profile, pixel_format, swizzle)
&& (swizzled_packed(pixel_format, swizzle)
|| self.swizzles_decoded_srgb(texture, pixel_format, swizzle));
if shader_swizzle {
self.variant.swizzled_storage.insert(texture);
@@ -2077,36 +2076,6 @@ impl ResourcePlanner<'_> {
u64::from(class)
}
/// The `UnmeasuredTexels(slot)` specialization: 1 where a texture or texture buffer is bound
/// at `slot` and its class ([`texel_format`](Self::texel_format)) is unmeasured on a device
/// that samples through Metal's own texture unit
/// (`TexelFormat::unmeasured_on_metal_sampler`), else 0, a slot bound to nothing's among
/// them, and one bound to a placeholder format, which reads its neutral (its zero texel
/// converts alike under every class).
pub fn unmeasured_texels(&self, slot: SlotRef) -> u64 {
match self.texture_shape(slot) {
Some(shape) if shape.pixel_format() != crate::metal::PixelFormat::Invalid => {
u64::from(TexelFormat(self.texel_format(slot) as u32).unmeasured_on_metal_sampler())
}
_ => 0,
}
}
/// The `PlainHalfTexels(slot)` specialization: 1 where the class of the texture or texture
/// buffer bound at `slot` ([`texel_format`](Self::texel_format)) converts every texel to
/// `half` as its `float` value rounded to nearest even on a device that samples through
/// Metal's own texture unit (`TexelFormat::plain_on_metal_sampler`), else 0; 1 for a slot
/// bound to nothing and one bound to a placeholder format (its zero texel converts alike
/// under every class).
pub fn plain_half_texels(&self, slot: SlotRef) -> u64 {
match self.texture_shape(slot) {
Some(shape) if shape.pixel_format() != crate::metal::PixelFormat::Invalid => {
u64::from(TexelFormat(self.texel_format(slot) as u32).plain_on_metal_sampler())
}
_ => 1,
}
}
/// The `TextureSwizzle(slot)` specialization: the swizzle of the texture buffer bound at
/// `slot`, as its word, which the function applies to its reads, or of the texture bound at a
/// storage slot of the plan's `VariantKey::swizzled_storage`, which it applies to its reads and
@@ -2136,20 +2105,9 @@ impl ResourcePlanner<'_> {
/// (`VariantKey::swizzled_storage`) on `profile`'s device: a packed normalized format
/// (`TexelFormat::packed_exact`), whose texel the function converts by each channel's own code
/// scale, under a swizzle that reads some texel as no unswizzled texture does
/// (`reads_unswizzled`), on a device that does not sample through Metal's own sampler (where the
/// device's sample is Metal's, swizzle and all, `VkProperty::MetalSampler`).
fn swizzled_packed(
profile: &DeviceProfile,
pf: PixelFormat,
swizzle: TextureSwizzleChannels,
) -> bool {
!profile
.fields()
.enabled
.properties
.contains(&crate::device::requirements::VkProperty::MetalSampler)
&& texel_format(pf).packed_exact()
&& !reads_unswizzled(pf, swizzle)
/// (`reads_unswizzled`).
fn swizzled_packed(pf: PixelFormat, swizzle: TextureSwizzleChannels) -> bool {
texel_format(pf).packed_exact() && !reads_unswizzled(pf, swizzle)
}
#[cfg(test)]
+11 -38
View File
@@ -221,8 +221,6 @@ pub(crate) fn bound_value(
.unwrap_or(u64::from(metal::sampler::NEUTRAL_BORDER_TEXELS)),
SpecKey::BicubicTexels(slot) => resources.bicubic_texels(slot)?,
SpecKey::TexelFormat(slot) => resources.texel_format(slot),
SpecKey::UnmeasuredTexels(slot) => resources.unmeasured_texels(slot),
SpecKey::PlainHalfTexels(slot) => resources.plain_half_texels(slot),
SpecKey::TextureSwizzle(slot) => resources.texture_swizzle(slot),
SpecKey::SparseTexture(slot) => sparse_texture(shape, slot),
SpecKey::ConstantLanes(slot) => constant_lanes(shape, slot),
@@ -266,10 +264,9 @@ pub(crate) fn record_specialized(
}
/// Record in `resources`' template the value of each key a specialized note of `stages` tests that
/// no push carries but the bound resources decide (`SpecKey::BoundSamplerWord`),
/// or what the command's handles can name (`SpecKey::HeapYCbCrTextures`,
/// `SpecKey::HeapRawTextures` and `SpecKey::HeapNanFamilies`, through `reach`, the stages a used resource's render stages reach,
/// as for the heap's members; `SpecKey::FilteringArgumentSampler`), which
/// no push carries but the bound resources decide (`SpecKey::BoundSamplerWord`), or what the
/// command's handles can name (`SpecKey::HeapRawTextures` and `SpecKey::HeapNanFamilies`, through
/// `reach`, the stages a used resource's render stages reach, as for the heap's members), which
/// `BindingPlan::specialized_value` gives the runtime at
/// each draw or dispatch, where it reads such a note (`StageModule::precision_notes_bound`). Nothing
/// pushes it: instantiation writes only the keys its push fields name.
@@ -289,10 +286,8 @@ pub(crate) fn record_noted<'a>(
matches!(
key,
SpecKey::BoundSamplerWord(_)
| SpecKey::HeapYCbCrTextures(_)
| SpecKey::HeapRawTextures(_)
| SpecKey::HeapNanFamilies(_)
| SpecKey::FilteringArgumentSampler
)
})
.collect();
@@ -306,14 +301,8 @@ pub(crate) fn record_noted<'a>(
continue;
}
let value = match key {
SpecKey::HeapYCbCrTextures(stage) => u64::from(heap_ycbcr(shape, stage, reach)),
SpecKey::HeapRawTextures(stage) => u64::from(heap_raw(shape, stage, reach)),
SpecKey::HeapNanFamilies(stage) => u64::from(heap_nan_families(shape, stage, reach)),
// A sampler state of any listed shape may be the one an argument buffer names.
SpecKey::FilteringArgumentSampler => u64::from(
(shape.argument_samplers.shapes.iter())
.any(|s| s.linear || s.anisotropic || s.cubic),
),
key => bound_value(key, shape, resources)?.ok_or_else(|| {
internal(format!("a noted {key:?}, which no bound resource decides"))
})?,
@@ -325,30 +314,14 @@ pub(crate) fn record_noted<'a>(
Ok(())
}
/// Whether a heap member of `shape` that reaches `stage` (`bind::heap`'s members: a texture the
/// command makes resident, its render stages through `reach`, or binds at a texture slot of the
/// stage) is of a two-plane YCbCr class (`TexelFormat::two_plane_ycbcr`).
fn heap_ycbcr(
shape: &BindShape,
stage: Stage,
reach: &dyn Fn(metal::RenderStages) -> Vec<Stage>,
) -> bool {
crate::bind::heap::members(shape, &[stage], reach)
.iter()
.any(|m| match m.shape {
TextureShape::Texture { pixel_format, .. } => {
crate::metal::texel_format::texel_format(pixel_format).two_plane_ycbcr()
}
_ => false,
})
}
/// The `SpecKey::HeapRawTextures` of `stage` for `shape`: of the heap members of `shape` that reach
/// `stage` (as for [`heap_ycbcr`]), the bit `bind::heap::HELD` where one is a texture a heap holds
/// by its raw texels alone (`bind::heap::heap_raw_form`), which the stage's `float` read, sample or
/// gather decodes by the device's arithmetic, and the bit `bind::heap::FILTERED` where one such is
/// of a form whose sample the function filters (not a bfloat one). Both the notes' value and the
/// stage's constant, whose `HELD` bit gates its raw arms (`lower::texture::heap_raw_form`).
/// `stage` (`bind::heap`'s members: a texture the command makes resident, its render stages through
/// `reach`, or binds at a texture slot of the stage), the bit `bind::heap::HELD` where one is a
/// texture a heap holds by its raw texels alone (`bind::heap::heap_raw_form`), which the stage's
/// `float` read, sample or gather decodes by the device's arithmetic, and the bit
/// `bind::heap::FILTERED` where one such is of a form whose sample the function filters (not a
/// bfloat one). Both the notes' value and the stage's constant, whose `HELD` bit gates its raw arms
/// (`lower::texture::heap_raw_form`).
pub(crate) fn heap_raw(
shape: &BindShape,
stage: Stage,
@@ -373,7 +346,7 @@ pub(crate) fn heap_raw(
/// The `SpecKey::HeapNanFamilies` of `stage` for `shape`: the bit of each family
/// (`bind::heap::nan_family`) of the heap members of `shape` that reach `stage` (as for
/// [`heap_ycbcr`]), whose texels a stage's `half` or `float` write may store a NaN in.
/// [`heap_raw`]), whose texels a stage's `half` or `float` write may store a NaN in.
fn heap_nan_families(
shape: &BindShape,
stage: Stage,
+4 -7
View File
@@ -874,11 +874,9 @@ codec_enum! {
SparseTexture(f0), TexelFormat(f0), SamplerState { slot, fields },
TgOffset(f0), TileThreadgroupLength, TileGridWidth, TextureSwizzle(f0),
ObjectLocalSize(f0), ObjectFlatLocalSize, ObjectMultiRegion, SamplerMinLevel(f0),
ConstantLanes(f0), UnmeasuredTexels(f0), BoundTexelFormat(f0), OffsetBaseAxes(f0),
SamplerAnisotropy(f0), RangeAtBindOffset(f0), PlainHalfTexels(f0),
NearestPixelSampler(f0), BoundSamplerWord(f0), HeapYCbCrTextures(f0),
FilteringArgumentSampler, StageInReach, HeapRawTextures(f0), BorderTexels(f0),
HeapNanFamilies(f0), DeepThreadgroup,
ConstantLanes(f0), BoundTexelFormat(f0), OffsetBaseAxes(f0), SamplerAnisotropy(f0),
RangeAtBindOffset(f0), NearestPixelSampler(f0), BoundSamplerWord(f0), StageInReach,
HeapRawTextures(f0), BorderTexels(f0), HeapNanFamilies(f0), DeepThreadgroup,
}
PushField {
RootTableAddress, ExecutionStatusAddress, DispatchRegion, BaseVertexInstance,
@@ -1044,7 +1042,7 @@ codec_enum! {
RoundingIndependenceAll, Rgba4OpaqueBlackSwizzled, FramebufferColorSampleCount(f0),
FramebufferIntegerColorSampleCount(f0), FramebufferDepthSampleCount(f0),
FramebufferStencilSampleCount(f0), FramebufferNoAttachmentsSampleCount(f0),
InterpolateAtOffsetCentered, SimdgroupLockstep, MetalSampler, StorageImageSampleCount(f0),
InterpolateAtOffsetCentered, SimdgroupLockstep, StorageImageSampleCount(f0),
DepthResolveMode(f0), StencilResolveMode(f0), IndependentResolveNone, IndependentResolve,
VariableSampleLocations, SampleLocationSampleCount(f0), ColorAttachmentSampleCount(f0, f1),
MetalCenterVaryings, MetalHalfStorageWrites, MetalHalfStorageNans,
@@ -1474,7 +1472,6 @@ codec_enum! {
DevicePackConversion,
TessellationTriangleOrder,
UnmeasuredGroupSpeculation,
NotMipmappedAnisotropicFilter,
DeviceSampleLevel,
CoverageReadsRoundedAlpha,
UnmeasuredFetchBlend,
+2 -2
View File
@@ -61,7 +61,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 = 2238;
pub const SEMANTICS_VERSION: u32 = 2239;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -71,7 +71,7 @@ pub const SEMANTICS_VERSION: u32 = 2238;
/// 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 = 576;
pub const ARTIFACT_FORMAT_VERSION: u32 = 577;
/// 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
+1 -29
View File
@@ -740,28 +740,6 @@ fn the_version_267_members_round_trip() {
assert_eq!(decode::<RuntimeFact>(&encode(&fact)), Ok(fact));
}
/// The member format version 326 appends encodes and decodes as itself: whether a texture slot's
/// bound format has no family Metal's `half` conversion is measured for on a device sampling
/// through Metal's own texture unit.
#[test]
fn the_version_326_member_round_trips() {
use crate::pipeline::sym::SpecKey;
let key = SpecKey::UnmeasuredTexels(SlotRef {
stage: Stage::Fragment,
class: SlotClass::Texture,
index: 7,
});
assert_eq!(decode::<SpecKey>(&encode(&key)), Ok(key));
assert_ne!(
encode(&key),
encode(&SpecKey::ConstantLanes(SlotRef {
stage: Stage::Fragment,
class: SlotClass::Texture,
index: 7,
}))
);
}
/// The member format version 374 appends encodes and decodes as itself: the axes on which a texture
/// slot's bound view's parent's base-level size, which Metal's texel-offset rule reads, is not a
/// power of two where the view's own is.
@@ -838,14 +816,13 @@ fn the_version_535_member_round_trips() {
/// decode together in one render pipeline: `PrecisionNote::CubeGradientFootprint` and
/// `CombinedSampler`, `RuntimeFact::InterlockedFramebufferFetch` and
/// `GraphicsState::storage_attachments`, `SpecKey::TexelFormat`, `RuntimeFact::TexelFormat` and
/// `SrgbTexture`, `VkProperty::MetalSampler`, and `PrecisionNote::HalfTexelConversion`,
/// `SrgbTexture`, and `PrecisionNote::HalfTexelConversion`,
/// `HalfSampleFilter`, `SrgbTexelDecode`, and `FloatSampleFilter`,
/// `HandleClass::Sampler { compare, integer }` and
/// `SyntheticBinding::SamplerTable`, and `RuntimeFact::UlongAtomicView`, each beside the others
/// rather than only on its own side's fixtures.
#[test]
fn the_merged_members_round_trip_in_one_render_pipeline() {
use crate::device::requirements::VkProperty;
use crate::pipeline::artifact::{PrecisionNote, RuntimeDependency, SpecConstant};
use crate::pipeline::facts::{Mechanism, RuntimeFact};
use crate::pipeline::graphics::StorageAttachmentUse;
@@ -891,7 +868,6 @@ fn the_merged_members_round_trip_in_one_render_pipeline() {
default: 0,
unread_bits: 0,
});
p.requirements.properties.insert(VkProperty::MetalSampler);
let set = p.layout.sets.len() as u32;
p.layout.sets.push(DescriptorSetLayout {
set,
@@ -1011,10 +987,6 @@ fn the_merged_members_round_trip_in_one_render_pipeline() {
.constants
.iter()
.any(|c| c.key == SpecKey::TexelFormat(texture)));
assert!(sealed
.requirements
.properties
.contains(&VkProperty::MetalSampler));
let bindings = sealed.layout.sets.last().map(|s| &s.bindings[..]);
assert!(matches!(
bindings.map(|b| &b[0].source),
+3 -7
View File
@@ -15,9 +15,9 @@ use crate::device::function_storage;
use crate::device::metal::MetalDeviceProperties;
use crate::device::policy::DevicePolicy;
use crate::device::profile::{
BufferAccess, CubeGradientRoute, CubeGradients, DescriptorCaps, DeviceProfile, EnabledCaps,
FormatTable, FragmentCaps, FunctionStorage, HandleDomain, ImageCaps, Independence, LeafCaps,
PointerDomain, ProfileFields, Robustness,
BufferAccess, DescriptorCaps, DeviceProfile, EnabledCaps, FormatTable, FragmentCaps,
FunctionStorage, HandleDomain, ImageCaps, Independence, LeafCaps, PointerDomain, ProfileFields,
Robustness,
};
use crate::device::requirements::{
ApiVersion, FloatControl, FloatWidth, FormatUsage, ResolveMode, SubgroupOp, VkExtension,
@@ -336,10 +336,6 @@ fn derive_fields(desc: &DeviceDescription, policy: &DevicePolicy) -> ProfileFiel
// The floor: no Vulkan query states how much a thread holds.
function_storage: FunctionStorage::Assumed(function_storage::FLOOR),
// Vulkan's rule, the device's own reading of the gradients handed to it.
cube_gradients: CubeGradients {
graphics: CubeGradientRoute::Vulkan,
compute: CubeGradientRoute::Vulkan,
},
}
}
-64
View File
@@ -216,19 +216,10 @@ impl DeviceProfile {
pub fn takes_driver_deviation(&self, deviation: DriverDeviation) -> bool {
let f = &self.fields;
match deviation {
DriverDeviation::CubeGradientRoute => {
f.cube_gradients.compute == CubeGradientRoute::Metal
}
DriverDeviation::GraphicsCubeGradientTangents => {
f.cube_gradients.graphics == CubeGradientRoute::AppleProjected
}
DriverDeviation::SimdgroupLockstep => f
.enabled
.properties
.contains(&VkProperty::SimdgroupLockstep),
DriverDeviation::MetalSampler => {
f.enabled.properties.contains(&VkProperty::MetalSampler)
}
DriverDeviation::MetalCenterVaryings => f
.enabled
.properties
@@ -462,61 +453,6 @@ pub struct ProfileFields {
/// (`VkLimit::FunctionStorageBytesPerThread`), and a vertex or fragment function on a device
/// not measured more ([`FunctionStorage::Assumed`]).
pub function_storage: FunctionStorage,
/// How the driver hands a cube sample's explicit gradients to the GPU, in a graphics and in
/// a compute pipeline: Vulkan's cube derivative rule unless the driver is measured with
/// another (`DriverDeviation::CubeGradientRoute` and `GraphicsCubeGradientTangents`).
pub cube_gradients: CubeGradients,
}
/// 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, the device's own reading,
/// on every driver.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct CubeGradients {
/// A vertex or fragment function's.
pub graphics: CubeGradientRoute,
/// A kernel's.
pub compute: CubeGradientRoute,
}
/// The route of a cube sample's explicit gradients to the GPU ([`CubeGradients`]). Metal's
/// footprint is the one the Apple M3 Max reads under macOS 27 (`lower::sampler::CubeFootprint`):
/// each gradient's two tangent components on the face, its normal component dropped.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CubeGradientRoute {
/// Vulkan's rule ("Cube Map Derivative Transformation") reads the footprint from them: the
/// 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`). 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
/// `gradientcube`, whose macOS 27 reading takes the face's two tangents of what it is handed: an `x` or `z` face's gradient without its normal component reaches Metal as its
/// own, exactly; on a `y` face the fixup writes the face's `x` tangent on both, so the function
/// hands Metal's length there, which keeps an isotropic sample's footprint and lays an
/// anisotropic one's ellipse on the diagonal (`lower::sampler::CubeFootprint::Projected`,
/// `PrecisionNote::CubeGradientFootprint`).
AppleProjected,
/// 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,
}
impl CubeGradients {
/// The route of a function of `stage`: a kernel's is the compute pipeline's.
pub fn route(self, stage: crate::pipeline::sym::Stage) -> CubeGradientRoute {
match stage {
crate::pipeline::sym::Stage::Kernel => self.compute,
_ => self.graphics,
}
}
}
/// The Function storage a thread holds correctly ([`DeviceProfile::function_storage`]), in bytes:
+2 -13
View File
@@ -600,15 +600,6 @@ pub enum VkProperty {
/// No Vulkan query reports it. A kernel whose threadgroup accesses only that lockstep orders,
/// at a place no subgroup barrier may stand, requires it rather than emulated simdgroups.
SimdgroupLockstep,
/// The device samples, filters, and converts texels through Metal's own sampler on Apple's
/// GPU (the driver's measured deviation
/// [`DriverDeviation::MetalSampler`](crate::error::DriverDeviation::MetalSampler)), so a
/// sample's footprint, weights, rounding, and sRGB decode are Metal's. No Vulkan query reports
/// it. A module that leaves a sample, gather or comparison to the device's sampler, or an
/// 8-bit sRGB texel to the device's decode, requires it on such a device, as a module on
/// another requires [`VkProperty::DeviceSampling`] and records
/// `PrecisionNote::DeviceSampling` (and `PrecisionNote::SrgbTexelDecode` for the decode).
MetalSampler,
/// `storageImageSampleCounts` has this sample count: a multisampled shadow of the stencil.
StorageImageSampleCount(u32),
/// `supportedDepthResolveModes` (`VkPhysicalDeviceDepthStencilResolveProperties`, Vulkan 1.2)
@@ -693,10 +684,8 @@ pub enum VkProperty {
/// format requires it; without it, the module records `PrecisionNote::DeviceColorConversion`.
MetalNormStorageWrites,
/// Native device sampling: the module hands its samples, gathers and comparisons to the
/// device's own sampler as a device that samples through Metal's
/// ([`VkProperty::MetalSampler`]) would, on a device that does not. No Vulkan query reports
/// it: the profile takes it wherever it lacks `VkProperty::MetalSampler`. A module that
/// leaves a sample to the device's sampler there requires it and records
/// device's own sampler. No Vulkan query reports it: every profile takes it. A module that
/// leaves a sample to the device's sampler requires it and records
/// [`PrecisionNote::DeviceSampling`](crate::pipeline::PrecisionNote::DeviceSampling).
DeviceSampling,
/// The device stores every unbiased depth a draw writes to a `Depth16Unorm` attachment as
-23
View File
@@ -490,33 +490,10 @@ pub enum Needs {
#[non_exhaustive]
#[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::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
/// that needs that order takes emulated simdgroups, exact.
SimdgroupLockstep,
/// 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, 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`. 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
/// SPIRV-Cross's `spvGradientCube`, whose result Metal reads by its macOS 27 rule, the face's
/// two tangents: an `x` or `z` face's gradient reaches it as Metal's own, a `y` face's `z`
/// tangent is lost. Unmeasured, as [`DriverDeviation::CubeGradientRoute`].
GraphicsCubeGradientTangents,
/// The device reads a center-sampled varying (a smooth input decorated neither `Centroid`
/// nor `Sample`) of a multisampled pipeline at the pixel center in every fragment
/// invocation, a sample-rate one's included, as Metal reads it
+3 -6
View File
@@ -802,12 +802,9 @@ pub struct AccessPlan {
/// the ids as this states, and the heap's function-table array, or, on a device without the
/// array's features, the stage's function-table snapshot, one more again.
pub function_tables: Option<function_table::TableReads>,
/// A heap texture's access reads its texel class: the handle-table search carries the class's index
/// (`memory::handles::Lookup::Flagged`), so every heap handle carries it beside its element.
pub heap_class: bool,
/// A heap texture's float write the function makes tests its texel class's index
/// (`lower::texture::emit`): the handle-table search carries the index, as under
/// [`heap_class`](Self::heap_class), but the module needs no table of the classes.
/// (`lower::texture::emit`): the handle-table search carries the index
/// (`memory::handles::Lookup::Flagged`), so every heap handle carries it beside its element.
pub heap_class_index: bool,
/// A heap storage access the function makes converts a member by its texel class and its
/// red-blue order (`lower::texture::heap_storage_conversions`): the handle-table search
@@ -836,7 +833,7 @@ pub struct AccessPlan {
impl AccessPlan {
/// Whether the handle-table search carries each heap handle's texel class index.
pub fn carries_class(&self) -> bool {
self.heap_class || self.heap_class_index
self.heap_class_index
}
/// What the function's handle-table search yields.
@@ -436,15 +436,6 @@ fn is_nan(f: Form, b: u64) -> bool {
}
}
/// Whether `f32` bits `got` are the device's quantize's answer for the `half` value `want` (`f32`
/// bits) below the smallest normal half: its signed zero. SPIR-V lets `OpQuantizeToF16` answer a
/// zero there, and the interpreter's does (as NIR's `fquantize2f16`), so a module rounding by
/// [`QuantizeForm::Device`] may answer it (`PrecisionNote::NativeHalfQuantize`).
fn quantize_flush_of(got: u64, want: u64) -> bool {
let w = f32::from_bits(want as u32);
w != 0.0 && w.abs() < 2f32.powi(-14) && got == want & 0x8000_0000
}
fn is_zero(f: Form, b: u64) -> bool {
f.is_float() && (b << 1) & mask(f.bits()) == 0
}
@@ -4100,7 +4091,6 @@ mod convert_suffix;
mod divide;
mod fast;
mod fused;
mod half_texel;
mod libm;
mod narrow;
mod pack;
@@ -1,520 +0,0 @@
//! Interpreter differential tests of the conversion of a texel to a `half` result on a device that
//! samples through Metal's own texture unit (`lower::texture::half`): every texel to nearest even
//! by the module's rounding (the device's native conversion), but a YCbCr field's one texel on the
//! grid `8192`, with ties away from zero. References are plain Rust. Each runs in every
//! [`QuantizeForm`]; the device's quantize ([`QuantizeForm::Device`]) may answer a `half` denormal
//! as its signed zero ([`quantize_flush_of`]). The exact tests below bound where the device's
//! nearest-even `half` of Metal's `float` texel is Metal's `half` (the conditions of
//! `PrecisionNote::HalfTexelConversion`, `texture::half_texels`).
use super::texel_round::half_of;
use super::*;
use crate::lower::arith::texel_round::HalfRounding;
use crate::lower::texture::half::{self, TexelLanes};
use crate::metal::texel_format::{texel_format, PackedTexels};
use crate::metal::PixelFormat as P;
use crate::spirv::builder::QuantizeForm;
/// The module roundings the routine is built under.
const FORMS: [QuantizeForm; 3] = [
QuantizeForm::Device,
QuantizeForm::Converted,
QuantizeForm::Controlled,
];
fn v4() -> Form {
vec(float(32), 4)
}
/// The routine at class `class` (an input) and `lanes`, in a module rounding to `half` by `q`.
fn body_lanes(
lanes: TexelLanes,
q: QuantizeForm,
) -> impl Fn(&mut FunctionBuilder<'_>, &[Value]) -> BResult<Value> {
move |fb, x| {
fb.module().set_quantize_form(q);
let r = half::define(fb.module())?;
let lanes = lanes.value(fb)?;
half::convert(fb, r, x[0], x[1], lanes)
}
}
/// Every lanes argument: one texel's, each gathered channel's, and a value that may be filtered.
fn every_lanes() -> Vec<TexelLanes> {
let mut out = vec![TexelLanes::Texel, TexelLanes::Filtered];
out.extend((0..4).map(TexelLanes::Gathered));
out
}
/// Run the routine over `texels` at `class` and `lanes`, against `reference` of each lane's value,
/// in every [`QuantizeForm`] (a `half` denormal the device's quantize's zero or itself in
/// [`QuantizeForm::Device`]).
fn run_lanes(
what: &str,
class: u32,
lanes: TexelLanes,
texels: &[[u64; 4]],
reference: &dyn Fn(u64) -> u64,
) {
let cases: Vec<Case> = texels
.iter()
.map(|t| vec![t.to_vec(), vec![u64::from(class)]])
.collect();
for q in FORMS {
check_accept(
&format!("{what} {lanes:?} {q:?}"),
&[v4(), int(32)],
v4(),
&body_lanes(lanes, q),
&cases,
&|c| Some(c[0].iter().map(|x| reference(*x)).collect()),
&|g, w| texel_answers(q, g, w),
);
}
}
/// Whether `f32` bits `got` answer the `half` value `want` in a module rounding by `q`: exactly, a
/// NaN for a NaN, or, by the device's quantize, a denormal's signed zero.
fn texel_answers(q: QuantizeForm, got: u64, want: u64) -> bool {
got == want
|| (is_nan(v4(), got) && is_nan(v4(), want))
|| (q == QuantizeForm::Device && quantize_flush_of(got, want))
}
/// `x` in groups of four lanes, the last padded with zeros.
fn quads(x: &[u64]) -> Vec<[u64; 4]> {
x.chunks(4)
.map(|c| {
let mut q = [0u64; 4];
q[..c.len()].copy_from_slice(c);
q
})
.collect()
}
/// The treatment bits of `pf`.
fn bits(pf: P) -> u32 {
texel_format(pf).0
}
/// `f32` bits of `x`'s `half` by `mode`, a NaN kept.
fn rounded(mode: HalfRounding) -> impl Fn(u64) -> u64 {
move |x| {
let f = f32::from_bits(x as u32);
if f.is_nan() {
x
} else {
u64::from(half_of(f, mode))
}
}
}
/// Every half below `2^-13` (the denormals and the least normal binade), random `f32` patterns of
/// every magnitude, and the rounding edges: the tie below the least denormal, the overflow, the
/// infinities, an `f32` denormal, and `-0`.
fn float_texels() -> Vec<u64> {
let mut rng = Rng(0x00b1_f0b1_f5ee_d001);
let mut out: Vec<u64> = (0u32..0x800)
.map(|h| u64::from((f16_to_f64(h as u16) as f32).to_bits()))
.collect();
out.extend((0..4000).map(|_| rng.next() & 0xFFFF_FFFF));
out.extend([
0x3300_0000u64, // 2^-25: the tie below the smallest half denormal
0x477F_E000, // 65504
0x477F_F000, // 65520: the tie past the largest half
0x4780_0000,
0x7F80_0000,
0xFF80_0000,
0x0000_0001,
0x8000_0000,
]);
out
}
/// A 32-bit and a 16-bit float texel convert to nearest even in every access, a read's, a
/// gather's and a sample's alike: past `65504` to the infinity, half denormals kept (but by the
/// device's quantize). Metal rounds a 32-bit float texel's sample toward zero, saturating at
/// `±65504`, and a 16-bit float's linear sum with ties away from zero; the device's nearest even is
/// the answer, noted (`PrecisionNote::HalfTexelConversion`). With every tie of `texel_round`'s
/// probes (each half denormal's, every 13th normal half's, the top binade's).
#[test]
fn a_float_texel_rounds_to_nearest_even_in_every_access() {
let mut texels = float_texels();
texels.extend(super::texel_round::half_probe_bits());
let texels = quads(&texels);
for pf in [P::RGBA32Float, P::R32Float, P::RGBA16Float] {
for lanes in every_lanes() {
run_lanes(
&format!("{pf:?}"),
bits(pf),
lanes,
&texels,
&rounded(HalfRounding::NearestEven),
);
}
}
}
/// A two-plane YCbCr format's one texel and a 2D gather's lanes: its step of `1/8192` (or of
/// `1/2048`, a `half` already) rounds to `half` with ties away from zero, as Metal's read and
/// nearest sample of `YCBCR8_420_2P_sRGB`, `YCBCR10_420_2P_sRGB` and three 12-bit and
/// extended-range formats did (every channel), and its gathers, and every step of each grid: the
/// extended-range steps signed within `[-2, 2]`. A value that may be filtered keeps nearest even (a
/// filtered value is the device's).
#[test]
fn a_ycbcr_texel_rounds_its_step_with_ties_away() {
for (pf, d, lo, hi) in [
(P::YCBCR84202P, 2048, 0, 2048),
(P::YCBCR84202PSRGB, 8192, 0, 8192),
(P::YCBCR124202P, 8192, 0, 8192),
(P::YCBCR104202PXR, 8192, -16384, 16384),
] {
assert!(
PackedTexels::of(pf).is_some_and(PackedTexels::ycbcr),
"{pf:?}"
);
let values: Vec<u64> = (lo..=hi)
.map(|k: i32| u64::from((k as f32 / d as f32).to_bits()))
.collect();
let texels = quads(&values);
for lanes in every_lanes() {
let mode = if lanes == TexelLanes::Filtered {
HalfRounding::NearestEven
} else {
HalfRounding::NearestAway
};
run_lanes(&format!("{pf:?}"), bits(pf), lanes, &texels, &rounded(mode));
}
// A step of `1/8192` halfway between two halves rounds away from zero: `4098 / 8192`
// (between the halves `4096 / 8192` and `4100 / 8192`) to `4100 / 8192`.
if d == 8192 {
let away = half_of(4098.0 / 8192.0, HalfRounding::NearestAway);
assert_eq!(f32::from_bits(away) * 8192.0, 4100.0);
}
}
}
/// [`half::ROUTINE_WORDS`] bounds the routine's emission, and [`half::CALL_WORDS`] a call's.
#[test]
fn the_half_texel_routine_words_bound_its_emission() {
use crate::spirv::serialize::serialize;
let ins = [v4(), int(32)];
let size = |body: Body<'_>| -> usize {
let m = kernel(&ins, v4(), body).expect("build");
serialize(m).expect("serialize").words.len()
};
for q in FORMS {
let without = size(&|fb, x| {
fb.module().set_quantize_form(q);
Ok(x[0])
});
let defined = size(&|fb, x| {
fb.module().set_quantize_form(q);
half::define(fb.module())?;
Ok(x[0])
}) - without;
let called = size(&body_lanes(TexelLanes::Filtered, q)) - without - defined;
assert!(
defined as u64 <= half::ROUTINE_WORDS,
"{q:?}: the routine is {defined} words, bound {}",
half::ROUTINE_WORDS
);
assert!(
called <= half::CALL_WORDS as usize,
"{q:?}: a call is {called} words, bound {}",
half::CALL_WORDS
);
eprintln!("half texel routine {q:?}: {defined} words, a call {called}");
}
}
/// On a device that samples through Metal's own texture unit, an 8-bit sRGB format's `f32` texel is
/// Metal's `float` value, a step `n / D` rounded to nearest even on the grids `1/4095` (a color
/// channel's table step, or a linear sum rounded onto it), `1/4080` (alpha's linear sum), and
/// `1/255` (alpha's code), and its rounding to `half` to nearest even is the step's own rounding to
/// `half`, Metal's `half` value: that class's conversion is Metal's there, unnoted
/// (`texture::half_texels`). Exact: integer arithmetic on the step and on the `f32` value.
#[test]
fn metals_srgb_float_steps_round_to_their_half_steps() {
for d in [4095u32, 4080, 255] {
let misses = steps_rounding_twice(d);
assert!(misses.is_empty(), "the steps n / {d} at n in {misses:?}");
}
}
/// `p / q` (in `[0, 1]`) rounded to `half` to nearest even: the value `k · 2^x` as `(k, x)` with
/// `k` odd (or zero), so that equal values are equal pairs.
fn half_of_ratio(p: u128, q: u128) -> (u128, i32) {
if p == 0 {
return (0, 0);
}
// The exponent `e` of `p / q` (`2^e <= p / q < 2^(e + 1)`), at least half's least normal
// one, -14.
let mut e = 0i32;
while e > -14 && (p << e.unsigned_abs()) < q {
e -= 1;
}
// `p / q` in units of `2^(e - 10)`, rounded to nearest even.
let scaled = p << (10 - e).unsigned_abs();
let (mut k, r) = (scaled / q, scaled % q);
if 2 * r > q || (2 * r == q && k % 2 == 1) {
k += 1;
}
let mut x = e - 10;
while k % 2 == 0 {
k /= 2;
x += 1;
}
(k, x)
}
/// The `f32` value `n / d` rounded to nearest even (IEEE division of two exact operands), as the
/// ratio of its significand to a power of two.
fn f32_step(n: u32, d: u32) -> (u128, u128) {
let bits = (n as f32 / d as f32).to_bits();
if bits == 0 {
return (0, 1);
}
let significand = u128::from(bits & 0x7f_ffff | 0x80_0000);
let exponent = ((bits >> 23) & 0xff) as i32 - 150;
assert!(exponent < 0, "{n} / {d}");
(significand, 1u128 << exponent.unsigned_abs())
}
/// The steps `n` of grid `1/d` (`0 <= n <= d`) whose `f32` value rounds to another `half` than
/// the step itself: exact, by integer arithmetic on the step and on the `f32` value.
fn steps_rounding_twice(d: u32) -> Vec<u32> {
(0..=d)
.filter(|&n| {
let (p, q) = f32_step(n, d);
half_of_ratio(u128::from(n), u128::from(d)) != half_of_ratio(p, q)
})
.collect()
}
/// Metal's `float` texel of every grid but the 16-bit normalized ones is a step `n / D` rounded to
/// `f32` to nearest even, and that value's rounding to `half` is the step's own, Metal's `half`,
/// for every step: the 8-bit normalized codes (`1/255`, `1/127`) and filter grids (`1/4080`,
/// `1/2032`), every packed code scale and filter grid, the sRGB table's `1/4095`, and the YCbCr
/// grids `1/2048` and `1/8192`. So on a device that samples through Metal's own texture unit the
/// device's nearest even `half` of the texel is Metal's for those classes, unnoted. The 16-bit
/// grids are not: `65455 / 65535`, `65519 / 65535` and `32759 / 32767` round twice, one unit in
/// the last place of the `half` from Metal's (`PrecisionNote::HalfTexelConversion` on a 16-bit
/// normalized slot). A signed step's value is the negation of its magnitude's, so the magnitudes
/// cover both signs. Exact: integer arithmetic on the step and on the `f32` value.
#[test]
fn metal_float_steps_round_to_their_half() {
let mut grids = vec![255u32, 127, 4080, 2032, 4095, 2048, 8192];
for p in PackedTexels::ALL {
grids.extend(p.scales().into_iter().flatten());
grids.extend(p.filter_grids().into_iter().flatten());
}
grids.sort_unstable();
grids.dedup();
for d in grids {
let misses = steps_rounding_twice(d);
assert!(misses.is_empty(), "the steps n / {d} at n in {misses:?}");
}
assert_eq!(steps_rounding_twice(65535), vec![65455, 65519]);
assert_eq!(steps_rounding_twice(32767), vec![32759]);
}
/// The YCbCr field's ties away come from the nearest-even `half` and the texel, selected after the
/// rounding of the texel itself, so every rounding the routine leaves to the device (the
/// `Converted` form's `OpFConvert` to `half` and the `Device` form's `OpQuantizeToF16`) reads the
/// routine's texel parameter directly: where a device specializes a class without the field, the
/// selection drops it whole, and no `[[clang::optnone]]` call is left at the access on MoltenVK.
#[test]
fn the_device_rounding_reads_the_texel_alone() {
use crate::spirv::serialize::serialize;
use std::collections::BTreeSet;
// SPIR-V opcodes.
const OP_TYPE_FLOAT: u32 = 22;
const OP_TYPE_VECTOR: u32 = 23;
const OP_FUNCTION: u32 = 54;
const OP_FUNCTION_PARAMETER: u32 = 55;
const OP_FUNCTION_END: u32 = 56;
const OP_FCONVERT: u32 = 115;
const OP_QUANTIZE_TO_F16: u32 = 116;
for q in [QuantizeForm::Device, QuantizeForm::Converted] {
let m = kernel(&[v4(), int(32)], v4(), &|fb, x| {
fb.module().set_quantize_form(q);
half::define(fb.module())?;
Ok(x[0])
})
.expect("build");
let words = serialize(m).expect("serialize").words;
let mut insts = Vec::new();
let mut i = 5;
while i < words.len() {
let n = ((words[i] >> 16) as usize).max(1);
insts.push(&words[i..(i + n).min(words.len())]);
i += n;
}
// The `half` scalar and vector types, the results of a conversion to `half`.
let mut halves = BTreeSet::new();
for w in &insts {
match w[0] & 0xFFFF {
OP_TYPE_FLOAT if w.get(2) == Some(&16) => {
halves.insert(w[1]);
}
OP_TYPE_VECTOR if halves.contains(&w[2]) => {
halves.insert(w[1]);
}
_ => {}
}
}
// The routine is the module's function whose first parameter is a `vec4` and that has
// three parameters; its texel is that first parameter.
let mut texel = None;
let mut params = Vec::new();
let mut roundings = Vec::new();
let mut body = Vec::new();
for w in &insts {
match w[0] & 0xFFFF {
OP_FUNCTION => {
params.clear();
body.clear();
}
OP_FUNCTION_PARAMETER => params.push(w[2]),
OP_FUNCTION_END => {
if params.len() == 3 {
texel = Some(params[0]);
roundings = body.clone();
}
}
OP_FCONVERT if halves.contains(&w[1]) => body.push((w[2], w[3])),
OP_QUANTIZE_TO_F16 => body.push((w[2], w[3])),
_ => {}
}
}
let texel = texel.expect("the routine");
assert!(!roundings.is_empty(), "{q:?}: the routine rounds the texel");
for (result, operand) in roundings {
assert_eq!(
operand, texel,
"{q:?}: the device's rounding %{result} reads %{operand}, not the texel"
);
}
}
}
/// The plain arm (`narrow::round_texel`, `SpecKey::PlainHalfTexels`) answers as the routine does
/// for every class that takes it: for each pixel format whose class `plain_on_metal_sampler` holds,
/// the routine at that class, one texel's lanes, a filtered value's and gathered channels', is the
/// texel rounded to nearest even with its NaN kept (a denormal the device's quantize's zero or
/// itself), as is the plain arm itself, in each form a device sampling through Metal's own texture
/// unit rounds in.
#[test]
fn the_plain_arm_is_the_metal_sampler_routine_for_its_classes() {
let mut texels: Vec<u64> = vec![
0,
0x8000_0000,
1,
0x8000_0001,
0x0080_0000,
0x3380_0000,
0x3380_0001,
0x387F_E000,
0x387F_F000,
0x3880_0000,
0x3F80_0000,
0xBF80_0000,
0x477F_E000,
0x477F_EFFF,
0x477F_F000,
0x4780_0000,
0x7F7F_FFFF,
0x7F80_0000,
0xFF80_0000,
0x7FC0_0000,
0x7F80_0001,
0xFFC0_2000,
];
// Every 8-bit code's value, and a spread of bit patterns.
texels.extend((0..=255u32).map(|c| u64::from((c as f32 / 255.0).to_bits())));
let mut s = 0x9E37_79B9_u32;
for _ in 0..256 {
s ^= s << 13;
s ^= s >> 17;
s ^= s << 5;
texels.push(u64::from(s));
}
let quads = quads(&texels);
let rte = |x: u64| -> u64 {
let f = f32::from_bits(x as u32);
if f.is_nan() {
x
} else {
u64::from((f16_to_f64(f64_to_f16(f64::from(f))) as f32).to_bits())
}
};
let roundings = [
QuantizeForm::Device,
QuantizeForm::Converted,
QuantizeForm::Controlled,
];
let mut plain_classes = std::collections::BTreeSet::new();
for &pf in P::ALL {
let class = texel_format(pf);
if !class.plain_on_metal_sampler() || !plain_classes.insert(class.0) {
continue;
}
let cases: Vec<Case> = quads
.iter()
.map(|t| vec![t.to_vec(), vec![u64::from(class.0)]])
.collect();
for q in roundings {
for lanes in every_lanes() {
check_accept(
&format!("{pf:?} {lanes:?} {q:?}"),
&[v4(), int(32)],
v4(),
&body_lanes(lanes, q),
&cases,
&|c| Some(c[0].iter().map(|x| rte(*x)).collect()),
&|g, w| texel_answers(q, g, w),
);
}
}
}
assert!(
plain_classes.len() > 10,
"{} plain classes",
plain_classes.len()
);
let cases: Vec<Case> = quads.iter().map(|t| vec![t.to_vec()]).collect();
for q in roundings {
check_accept(
&format!("the plain arm {q:?}"),
&[v4()],
v4(),
&move |fb: &mut FunctionBuilder<'_>, x: &[Value]| {
fb.module().set_quantize_form(q);
let half4 = Form {
held: Held::Float(FloatFmt::Half),
lanes: 4,
};
crate::lower::arith::narrow::round_texel(fb, half4, x[0])
},
&cases,
&|c| Some(c[0].iter().map(|x| rte(*x)).collect()),
&|g, w| texel_answers(q, g, w),
);
}
// The predicate leaves out a YCbCr field on the grid 8192 alone.
for (pf, plain) in [
(P::YCBCR84202PSRGB, false),
(P::YCBCR124202P, false),
(P::RGBA32Float, true),
(P::R32Float, true),
(P::RGBA16Unorm, true),
(P::RG16Snorm, true),
(P::RGBA8Unorm, true),
(P::BGRA8Unorm, true),
(P::RGBA16Float, true),
(P::RGB10A2Unorm, true),
] {
assert_eq!(texel_format(pf).plain_on_metal_sampler(), plain, "{pf:?}");
}
}
@@ -111,93 +111,6 @@ fn f32_to_half_rounds_exactly_in_every_mode() {
}
}
/// Every half magnitude's neighbourhood that decides a directed rounding, both signs: the half
/// itself, its tie with the next half, and one `f32` ulp on either side of the tie (one below a
/// half is one above the tie before it), for every finite half; with the `f32` denormals, the
/// overflow edge, and the specials of [`half_probe_bits`].
fn every_tie_bits() -> Vec<u64> {
let mut out: Vec<u32> = Vec::new();
for h in 0u16..0x7C00 {
let v = f16_to_f64(h) as f32;
let next = f16_to_f64(h + 1);
let tie = ((f64::from(v) + next) / 2.0) as f32;
let t = tie.to_bits();
out.extend([v.to_bits(), t - 1, t, t + 1]);
}
let negated: Vec<u32> = out.iter().map(|b| b | 0x8000_0000).collect();
out.extend(negated);
let mut out: Vec<u64> = out.into_iter().map(u64::from).collect();
out.extend(
half_probe_bits()
.into_iter()
.filter(|b| *b as u32 & 0x7FFF_FFFF >= 0x477F_E000),
);
out.extend([0x0000_0001, 0x8000_0001, 0x007F_FFFF, 0x807F_FFFF]);
out
}
/// `f32_to_half_from_even` rounds every half's tie and its neighbours, and every half, toward
/// zero saturating and with ties away exactly, from the module's own rounding to nearest even
/// (`narrow::round_texel`) in every [`QuantizeForm`] (from the device's quantize, a half denormal
/// may be its signed zero): four lanes at a time, as the texel routine calls it.
#[test]
fn f32_to_half_from_even_is_exact_on_every_tie() {
use crate::lower::arith::narrow;
use crate::spirv::builder::QuantizeForm;
let v = vec(float(32), 4);
let h = vec(float(16), 4);
let b = Form {
held: Held::Bool,
lanes: 1,
};
let quads: Vec<Vec<u64>> = every_tie_bits()
.chunks(4)
.map(|c| {
let mut q = c.to_vec();
q.resize(4, 0);
q
})
.collect();
for q in [
QuantizeForm::Device,
QuantizeForm::Converted,
QuantizeForm::Controlled,
] {
for (tz, mode) in [
(true, HalfRounding::TowardZeroSaturating),
(false, HalfRounding::NearestAway),
] {
let cases: Vec<Case> = quads
.iter()
.map(|x| vec![x.clone(), vec![u64::from(tz)]])
.collect();
check_accept(
&format!("f32_to_half_from_even {mode:?} {q:?}"),
&[v, b],
v,
&|fb, x| {
fb.module().set_quantize_form(q);
let even = narrow::round_texel(fb, h, x[0])?;
texel_round::f32_to_half_from_even(fb, v, (x[0], even), x[1])
},
&cases,
&|c| {
Some(
c[0].iter()
.map(|x| u64::from(half_of(f32::from_bits(*x as u32), mode)))
.collect(),
)
},
&|g, w| {
g == w
|| (is_nan(v, g) && is_nan(v, w))
|| (q == QuantizeForm::Device && quantize_flush_of(g, w))
},
);
}
}
}
/// 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: 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
@@ -11,8 +11,6 @@
//! on a format's grid is (the 8- and 16-bit normalized formats' bicubic sums). [`ratio_to_half`]
//! rounds once: rounding the `f32` quotient to `half` instead differs from it at `±65455 /
//! 65535`, `±65519 / 65535`, and `±32759 / 32767`.
//! - [`f32_to_half_from_even`]: toward zero saturating or ties away, derived from an exact
//! rounding to nearest even.
//! - [`grid_value`]: a signed step's value `n / D` on a normalized format's grid exactly, the
//! bicubic sums'.
//!
@@ -100,84 +98,6 @@ pub fn f32_to_half(
to_half(fb, f, x, mode)
}
/// `x` (`f32` lanes of form `f`) rounded to `half` toward zero, saturating at `±65504`, where
/// `toward_zero` (a `bool` scalar), else to nearest with ties away from zero, both derived from
/// `even`, `x` rounded to nearest even. `even` must be exact: the nearest-even `half` of every
/// finite `x` (either sign of a zero), an infinity's infinity, and a NaN `x` itself, as
/// [`round_texel`](crate::lower::arith::narrow::round_texel) gives where the device's rounding is
/// measured to be Metal's. The result is exact by construction:
///
/// - Each directed result is `even` or `o`, `even`'s neighbour on `x`'s side (its predecessor in
/// magnitude where `|even| > |x|`, else its successor). Toward zero takes `o` where `even` lies
/// past `x`, saturated at `65504` (a finite overflow's infinity steps back to the largest
/// `half`); ties away take the larger of `even` and `o` where `x` is their midpoint.
/// - Above the least normal `half` `2^-14`, `o` and the midpoint are `even`'s `f32` bits
/// `± 0x2000` and `± 0x1000`: a carry or borrow through the exponent lands on the next binade's
/// `half`, or its midpoint, exactly. At or below it they are `|even| ± 2^-24` and `± 2^-25` by
/// one `f32` addition each, whose operands and result lie on the `2^-25` grid below `2^-13`, so
/// exact in every rounding mode, and normal `f32`s or zero, so no mode flushes them. No
/// multiplication feeds them, so nothing contracts.
/// - Every test is on integer bits and the sign of `x` is set last, so no float mode changes the
/// answer: an infinity or a NaN is `even`, which is `x`.
///
/// About thirty instructions.
pub fn f32_to_half_from_even(
fb: &mut FunctionBuilder<'_>,
f: Form,
(x, even): (Value, Value),
toward_zero: Value,
) -> BResult<Value> {
let u = words(f);
let ut = ty(fb, u)?;
let ft = ty(fb, floats(f))?;
let c = |fb: &mut FunctionBuilder<'_>, v: u64| splat(fb, u, v);
let fc = |fb: &mut FunctionBuilder<'_>, v: f32| splat(fb, floats(f), u64::from(v.to_bits()));
let abs = c(fb, 0x7FFF_FFFF)?;
let b = fb.convert(ConvOp::Bitcast, x, ut)?;
let mag = bin(fb, BinOp::BitwiseAnd, b, abs)?;
let sign_bit = c(fb, 0x8000_0000)?;
let sign = bin(fb, BinOp::BitwiseAnd, b, sign_bit)?;
let e = fb.convert(ConvOp::Bitcast, even, ut)?;
let e = bin(fb, BinOp::BitwiseAnd, e, abs)?;
// `even` past `x`: its neighbour toward zero, else away from it.
let past = bin(fb, BinOp::UGreaterThan, e, mag)?;
// Normal halves: on the bits.
let (down, up) = (c(fb, 0xFFFF_E000)?, c(fb, 0x2000)?);
let step = fb.select(past, down, up)?;
let o_normal = bin(fb, BinOp::IAdd, e, step)?;
let (half_down, half_up) = (c(fb, 0xFFFF_F000)?, c(fb, 0x1000)?);
let half_step = fb.select(past, half_down, half_up)?;
let mid_normal = bin(fb, BinOp::IAdd, e, half_step)?;
// Half denormals and the least normal half: on the `2^-24` grid, by exact `f32` additions.
let ef = fb.convert(ConvOp::Bitcast, e, ft)?;
let (down, up) = (fc(fb, -(2f32.powi(-24)))?, fc(fb, 2f32.powi(-24))?);
let step = fb.select(past, down, up)?;
let o_low = bin(fb, BinOp::FAdd, ef, step)?;
let o_low = fb.convert(ConvOp::Bitcast, o_low, ut)?;
// `2^-24 - 2^-24` is `+0` in every rounding mode; the mask keeps it so wherever a mode might
// not.
let o_low = bin(fb, BinOp::BitwiseAnd, o_low, abs)?;
let (half_down, half_up) = (fc(fb, -(2f32.powi(-25)))?, fc(fb, 2f32.powi(-25))?);
let half_step = fb.select(past, half_down, half_up)?;
let mid_low = bin(fb, BinOp::FAdd, ef, half_step)?;
let mid_low = fb.convert(ConvOp::Bitcast, mid_low, ut)?;
let least_normal = c(fb, 0x3880_0000)?;
let low = bin(fb, BinOp::ULessThanEqual, e, least_normal)?;
let o = fb.select(low, o_low, o_normal)?;
let mid = fb.select(low, mid_low, mid_normal)?;
// Toward zero: `o` where `even` is past `x`, saturated. Ties away: the larger where `x` is
// the midpoint.
let tie = bin(fb, BinOp::IEqual, mid, mag)?;
let moves = fb.select(toward_zero, past, tie)?;
let max = c(fb, 0x477F_E000)?;
let saturated = fb.glsl(GlslOp::UMin, &[o, max])?;
let larger = fb.glsl(GlslOp::UMax, &[o, e])?;
let moved = fb.select(toward_zero, saturated, larger)?;
let r = fb.select(moves, moved, e)?;
let r = bin(fb, BinOp::BitwiseOr, r, sign)?;
fb.convert(ConvOp::Bitcast, r, ft)
}
/// [`f32_to_half`]: the sequence of its docs.
fn to_half(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, rule: HalfRounding) -> BResult<Value> {
let u = words(f);
@@ -50,13 +50,11 @@
//!
//! **An 8-bit sRGB attachment** (`RGBA8Unorm_sRGB`, `BGRA8Unorm_sRGB` and the rest) reads through
//! its input attachment the device's decode of its bytes, Vulkan's sRGB EOTF within the device's
//! precision, where Metal decodes a color byte to its twelve-bit step over 4095. On a device that
//! decodes through Metal's own texture unit (`VkProperty::MetalSampler`) that is Metal's decode,
//! and the module requires the property; elsewhere the interface records each `float` color it
//! reads so (`StageIo::decoded_fetches`), and a render pipeline whose attachment there has such a
//! format records `PrecisionNote::SrgbTexelDecode` (`color_writes::pipeline_writes`). The
//! interlocked storage form reads the attachment's bytes, no sRGB view of them, and decodes them
//! by Metal's table itself (`fetch`).
//! precision, where Metal decodes a color byte to its twelve-bit step over 4095. The interface
//! records each `float` color it reads so (`StageIo::decoded_fetches`), and a render pipeline whose
//! attachment there has such a format records `PrecisionNote::SrgbTexelDecode`
//! (`color_writes::pipeline_writes`). The interlocked storage form reads the attachment's bytes, no
//! sRGB view of them, and decodes them by Metal's table itself (`fetch`).
//!
//! **An `A8Unorm` attachment whose image holds Metal's alpha in red** (`R8_UNORM` on a device
//! without `A8_UNORM`, `LoweringInputs::alpha_in_red_colors`) reads `(r, 0, 0, 1)` through its
@@ -289,22 +287,10 @@ pub(super) fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<Co
.insert(color, e);
}
// A `float` color the device's input attachment decodes, an 8-bit sRGB format's through its
// sRGB EOTF: Metal's decode on a device that decodes through Metal's own texture unit, which
// the module then requires; elsewhere the interface records the color, whose pipeline notes the
// decode where the attachment is such a format (`color_writes::pipeline_writes`).
// sRGB EOTF: the interface records the color, whose pipeline notes the decode where the
// attachment is such a format (`color_writes::pipeline_writes`).
if form.is_float() && extended.is_none() && !input.alpha_red {
let metal = cx
.profile
.fields()
.enabled
.properties
.contains(&crate::device::requirements::VkProperty::MetalSampler);
match metal {
true => cx.families.sampler.metal_sampler = true,
false => {
cx.families.stage_io.interface.decoded_fetches.insert(color);
}
}
cx.families.stage_io.interface.decoded_fetches.insert(color);
}
// An attachment whose image holds Metal's alpha in red reads the red as Metal's alpha: a float
// (an integer read is Metal's pipeline error). The interface records the attachment, which
@@ -248,34 +248,13 @@ const MINIFIED_ZERO: f32 = 1.0 / 4096.0;
/// nearest.
const MINIFIED_NEAREST: f32 = 0.25;
/// Whether constexpr sampler `words` used as `use_` is one that Metal's own sampler on `profile`
/// (`DriverDeviation::MetalSampler`) filters anisotropically other than as Metal's `NotMipmapped`:
/// handed anisotropy, without a mip filter, its two filters different on the device. Vulkan has no
/// sampler without mipmapping, and no level clamp the device's sampler takes reads Metal's
/// `NotMipmapped` footprint at `maxAnisotropy` 2 to 16 where the filters differ
/// (`metal::sampler::vk_sampler`).
fn own_not_mipmapped(
words: [u64; 2],
use_: SamplerUse,
profile: &crate::device::DeviceProfile,
) -> Result<bool, Error> {
if !profile.takes_driver_deviation(crate::error::DriverDeviation::MetalSampler) {
return Ok(false);
}
let state = super::constexpr::state_of(words)?;
let device = super::constexpr::constexpr_desc(words, use_, profile)?;
Ok(state.mip_filter == MipFilter::None
&& device.max_anisotropy.is_some()
&& device.min_filter != device.mag_filter)
}
/// Whether sample `op` of a texture of `shape` (`image`) through static sampler `sampler` (`None`
/// for an argument buffer's) takes Metal's anisotropic filter emulated (the module's reach), with
/// its note recorded: `AnisotropicFilter` where it does, `DeviceAnisotropicFilter` where the
/// sampler's anisotropy is known and the sample, filtered at an implicit level or with
/// gradients, is out of reach; a runtime sampler slot's under its word's anisotropy alone. A
/// device whose own sampler answers the sample, anisotropy included, takes neither: one that
/// samples natively or through Metal's own sampler, with `samplerAnisotropy`.
/// device whose own sampler answers the sample, anisotropy included, takes neither: one with
/// `samplerAnisotropy`.
/// `integer`: the texel class is an integer one (never filtered); `observed`: the function
/// reads the sample's residency; `other_class`: the slot's variant binds a texture of another
/// class (`LoweringInputs::cross_class`); `swizzled`: the slot swizzles its converted texels
@@ -307,12 +286,6 @@ pub(super) fn select(
let cube = matches!(lod, Lod::CubeGrad(..));
if anisotropy {
cx.families.sampler.device_sampling = true;
if let Some(SamplerRef::Constexpr(words)) = sampler {
if own_not_mipmapped(words, use_, cx.profile)? {
cx.precision
.insert(PrecisionNote::NotMipmappedAnisotropicFilter);
}
}
return Ok(None);
}
let (degree, mip, device) = match sampler {
@@ -349,8 +322,8 @@ pub(super) fn select(
&& !other_class
&& !swizzled
&& matches!(image, ImageRef::Slot(_));
// Out of reach on Metal's own sampler, the device's filter is Metal's, at the footprint the
// cube's form hands it (`PrecisionNote::CubeGradientFootprint`).
// Out of reach, the device's filter, at the footprint the cube's form hands it
// (`PrecisionNote::CubeGradientFootprint`).
if anisotropy && !reached {
return Ok(None);
}
@@ -486,14 +459,7 @@ pub(super) fn sample(
match a.degree {
Degree::Const(_) => {
let x = filter(cx, fb, s, (key, a), &site, offset)?;
super::emit::texel_value(
cx,
fb,
s,
image,
(x, crate::lower::texture::half::TexelOrigin::Computed),
None,
)
super::emit::texel_value(cx, fb, s, image, x, None)
}
Degree::Slot(n) => {
// The plain sample where the bound sampler's word states no anisotropy.
@@ -505,14 +471,7 @@ pub(super) fn sample(
};
let emulation: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| {
let x = filter(cx, fb, s, (key, a), &site, offset)?;
let x = super::emit::texel_value(
cx,
fb,
s,
image,
(x, crate::lower::texture::half::TexelOrigin::Computed),
None,
)?;
let x = super::emit::texel_value(cx, fb, s, image, x, None)?;
Ok(ArmEnd::FallThrough(vec![x]))
});
let device: ArmFn<'_, EmitCx<'_>> = Box::new(move |fb, cx| {
+13 -117
View File
@@ -1,10 +1,9 @@
//! Emission of the sampling strategies.
use crate::lower::emit::EmitCx;
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,
heap_element, held_texel, live_or_zero, resident_access, sparse_spec, tile_map, tiled_word,
with_word,
};
use crate::spirv::builder::constructs::{ArmEnd, ArmFn, Merged};
use crate::spirv::builder::ops::image::ArmedOffset;
@@ -459,29 +458,12 @@ fn scaled_axis_gradients(
/// component is zero as `∂s_c / (2 |m_a|)` and `∂t_c / (2 |m_a|)`, so the device reads Metal's
/// length whatever its approximation of a vector's (one component is nonzero); its level is its
/// own logarithm of it, where Metal's piecewise-linear one minifies only past a footprint of
/// `1 + 3/2048` (`PrecisionNote::CubeGradientFootprint`). Every known route reads the one
/// component alike, so a route not measured takes it too (but for a `y` face through
/// [`CubeFootprint::Projected`]'s fixup, which reads it on both tangents).
/// `1 + 3/2048` (`PrecisionNote::CubeGradientFootprint`).
/// - [`CubeFootprint::Face`] (an anisotropic sampler): each gradient with its normal component
/// zeroed and Metal's mirroring applied, `(0, ρ g_y, g_z)` and `(0, g_y, ρ g_z)` on an `x` face,
/// `(g_x, 0, ρ g_z)` and `(ρ g_x, 0, g_z)` on a `y` face, `(g_x, ρ g_y, 0)` and `(ρ g_x, g_y, 0)`
/// on a `z` face (`dPdx`'s and `dPdy`'s), from which Vulkan's rule reads Metal's face gradients;
/// the device filters that ellipse by its own anisotropic rule.
/// - [`CubeFootprint::Projected`] (MoltenVK's graphics route under macOS 27,
/// `CubeGradientRoute::AppleProjected`): SPIRV-Cross's `spvGradientCube` (MoltenVK 1.4.1's
/// `adec7acb`) projects each gradient onto the face and writes the two values where Apple's
/// earlier reading took them: `(d_y, d_y, d_z)` on an `x` face, `(d_x, d_z, d_x)` on a `y` face
/// and `(d_x, d_y, d_x)` on a `z` face. Metal under macOS 27 reads the tangents of those, so on
/// an `x` or `z` face the gradient with its normal component zeroed reaches Metal as its own
/// (the probe: every lane of every sampler equal), and is handed so. On a `y` face Metal reads
/// `d_x` on both tangents, the `z` tangent lost: the function hands `(64/91 L, 0, 0)`, `L`
/// Metal's length of `(g_x, g_z)`, whose length on both tangents is `L` again, so an isotropic
/// sample keeps Metal's footprint up to that division's rounding (the probe: all 6,144 lanes of
/// each of three isotropic samplers equal, every face); an anisotropic one's ellipse lies on the
/// diagonal, 922 to 932 of a `y` face's 1,024 lanes differing
/// (`PrecisionNote::CubeGradientFootprint`).
/// - [`CubeFootprint::Metal`]: the gradients as the call states them, for a driver that hands them
/// to Metal's own `gradientcube` unchanged (`CubeGradientRoute::Metal`): exact, no note.
///
/// The major axis is `z` over `y` over `x` at equal magnitudes, which on a direction whose ties are
/// broken as Metal breaks them (`face::metal_ties`) is Metal's, there being none left. A footprint
@@ -494,14 +476,12 @@ pub(super) fn cube_footprint(
form: CubeFootprint,
) -> BResult<(SValue, SValue)> {
match form {
CubeFootprint::Metal => Ok(grads),
CubeFootprint::Word => Err(BuildError::Operand {
op: crate::spv::Op::Select,
rule: OperandRule::Arity,
}),
CubeFootprint::Face => face_gradients(fb, p, grads),
CubeFootprint::Length => tangent_length(fb, p, grads, false),
CubeFootprint::Projected => tangent_length(fb, p, grads, true),
CubeFootprint::Length => tangent_length(fb, p, grads),
}
}
@@ -577,20 +557,16 @@ fn face_gradients(
}
/// [`CubeFootprint::Length`]: each gradient's two tangent components' Metal length on the
/// tangent `(a + 2) mod 3`; or, `projected` ([`CubeFootprint::Projected`]), an `x` or `z` face's
/// gradient without its normal component and a `y` face's length times `64/91` on `x`.
/// tangent `(a + 2) mod 3`.
fn tangent_length(
fb: &mut FunctionBuilder<'_>,
p: SValue,
(dx, dy): (SValue, SValue),
projected: bool,
) -> BResult<(SValue, SValue)> {
let f = f32_ty(fb)?;
let triple = vec(fb, f, 3)?;
let m = Major::of(fb, p)?;
let zero = f32_const(fb, 0)?;
// Metal's length of a pair of equal components `c` is `91/64 c`.
let diagonal = f32_const(fb, (64.0f32 / 91.0).to_bits())?;
let one = |fb: &mut FunctionBuilder<'_>, g: SValue| -> BResult<SValue> {
let [gx, gy, gz] = components(fb, g)?;
// The face's two tangents: `y` and `z` on an `x` face, `x` and `z` on a `y` face, `x`
@@ -598,14 +574,6 @@ fn tangent_length(
let first = fb.select(m.y_or_z, gx, gy)?;
let second = fb.select(m.z, gy, gz)?;
let length = super::anisotropic::metal_length(fb, first, second)?;
if projected {
let on_y_face = fb.binary(BinOp::FMul, length, diagonal)?;
let on_x = fb.select(m.y, on_y_face, gx)?;
let on_x = fb.select(m.y_or_z, on_x, zero)?;
let on_y = fb.select(m.y, zero, gy)?;
let on_z = fb.select(m.y_or_z, zero, gz)?;
return fb.composite_construct(triple, &[on_x, on_y, on_z]);
}
// The tangent `(a + 2) mod 3`: `z` for an `x` face, `x` for a `y` face, `y` for a `z`
// face.
let on_x = fb.select(m.y, length, zero)?;
@@ -1069,7 +1037,7 @@ pub(super) fn sampled_value(
let (x, word) = pixel_fetch(cx, fb, s, si, image, offset.as_ref(), arm)?;
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);
return texel_value(cx, fb, s, image, x, word);
}
if let SampleOp::Bicubic(b) = &s.op {
// No sparse form: the slot takes no sparse arm, and the word is 0. The routines return the
@@ -1231,7 +1199,7 @@ pub(super) fn sampled_value(
None => word,
};
let texel = live_or_zero(fb, live, texel)?;
texel_value(cx, fb, s, image, (texel, TexelOrigin::Image), word)
texel_value(cx, fb, s, image, texel, word)
}
/// The plane coordinate of `s`, read from the AIR operand as given: the device's sampler, and an
@@ -2249,24 +2217,23 @@ pub(super) fn texel_value(
fb: &mut FunctionBuilder<'_>,
s: &Sampling,
image: super::CombinedImage,
(texel, origin): (SValue, TexelOrigin),
texel: SValue,
word: Option<SValue>,
) -> BResult<SValue> {
let held = held_value(cx, fb, s, image, (texel, origin))?;
let held = held_value(cx, fb, s, image, texel)?;
let held = held_constants(cx, fb, s, held)?;
with_word(cx, fb, &s.result, held, word)
}
/// The held texel of sampling `s`'s image texel `texel`: an 8-bit sRGB texel's raw code decoded
/// by the device's transfer, a slot's `half` or `float` texel converted by the bound format's class,
/// else the texel held as the result's type holds it; before the lanes Metal reads as constants
/// are set ([`held_constants`]).
/// by the device's transfer, else the texel held as the result's type holds it; before the lanes
/// Metal reads as constants are set ([`held_constants`]).
pub(super) fn held_value(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
s: &Sampling,
image: super::CombinedImage,
(texel, origin): (SValue, TexelOrigin),
texel: SValue,
) -> BResult<SValue> {
let Some(form) = s.texel else {
return Err(cx.fail("a sample without a texel form"));
@@ -2280,78 +2247,7 @@ pub(super) fn held_value(
};
return crate::lower::texture::srgb_texel(fb, form, texel, color);
}
// A `half` texel of a slot converts by the bound format's class: a gather's texel as a read's,
// a sample's (nearest, linear, or fetched) filtered value as a sample's, each with the access's
// lanes. Not where the sample's texel is the device's (`Sampling::half_texel`): it is held.
let half = match s.source {
Source::Combined(key) if !s.depth && s.half_texel => {
half_class(cx, &ImageRef::Slot(key.texture), form)
}
Source::Heap { handle, .. }
| Source::HeapSampler { handle, .. }
| Source::HeapArray { handle, .. }
if !s.depth && s.half_texel =>
{
crate::lower::texture::heap_half_class(cx, fb, handle, form)?
}
_ => None,
};
Ok(match half {
Some(h) => {
let lanes = sample_lanes(cx, fb, s)?;
h.convert(fb, texel, lanes, origin)?
}
None => held_texel(fb, image.texel, form, texel)?,
})
}
/// Whether sampler word `word` states a sampler that reads one texel of one level: nearest min and
/// mag filters, no anisotropy, and no linear mip filter (a `bool`).
fn word_reads_one(fb: &mut FunctionBuilder<'_>, word: SValue) -> BResult<SValue> {
let filters =
fb.u32_const(SamplerWord::MIN_LINEAR | SamplerWord::MAG_LINEAR | SamplerWord::ANISOTROPIC)?;
let filters = fb.module().const_value(filters)?;
let filters = fb.binary(BinOp::BitwiseAnd, word, filters)?;
let zero = fb.u32_const(0)?;
let zero = fb.module().const_value(zero)?;
let nearest = fb.binary(BinOp::IEqual, filters, zero)?;
let mip = fb.u32_const(SamplerWord::MIP_FILTER)?;
let mip = fb.module().const_value(mip)?;
let mip = fb.binary(BinOp::BitwiseAnd, word, mip)?;
let linear_mip = fb.u32_const(2 << SamplerWord::MIP_FILTER_SHIFT)?;
let linear_mip = fb.module().const_value(linear_mip)?;
let one_level = fb.binary(BinOp::INotEqual, mip, linear_mip)?;
fb.binary(BinOp::LogicalAnd, nearest, one_level)
}
/// The lanes of sampling `s`'s texel for the class's conversion (`half::TexelLanes::code`): a 2D
/// gather's channel, one texel's lanes, or a value that may be filtered, as [`Sampling::one_texel`]
/// says; where a runtime or argument buffer's sampler's word decides, one texel's where the word
/// states nearest min and mag filters, no linear mip filter, and no anisotropy, else filtered.
pub(super) fn sample_lanes(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
s: &Sampling,
) -> BResult<SValue> {
use crate::lower::texture::half::TexelLanes;
use crate::lower::texture::OneTexel;
let word = match s.one_texel {
OneTexel::Always => {
let lanes = match s.op {
SampleOp::Gather { component, .. } => TexelLanes::Gathered(component),
_ => TexelLanes::Texel,
};
return lanes.value(fb);
}
OneTexel::Never => return TexelLanes::Filtered.value(fb),
OneTexel::Word(n) => sampler_word(cx, fb, Pixel::Spec(n))?,
OneTexel::Heap(h) => sampler_word(cx, fb, Pixel::Heap(h))?,
OneTexel::Table(_) => array_word(cx, fb, s)?,
};
let one = word_reads_one(fb, word)?;
let texel = TexelLanes::Texel.value(fb)?;
let filtered = TexelLanes::Filtered.value(fb)?;
fb.select(one, texel, filtered)
held_texel(fb, image.texel, form, texel)
}
#[cfg(test)]
@@ -4,7 +4,7 @@
//!
//! **Why fetches on every device.** No Vulkan format holds these codes: the image holds the
//! texels' bytes in an unsigned integer format, which no device filters, so the shader reads
//! the taps and filters them itself, on a device that samples through Metal's own sampler too.
//! the taps and filters them itself.
//!
//! **Metal's answers** (an Apple M3 Max on macOS 26.7 and an Apple M4 on macOS 27.0.1,
//! byte-identical): a nearest sample is the read of the texel at Metal's position, decoded (its
@@ -7,10 +7,8 @@
//! Vulkan's face orientation, `s` and `t` the axes of the face's `s_c` and `t_c` and `σ` their
//! signs, with `dPdx`'s `t` component and `dPdy`'s `s` component times `ρ = σ_s σ_t` through an
//! anisotropic sampler. Vulkan's cube derivative rule must read that from the `Face` form over
//! `2 |m_a|`, and nothing on the normal; the `Length` form must hand Metal's length of the two on
//! one tangent; and Metal's own reading must take an `x` or `z` face's gradients from what
//! MoltenVK's swizzle (SPIRV-Cross's `spvGradientCube`) makes of the `Projected` form, and a `y`
//! face's Metal length.
//! `2 |m_a|`, and nothing on the normal; and the `Length` form must hand Metal's length of the
//! two on one tangent.
//!
//! Through a runtime sampler `emit::word_footprint` hands one of those forms or the isotropic one
//! by the sampler's word (`emit::by_anisotropy`).
@@ -64,25 +62,6 @@ fn metal_length(x: f32, y: f32) -> f32 {
(big + small * 0.1875).max(big * 0.765_625 + small * 0.656_25)
}
/// SPIRV-Cross's `spvGradientCube` (MoltenVK's cube-gradient swizzle on an Apple GPU) of
/// gradient `g` at direction `p`: the vector Apple's hardware is handed.
fn swizzled(p: [f32; 3], g: [f32; 3]) -> [f32; 3] {
let a = p.map(f32::abs);
let x_major = a[0] >= a[1].max(a[2]);
let y_major = a[1] >= a[2];
let permute = |v: [f32; 3]| match (x_major, y_major) {
(true, _) => [v[1], v[2], v[0]],
(false, true) => [v[0], v[2], v[1]],
(false, false) => v,
};
let (q, dq) = (permute(p), permute(g));
let d = [dq[0] - q[0] / q[2] * dq[2], dq[1] - q[1] / q[2] * dq[2]];
match x_major {
true => [d[0], d[0], d[1]],
false => [d[0], d[1], d[0]],
}
}
/// Directions on each of the six faces, at the face's center and off it.
fn directions() -> Vec<[f32; 3]> {
let mut out = Vec::new();
@@ -183,43 +162,6 @@ fn a_length_footprint_hands_metals_length_on_one_tangent() {
}
}
/// Through MoltenVK's swizzle, Metal's macOS 27 reading (the face's two tangents of what it is
/// handed) takes an `x` or `z` face's tangents of the `Projected` form as the gradient's own, and
/// on a `y` face reads the same value on both tangents, whose Metal length is the gradient's
/// within the five roundings between (`64/91`, its product, and the length's two products and
/// sum).
#[test]
fn a_projected_footprint_reaches_metals_reading_through_the_fixup() {
let lanes = directions();
for g in GRADIENTS {
for is_dx in [true, false] {
for (d, h) in lanes
.iter()
.zip(handed_as(CubeFootprint::Projected, g, &lanes, is_dx))
{
let (a, (s, _), (t, _)) = face_of(*d);
assert_eq!(h[a], 0.0, "{d:?} {g:?}: the normal's component {h:?}");
let fixed = swizzled(*d, h);
if a == 1 {
assert_eq!(fixed[s], fixed[t], "{d:?} {g:?}: handed {h:?}");
let want = metal_length(g[s], g[t]);
let got = metal_length(fixed[s], fixed[t]);
assert!(
(got - want).abs() <= 4.0 * want * f32::EPSILON,
"{d:?} {g:?}: {got} for {want}"
);
} else {
assert_eq!(
[fixed[s], fixed[t]],
[g[s], g[t]],
"{d:?} {g:?}: handed {h:?}"
);
}
}
}
}
}
/// What `by_anisotropy` hands the device for gradient `g` through a sampler of word `word`, per
/// direction of `lanes`, choosing between the gradients `cube_footprint` hands in form `set` and in
/// form `clear`.
@@ -1,9 +1,8 @@
//! The sampling routines are routines: the texel conversion states `DontInline`, every other
//! function none, and the entry states none.
//! The sampling routines are routines: the in-place linear quad's exact sum states `DontInline`,
//! every other function none, and the entry states none.
use super::kernel_on;
use crate::lower::sampler::bicubic::routines;
use crate::lower::texture::half;
use crate::spirv::builder::ModuleBuilder;
use crate::spirv::serialize::serialize;
@@ -22,13 +21,11 @@ fn controls(words: &[u32]) -> Vec<u32> {
out
}
/// The texel conversion and the linear and bicubic filters' sums beside a kernel entry: the texel
/// routine, a kept routine, states `DontInline` (0x2, the in-place linear quad's exact sum) and
/// every other function `None`.
/// The linear and bicubic filters' sums beside a kernel entry: the in-place linear quad's exact
/// sum, a kept routine, states `DontInline` (0x2) and every other function `None`.
#[test]
fn the_texel_routine_alone_is_declared_dont_inline() {
let mut b = ModuleBuilder::new();
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");
@@ -36,8 +33,8 @@ fn the_texel_routine_alone_is_declared_dont_inline() {
let words = serialize(m).expect("serialized").words;
let mut got = controls(&words);
got.sort_unstable();
// 4 routines (the plane's, the line's, the quad's, and the texel conversion) and the entry.
assert!(got.len() >= 5, "{} functions", got.len());
// 3 routines (the plane's, the line's and the quad's) and the entry.
assert!(got.len() >= 4, "{} functions", got.len());
let mut want = vec![0; got.len() - 1];
want.push(0x2);
assert_eq!(got, want, "each routine's control, and none on the entry");
+8 -115
View File
@@ -1,45 +1,29 @@
//! What the device-sampled filters share with the emulated ones the device has no form for
//! (`extended`, `heap_raw`, `in_place`, `bicubic`): the census words of a filter's footprint and
//! of a runtime sampler's word, the rule of an axis whose two taps read one texel ([`merged`]), the samplers
//! that read one texel of one level ([`unfiltered`]), and the note of a filtered
//! sample that Metal's own sampler answers otherwise than Metal filters the format bound there
//! ([`filter_note`]).
//! of a runtime sampler's word, the rule of an axis whose two taps read one texel ([`merged`]), and
//! the samplers that read one texel of one level ([`unfiltered`]).
//!
//! Every filtered sample of a format the device samples is the device's: Metal's own filter on a
//! device that samples through Metal's own sampler (`VkProperty::MetalSampler`, MoltenVK), and the
//! device's own elsewhere (`VkProperty::DeviceSampling`, recorded as
//! `PrecisionNote::DeviceSampling`).
//! Every filtered sample of a format the device samples is the device's own
//! (`VkProperty::DeviceSampling`, recorded as `PrecisionNote::DeviceSampling`).
//!
//! **Two-plane YCbCr textures** (`YCBCR8_420_2P` and its kin). A format's view holds each channel
//! of the converted color as Metal reads it, a step `k / D` (alpha 1) on its field's grid: `2048`
//! (`PackedTexels::YCbCr2048`), `8192` (`PackedTexels::YCbCr8192`), or `8192` signed within
//! `[-2, 2]` (`PackedTexels::YCbCrExtended8192`). Metal's 2D linear sample sums the steps on the
//! grid, each term truncated; Metal's own sampler filters the view's texels as an `RGBA16Float` or
//! `RGBA32Float` texture's, within one step of the grid, so a filtered sample of such a slot there
//! records `PrecisionNote::HalfSampleFilter` or `PrecisionNote::FloatSampleFilter` where the bound
//! format is two-plane YCbCr ([`metal_filtered_ycbcr`]), through a runtime sampler slot only where
//! the bound sampler filters ([`filtering_word`]). A heap's texture (an argument buffer's) is held
//! by the same view and sampled by the same sampler, so its filtered sample records the note where
//! a texture its handles can name is two-plane YCbCr, and through an argument buffer's sampler
//! where a sampler state an argument buffer can name filters. A device whose memory is the host's
//! reads a slot's planes in place, Metal's filter exactly (`in_place`).
//! grid, each term truncated; the device's sampler filters the view's texels its own way
//! (`PrecisionNote::DeviceSampling`). A device whose memory is the host's reads a slot's planes in
//! place, Metal's filter exactly (`in_place`).
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::lower::select::{NoteOn, NoteTest};
use crate::metal::sampler::SamplerWord;
use crate::metal::texel_format::{PackedTexels, TexelFormat};
use crate::metal::SamplerMipFilter;
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::sym::SamplerRef;
use crate::spirv::builder::FunctionBuilder;
use crate::spirv::error::BResult;
use crate::spirv::ids::Value as SValue;
use crate::spirv::ir::BinOp;
use super::bicubic::{scalar, value, Tap, Tys};
use super::SampleOp;
/// The census words a runtime sampler's emulation adds once per sample: the word's filter test and
/// each axis's mode test (`reaches_word`), each axis's mode and the coordinates' extraction, the
@@ -54,62 +38,6 @@ pub(super) const WORD_TAP_WORDS: u32 = 160;
/// The census words of a linear 2D sample's emulation.
pub(super) const PLANE_WORDS: u32 = 576;
/// The note of sample `op` of `image` through `sampler` (`None`: an argument buffer's) with
/// texel form `form` where Metal's own sampler (`VkProperty::MetalSampler`) filters it otherwise
/// than Metal filters the format bound there, with the clauses under which it holds
/// ([`metal_filtered_ycbcr`]): `PrecisionNote::HalfSampleFilter` for a `half` result,
/// `PrecisionNote::FloatSampleFilter` for a `float` one (a depth texture's and a comparison's
/// included); `None` for a sample that is not filtered (a constexpr sampler that reads one texel
/// of one level, [`unfiltered`]), one of another result, a heap texture's, and every sample on a
/// device that samples natively, whose module records `PrecisionNote::DeviceSampling` instead.
/// Through a runtime sampler slot each clause also tests the word of the sampler bound there
/// ([`filtering_word`]), which the runtime reads at each draw or dispatch: a bound sampler that
/// reads one texel of one level takes the texel the view holds, Metal's read, and holds none.
/// An argument buffer's sampler is the state whose ID its memory holds, which no plan reads: its
/// clauses test that a sampler state an argument buffer can name filters
/// (`NoteOn::ArgumentSamplers`, every live state), so a program whose live states all read one
/// texel of one level holds none.
pub(super) fn filter_note(
cx: &SelectCx<'_>,
op: &SampleOp,
form: Option<TexelForm>,
(sampler, image): (Option<SamplerRef>, ImageRef),
) -> Result<Option<(PrecisionNote, Vec<NoteClause>)>, Error> {
if !matches!(op, SampleOp::Sample { .. }) {
return Ok(None);
}
let note = match form.map(|f| f.conv) {
Some(TexelConv::F16) => PrecisionNote::HalfSampleFilter,
Some(TexelConv::F32) => PrecisionNote::FloatSampleFilter,
_ => return Ok(None),
};
let filters = match sampler {
Some(SamplerRef::Constexpr(words)) => match unfiltered(&super::state_of(words)?) {
true => return Ok(None),
false => None,
},
Some(SamplerRef::Slot(n)) => Some(filtering_word(n).to_vec()),
None => Some(vec![NoteTest::equal(NoteOn::ArgumentSamplers, 1, 1)]),
};
let Some(formats) = metal_filtered_ycbcr(cx, image) else {
return Ok(None);
};
let when = match filters {
None => formats,
Some(words) => formats
.iter()
.flat_map(|format| {
words.iter().map(move |&word| {
let mut clause = format.clone();
clause.insert(word);
clause
})
})
.collect(),
};
Ok(Some((note, when)))
}
/// The tests of the word of the sampler bound at runtime sampler slot `n` (`NoteOn::BoundSampler`,
/// `SamplerWord`) of which one holds exactly where a sample through it filters, [`unfiltered`]'s
/// rule read from the word: a linear minification or magnification filter, anisotropy or a cubic
@@ -127,41 +55,6 @@ pub(super) fn filtering_word(n: u32) -> [NoteTest; 2] {
]
}
/// On a device that samples through Metal's own sampler (`VkProperty::MetalSampler`), the clauses
/// under which a
/// filtered sample of texture slot `image` is not Metal's filter of the format bound there: where
/// that format is two-plane YCbCr (its class's `TexelFormat::PACKED` field one of
/// [`PackedTexels::YCbCr2048`], [`PackedTexels::YCbCr8192`] and
/// [`PackedTexels::YCbCrExtended8192`]), whose view holds Metal's reads exactly but which Metal's
/// sampler then filters as an `RGBA16Float` or `RGBA32Float` texture's texels, not on the format's
/// own grid. A consumer reads it under the bound format (`SpecKey::BoundTexelFormat`,
/// `StageModule::precision_notes_bound`; [`filter_note`] adds a runtime sampler slot's word). A heap's
/// texture, which a handle names at run time, holds one clause: a texture the stage's handles can
/// name is two-plane YCbCr (`SpecKey::HeapYCbCrTextures`, which the plan gives from the command's
/// heap members). `None` on any other device.
pub(super) fn metal_filtered_ycbcr(cx: &SelectCx<'_>, image: ImageRef) -> Option<Vec<NoteClause>> {
let metal = cx
.profile
.fields()
.enabled
.properties
.contains(&crate::device::requirements::VkProperty::MetalSampler);
if !metal {
return None;
}
Some(match image {
ImageRef::Slot(index) => any_of(
[
PackedTexels::YCbCr2048,
PackedTexels::YCbCr8192,
PackedTexels::YCbCrExtended8192,
]
.map(|p| NoteTest::equal(NoteOn::Bound(index), TexelFormat::PACKED_MASK, p.class().0)),
),
ImageRef::Heap { .. } => any_of([NoteTest::equal(NoteOn::HeapYCbCr(cx.stage), 1, 1)]),
})
}
/// 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:
+36 -95
View File
@@ -79,18 +79,17 @@
//! `calculate_*_lod` use the fragment's implicit derivatives and are tangled. Metal reads a bias as
//! `B = clamp(floor(half_rne(bias) * 64) / 64, -32, 31.984375)` and applies it whole, where Vulkan
//! clamps a `Bias` operand to `maxSamplerLodBias`. Through a sampler without a bias of its own the
//! `Bias` operand is the bias as given, which Metal's own sampler (MoltenVK) reads as Metal does and
//! another device's sampler reads its own way. Through a constexpr sampler with a bias of its own
//! the shader forms `B` (`emit::metal_bias`): the `Bias` operand within the limit, and a bias that
//! may reach past it also samples with the derivatives scaled by `2^B` ([`BiasReach`],
//! `bias_gradients`). Through an
//! anisotropic sampler of a 2D texture Metal's `B` shifts the footprint's minor axis alone, which
//! the axis gradients give (`emit::axis_gradients`): a constexpr sampler's always, a runtime or
//! argument buffer's sampler's where its word states anisotropy, chosen per invocation. Outside a
//! fragment function, Metal's sample without a level or gradients reads the
//! default level 0, shifted by its bias and bounded below by its `min_lod_clamp`: an explicit level
//! ([`Lod::Base`]), and `calculate_*_lod` is undefined in Metal (`NotRepresentable`). Gradients,
//! explicit levels, and gathers (which read the base level) are not tangled.
//! `Bias` operand is the bias as given, which the device's sampler reads its own way. Through a
//! constexpr sampler with a bias of its own the shader forms `B` (`emit::metal_bias`): the `Bias`
//! operand within the limit, and a bias that may reach past it also samples with the derivatives
//! scaled by `2^B` ([`BiasReach`], `bias_gradients`). Through an anisotropic sampler of a 2D
//! texture Metal's `B` shifts the footprint's minor axis alone, which the axis gradients give
//! (`emit::axis_gradients`): a constexpr sampler's always, a runtime or argument buffer's sampler's
//! where its word states anisotropy, chosen per invocation. Outside a fragment function, Metal's
//! sample without a level or gradients reads the default level 0, shifted by its bias and bounded
//! below by its `min_lod_clamp`: an explicit level ([`Lod::Base`]), and `calculate_*_lod` is
//! undefined in Metal (`NotRepresentable`). Gradients, explicit levels, and gathers (which read the
//! base level) are not tangled.
//!
//! **Pixel coordinates**. Metal reads a pixel sampler's coordinate `x` as it is given: its nearest
//! texel is `floor(x)`, and its linear filter's footprint and weights, and its gather's block, are
@@ -143,15 +142,13 @@
//! specialization; a gather through one is an ordinary gather.
//!
//! **The device's sampler**. Every other sample, gather and comparison of a format the device
//! samples is the device's: Metal's own on a device that samples through Metal's own sampler
//! (`VkProperty::MetalSampler`, MoltenVK), and the device's own elsewhere
//! (`VkProperty::DeviceSampling`, recorded as `PrecisionNote::DeviceSampling`); the module
//! requires the property. A cube's direction takes Metal's face at a tie (`face::metal_ties`).
//! Every footprint Metal's rule decides in the shader (the emulated filters the device has no form
//! for) reads Metal's position ([`position`]): the coordinate wrapped into one period first on a
//! repeating or mirrored axis, then scaled with ties away from zero. Metal reads a cube's
//! coordinate as a direction through a pixel sampler too, so a cube's pixel sampler is a normalized
//! one here.
//! samples is the device's own (`VkProperty::DeviceSampling`, recorded as
//! `PrecisionNote::DeviceSampling`); the module requires the property. A cube's direction takes
//! Metal's face at a tie (`face::metal_ties`). Every footprint Metal's rule decides in the shader
//! (the emulated filters the device has no form for) reads Metal's position ([`position`]): the
//! coordinate wrapped into one period first on a repeating or mirrored axis, then scaled with ties
//! away from zero. Metal reads a cube's coordinate as a direction through a pixel sampler too, so a
//! cube's pixel sampler is a normalized one here.
//!
//! Not lowered yet: a static texture sampled through an argument buffer's sampler, a heap image
//! sampled through several sampler candidates, the binding-array rule, and the bicubic forms
@@ -289,8 +286,7 @@ pub struct ConstexprArray {
/// Each element's canonical state words (`SamplerRef::Constexpr`).
pub samplers: Vec<[u64; 2]>,
/// Each element's sampler word (`metal::sampler::SamplerWord`), which a sampling reads where
/// the element's state decides what it does (`heap_raw::State::Table`,
/// `texture::OneTexel::Table`).
/// the element's state decides what it does (`heap_raw::State::Table`).
pub words: Vec<u32>,
}
@@ -361,9 +357,8 @@ pub enum Source {
/// `PrecisionNote::GradFromBias` where gradients carry it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BiasReach {
/// A sampler without a bias of its own: the `Bias` operand as given, which Metal's own sampler
/// (`VkProperty::MetalSampler`, MoltenVK) reads as Metal reads a bias, and another device's
/// sampler its own way.
/// A sampler without a bias of its own: the `Bias` operand as given, which the device's
/// sampler reads its own way.
Metal,
/// No bias, or a constant whose `B`, with the sampler's bias, is within the limit, through an
/// isotropic constexpr sampler: the `Bias` operand `B` alone.
@@ -414,30 +409,17 @@ pub enum Lod {
Hoisted,
}
/// The footprint a cube's explicit gradients take, and the device rule it is handed for
/// (`emit::cube_footprint`): Metal's under macOS 27 (the oracle, the Apple M3 Max), but where the
/// stage's route is MoltenVK's graphics fixup on macOS 26.7's identity, which hands that GPU its
/// own earlier footprint.
/// The footprint a cube's explicit gradients take, Metal's under macOS 27 (the oracle, the Apple
/// M3 Max), in the form Vulkan's cube derivative rule reads (`emit::cube_footprint`): the
/// device's reading of it is its own (`PrecisionNote::CubeGradientFootprint`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
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`).
/// each gradient's two tangent components, on one tangent.
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.
Face,
/// The gradients for MoltenVK's graphics fixup under macOS 27
/// (`CubeGradientRoute::AppleProjected`), through any sampler: an `x` or `z` face's without its
/// normal component, which Metal reads as its own; a `y` face's Metal length on `x`, which the
/// fixup hands Metal on both tangents (an isotropic sample's footprint kept, an anisotropic
/// one's ellipse on the diagonal).
Projected,
/// Metal's gradients as the call states them, through any sampler: for a driver that hands
/// the stage's cube gradients to Metal's own `gradientcube` unchanged
/// (`CubeGradientRoute::Metal`), whose GPU reads them by Metal's own rule. Exact: the module
/// records no `PrecisionNote::CubeGradientFootprint` for it.
Metal,
/// A runtime or argument buffer's sampler's, by its word: [`Face`] where the word states
/// `SamplerWord::ANISOTROPIC`, else [`Length`] (`emit::word_footprint`).
///
@@ -694,14 +676,6 @@ pub struct Sampling {
/// 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,
/// Whether the access reads one texel of one level: its `half` texel's lanes for the class's
/// conversion.
pub one_texel: crate::lower::texture::OneTexel,
/// A `half` texel of the slot, or of the heap color texture, converts by the bound format's
/// class (`texture::half`): not a raw, bicubic or depth one's, nor where the sample's texel is
/// the device's (`texture::device_texels`: a device that does not sample through Metal's own
/// sampler), rounded exactly. The emission follows it.
pub half_texel: bool,
/// Metal's value of the texels the access reads in a block of a sparse image that holds no
/// mapped tile.
pub unmapped: Unmapped,
@@ -964,10 +938,10 @@ impl Sampling {
/// the pixel scaling, the reading of a dynamic `Offset` operand, a heap element's access chain,
/// sampled image, and null select, the sparse arm, a bias past the limit's derivatives,
/// `bias_gradients`, and (for a dynamic bias) the test, the selection, and the second sample, a
/// `half` texel's call of its conversion routine or its exact rounding outside the bicubic
/// filter, an sRGB texel's raw decode, a cube gradient's footprint, a pixel coordinate's texel
/// or block centre, the positions of an observed footprint, the lanes Metal reads as
/// constants, a cube direction's broken ties, and a raw heap sample's decode.
/// `half` texel's exact rounding outside the bicubic filter, an sRGB texel's raw decode, a cube
/// gradient's footprint, a pixel coordinate's texel or block centre, the positions of an
/// observed footprint, the lanes Metal reads as constants, a cube direction's broken ties, 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) {
@@ -1003,10 +977,10 @@ impl Sampling {
..
} => (64 + 200 + 200 + 48, offset.as_ref()),
SampleOp::Sample {
lod: Lod::CubeGrad(_, _, form),
lod: Lod::CubeGrad(..),
offset,
..
} if *form != CubeFootprint::Metal => (64 + 200, offset.as_ref()),
} => (64 + 200, offset.as_ref()),
SampleOp::Sample { offset, .. } => (64, offset.as_ref()),
// The size query, the floor, the clamp, and the fetch.
SampleOp::PixelFetch { offset } => (96, offset.as_ref()),
@@ -1029,14 +1003,7 @@ impl Sampling {
let heap = match self.source {
Source::Combined(_) => 0,
Source::Heap { .. } => 32,
// A one-texel test the element's word decides reads that word.
Source::HeapArray { .. } => {
let table = match self.one_texel {
crate::lower::texture::OneTexel::Table(n) => table_words(n),
_ => 0,
};
32 + ARRAY_WORDS + table
}
Source::HeapArray { .. } => 32 + ARRAY_WORDS,
Source::HeapSampler { .. } => 56 + 2 * ENTRY_FIELD_WORDS + CUBIC_REACH_WORDS,
};
let residency = if self.residency {
@@ -1044,23 +1011,11 @@ impl Sampling {
} else {
0
};
// A `half` texel's call of the conversion routine or its exact rounding, or an sRGB texel's
// raw decode; the bicubic routines round their `half` result themselves.
// A `half` texel's exact rounding, or an sRGB texel's raw decode; the bicubic routines
// round their `half` result themselves.
let half = match (&self.op, self.texel) {
(SampleOp::Bicubic(_), _) | (_, None) => 0,
_ if self.raw => crate::lower::texture::SRGB_DECODE_WORDS,
// A heap color texture's call reads the class its handle carries first.
(_, Some(f)) if f.conv == crate::lower::texture::TexelConv::F16 => {
let class = match self.source {
Source::Heap { .. } | Source::HeapSampler { .. } | Source::HeapArray { .. }
if !self.depth =>
{
crate::lower::texture::HEAP_CLASS_WORDS
}
_ => 0,
};
crate::lower::texture::half::CALL_WORDS.max(f.read_words()) + class
}
(_, Some(f)) => f.read_words(),
};
// A pixel coordinate's texel centre: the floor, the shift, and their constants; by a
@@ -1151,10 +1106,6 @@ pub struct RuntimeSlot {
/// A cube's explicit gradients take their footprint by its word (`CubeFootprint::Word`): the
/// function reads whether its word is anisotropic.
pub anisotropy: bool,
/// A sample's `half` texel converts by the bound format's class where the sampler reads one
/// texel of one level (`texture::OneTexel::Word`), on a device that samples through Metal's
/// own sampler (`VkProperty::MetalSampler`): the function reads its word's filter fields.
pub texels: bool,
/// A clamped LOD query outside a fragment function reads it ([`SampleOp::QueryLevel`]), or an
/// extended-range sample whose linear mip filter blends two levels (`extended::Level::Word`):
/// the function reads its `SpecKey::SamplerMinLevel` specialization.
@@ -1187,9 +1138,6 @@ impl RuntimeSlot {
if self.emulated {
fields |= SamplerWord::ANISOTROPIC | SamplerWord::MIP_FILTER;
}
if self.texels {
fields |= SamplerWord::LINEAR_FILTER;
}
if self.reads {
fields |= SamplerWord::READ_STATE;
}
@@ -1257,14 +1205,8 @@ pub struct SamplerPlan {
pub bicubic_pixel: bool,
/// The bicubic routines the samples call, by dimension, an extended-range sample's among them.
pub bicubic_routines: BTreeSet<bicubic::routines::Routine>,
/// A sample relies on the device's sampler: the module requires `VkProperty::MetalSampler`
/// on a device that samples through Metal's own sampler, and `VkProperty::DeviceSampling` on
/// one that samples natively.
pub metal_sampler: bool,
/// A sample, gather or comparison goes to the device's sampler: on a device that samples
/// natively the module requires `VkProperty::DeviceSampling` and records
/// `PrecisionNote::DeviceSampling`; on one that samples through Metal's own it requires
/// `VkProperty::MetalSampler`.
/// A sample, gather or comparison goes to the device's sampler: the module requires
/// `VkProperty::DeviceSampling` and records `PrecisionNote::DeviceSampling`.
pub device_sampling: bool,
/// Every operation through an argument buffer's sampler tests its table entry's word for a
/// cubic filter (`SamplerWord::CUBIC`) and marks the command buffer's `ExecutionStatus` where
@@ -1926,7 +1868,6 @@ pub fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error
linear: false,
fetch_levels: false,
anisotropy: false,
texels: false,
min_level: false,
emulated: false,
reads: false,
+40 -131
View File
@@ -5,7 +5,6 @@ use crate::air::abi::{AddressMode, Coordinates, Filter, MipFilter};
use crate::air::intrinsics::{ImageDim, ImageShape, LodMode, TexOp, TexRole, Texture};
use crate::air::ir::{BinOp, Const, Inst, InstId, InstKind, Value, ValueId};
use crate::budget::Meter;
use crate::device::profile::CubeGradientRoute;
use crate::device::requirements::{VkFeature, VkLimit};
use crate::error::{
Capability, Error, Feature, InternalError, InternalKind, LowerFamily, Unsupported,
@@ -114,10 +113,8 @@ fn own_bias(sampler: SamplerArg) -> Result<f32, Error> {
})
}
/// Whether fragment bias sampled through `sampler` goes to the device's sampler whole (on
/// MoltenVK, `VkProperty::MetalSampler`, the `Bias` operand reaches Metal's `bias()` as Metal
/// applies it): the sampler has no bias of its own, whose sum with the operand's no measurement
/// has read.
/// Whether fragment bias sampled through `sampler` goes to the device's sampler whole: the
/// sampler has no bias of its own, whose sum with the operand's no measurement has read.
fn bias_to_metal(sampler: SamplerArg) -> Result<bool, Error> {
Ok(own_bias(sampler)? == 0.0)
}
@@ -436,11 +433,11 @@ fn prelude(
))
})
});
// The hoisted derivatives are the whole bias's, but Metal's own sample where the device samples
// through Metal's sampler and the sample takes no bias, which the module then requires.
// The hoisted derivatives are the whole bias's, but the device's own sample where the sample
// takes no bias, as Metal's sampler takes it.
if let Some(h) = &hoist {
if hoist_is_metals(cx, h, ops, samplers)? {
cx.families.sampler.metal_sampler = true;
cx.families.sampler.device_sampling = true;
} else {
cx.precision.insert(PrecisionNote::GradFromBias);
}
@@ -554,13 +551,12 @@ fn select_heap_switch(
/// `smp_handle`, as one sampling through an array of the candidates' samplers
/// (`Source::HeapArray`): its element `smp_handle - first` is exactly the sampler of the candidate
/// of that handle, and the raw emulation reads that element's state word
/// (`heap_raw::State::Table`), as it states whether the sampling reads one texel where the
/// candidates differ in that (`OneTexel::Table`). Where every candidate is a constexpr sampler,
/// (`heap_raw::State::Table`). Where every candidate is a constexpr sampler,
/// their handles consecutive (`first..first + n`); the device indexes an array of samplers by a
/// value that may differ between invocations (`shaderSampledImageArrayNonUniformIndexing`, which
/// the heap's own image array already needs); the use is not tangled; and each candidate's
/// sampling is the same but for its sampler, the state its raw emulation follows, and whether it
/// reads one texel. `None` otherwise, and the switch over the candidates stays.
/// sampling is the same but for its sampler and the state its raw emulation follows. `None`
/// otherwise, and the switch over the candidates stays.
fn select_heap_array(
cx: &mut SelectCx<'_>,
call: Call<'_>,
@@ -605,11 +601,9 @@ fn select_heap_array(
_ => return Ok(None),
}
}
use crate::lower::texture::OneTexel;
let elements = u32::try_from(arms.len())
.map_err(|_| cx.invariant("constexpr sampler candidates past u32"))?;
// A candidate's sampling but for its sampler, its raw emulation's constant state, and whether
// it reads one texel, which the element's word then states (`OneTexel::Table`).
// A candidate's sampling but for its sampler and its raw emulation's constant state.
let shape = |x: &Sampling| -> Option<Sampling> {
let mut y = x.clone();
let Source::Heap { handle, key } = y.source else {
@@ -628,9 +622,6 @@ fn select_heap_array(
}
raw.state = State::Table { elements };
}
if matches!(y.one_texel, OneTexel::Always | OneTexel::Never) {
y.one_texel = OneTexel::Table(elements);
}
Some(y)
};
let Some(one) = arms.first().and_then(shape) else {
@@ -657,10 +648,6 @@ fn select_heap_array(
for w in &samplers {
words.push(super::constexpr::sampler_word(*w)?.0);
}
let one_texel = match arms.first().map(|x| x.one_texel) {
Some(o) if arms.iter().all(|x| x.one_texel == o) => o,
_ => OneTexel::Table(elements),
};
let array = super::ConstexprArray {
first,
samplers,
@@ -690,7 +677,6 @@ fn select_heap_array(
sampler: smp_handle,
key,
};
x.one_texel = one_texel;
cx.families.sampler.heap = before;
cx.families.sampler.heap_arrays.insert(key);
Ok(Some(TextureStrategy::Sampling(Box::new(x))))
@@ -2131,7 +2117,7 @@ fn select_one(
// forms from the `Bias` operand at any bias: the module requires the
// device.
if reach == BiasReach::Metal {
cx.families.sampler.metal_sampler = true;
cx.families.sampler.device_sampling = true;
}
(Some(id(cx, v)?), reach)
}
@@ -2211,15 +2197,12 @@ fn select_one(
}
SamplerArg::Static(SamplerRef::Slot(_), _) | SamplerArg::Heap(_) => None,
};
// 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)) => CubeFootprint::Length,
(CubeGradientRoute::Vulkan, Some(true)) => CubeFootprint::Face,
(CubeGradientRoute::Vulkan, None) => CubeFootprint::Word,
// Vulkan's rule: the device's own reading of the form handed to it
// (`PrecisionNote::CubeGradientFootprint`).
let form = match anisotropic {
Some(false) => CubeFootprint::Length,
Some(true) => CubeFootprint::Face,
None => CubeFootprint::Word,
};
Lod::CubeGrad(dx, dy, form)
} else {
@@ -2482,10 +2465,9 @@ fn select_one(
}
}
let residency = observed && !fetches;
// 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).
// Every sample, gather and level query goes to the device's own sampler
// (`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 { .. }
@@ -2503,24 +2485,6 @@ fn select_one(
}
_ => false,
};
// A filtered sample's note, where Metal's own sampler filters the slot and a two-plane YCbCr
// format bound there takes another filter than Metal's: the clauses test the bound format,
// which the runtime reads at each draw, and through a runtime sampler slot the bound word's
// filter (`SpecKey::BoundSamplerWord`, which the plan gives: no key carries either); a heap
// texture's test what its handles and an argument buffer's sampler can name. A handle names a
// two-plane YCbCr texture (2D, one layer) only through a 2D color class.
let by = stat.map(|(r, _)| r);
let two_plane_reach = match image {
ImageRef::Slot(_) => true,
ImageRef::Heap { .. } => {
shape.dim == ImageDim::D2 && !shape.array && !shape.depth && !shape.ms
}
};
if two_plane_reach {
if let Some((note, when)) = super::linear::filter_note(cx, &op, form, (by, image))? {
cx.note_when(note, when, m)?;
}
}
// A pixel sampler's coordinate reaches the device's sampler over the level-0 size, whose
// texels at a texel edge or a filter step's edge are the device's arithmetic's on that
// coordinate (`pixel_note`). An argument buffer's sampler records a note of its own, which the
@@ -2534,45 +2498,14 @@ fn select_one(
if let SampleOp::Bicubic(b) = &mut op {
b.raw = raw;
}
// Whether the access reads one texel of one level, whose `half` or `float` texel a packed or
// normalized class converts from its codes; a runtime sampler's word decides it, which the
// slot's specialization then reads.
// Whether the access may read one texel of one level, whose `float` texel the device
// converts from its codes.
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 (`texture::half`): no sampler word decides
// them. A slot's texture of a YCbCr format on the grid `8192` (`TexelFormat::YCBCR_8192`) then
// takes the device's rounding of a sample of its one texel (toward zero on MoltenVK over the
// M3 Max, measured; unmeasured on other Apple GPUs), 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::device_texels(cx) =>
{
if let ImageRef::Slot(index) = image {
use crate::metal::texel_format::TexelFormat;
let ties = NoteTest::equal(
NoteOn::Bound(index),
TexelFormat::YCBCR_8192,
TexelFormat::YCBCR_8192,
);
cx.note_when(PrecisionNote::HalfTexelConversion, vec![[ties].into()], m)?;
}
crate::lower::texture::OneTexel::Never
}
other => other,
};
// A bicubic sample rounds its `half` result exactly, keeping denormals, and a raw texel's
// decode rounds its own; another `half` access converts its texel: the device's where the device's texel is
// the answer, else by the bound format's class (a heap color texture's by the class its
// handle carries: the module's routine, called with the class read from the handle).
let device = crate::lower::texture::device_texels(cx);
// Another `half` access's texel is the device's `float` texel rounded to nearest even: not a
// bicubic sample's, which rounds its `half` result exactly, nor a raw texel's, whose decode
// rounds its own.
if !raw && half && !matches!(op, SampleOp::Bicubic(_)) {
if image.heap() && !shape.depth && !device {
cx.families.texture.heap_half = true;
cx.families.access.heap_class = true;
}
let sample = !matches!(op, SampleOp::Gather { .. });
crate::lower::texture::half_texels(cx, image, shape, sample, device, m)?
cx.precision.insert(PrecisionNote::HalfTexelConversion);
}
// A `float` texel that may be one texel's is the device's conversion of its codes: not an sRGB
// raw texel's (decoded by the device's transfer, `SrgbTexelDecode`), a bicubic sample's, or an LOD query's; nor a depth
@@ -2591,18 +2524,6 @@ fn select_one(
{
crate::lower::texture::float_texel_notes(cx, image, shape, one_texel);
}
// The conversion's lanes read a runtime sampler's filter fields where its word decides: a
// `half` texel's on every profile.
let half_converts = half && !raw && !matches!(op, SampleOp::Bicubic(_)) && !device;
if let (crate::lower::texture::OneTexel::Word(n), true, ImageRef::Slot(_)) =
(one_texel, half_converts, image)
{
if !shape.depth {
if let Some(s) = cx.families.sampler.slots.get_mut(&n) {
s.texels = true;
}
}
}
let source = match (image, sampler) {
(ImageRef::Slot(texture), SamplerArg::Static(sampler, _)) => {
let key = BindingKey {
@@ -2662,8 +2583,8 @@ fn select_one(
}
_ => false,
};
// A packed normalized sampled slot of the variant (`LoweringInputs::swizzled_storage`, on a
// device without Metal's own sampler), whose view takes no swizzle: the sampling swizzles
// A packed normalized sampled slot of the variant (`LoweringInputs::swizzled_storage`), whose
// view takes no swizzle: the sampling swizzles
// the texel its class converts, and a gather of a component gathers the component the
// swizzle names, as plain Metal does.
let swizzle = match image {
@@ -2692,13 +2613,13 @@ fn select_one(
// footprint's note, but where a constexpr sampler's emulation answers every word of the
// sample (a runtime sampler's answers only the words its variant names).
if let SampleOp::Sample {
lod: Lod::CubeGrad(_, _, form),
lod: Lod::CubeGrad(..),
..
} = &op
{
let emulated =
anisotropic.is_some_and(|a| matches!(a.degree, super::anisotropic::Degree::Const(_)));
if *form != CubeFootprint::Metal && !emulated {
if !emulated {
cx.precision.insert(PrecisionNote::CubeGradientFootprint);
}
}
@@ -2732,8 +2653,6 @@ fn select_one(
residency,
footprint,
cube,
one_texel,
half_texel: half_converts && !shape.depth,
unmapped,
heap_raw: None,
declared,
@@ -2938,32 +2857,22 @@ fn pixel_position(
})
}
/// Whether sampling `op` through `sampler` reads one texel of one level: a 2D gather and a pixel
/// fetch always, a sample through a constexpr sampler whose state reads one (`linear::unfiltered`),
/// a runtime or argument buffer's sampler's where its word states one; a cube gather (`cube`: its
/// corner texels are made up), a bicubic sample, and an LOD query never.
fn one_texel(
op: &SampleOp,
sampler: SamplerArg,
cube: bool,
) -> Result<crate::lower::texture::OneTexel, Error> {
use crate::lower::texture::OneTexel;
/// Whether sampling `op` through `sampler` may read one texel of one level: a 2D gather and a
/// pixel fetch always, a sample through a constexpr sampler whose state reads one
/// (`linear::unfiltered`), a runtime or argument buffer's sampler's wherever its word may state
/// one; a cube gather (`cube`: its corner texels are made up), a bicubic sample, and an LOD query
/// never.
fn one_texel(op: &SampleOp, sampler: SamplerArg, cube: bool) -> Result<bool, Error> {
Ok(match op {
SampleOp::Gather { .. } if cube => OneTexel::Never,
SampleOp::Gather { .. } | SampleOp::PixelFetch { .. } => OneTexel::Always,
SampleOp::Gather { .. } => !cube,
SampleOp::PixelFetch { .. } => true,
SampleOp::Sample { .. } => match sampler {
SamplerArg::Static(SamplerRef::Constexpr(words), _) => {
match super::linear::unfiltered(&super::state_of(words)?) {
true => OneTexel::Always,
false => OneTexel::Never,
}
super::linear::unfiltered(&super::state_of(words)?)
}
SamplerArg::Static(SamplerRef::Slot(n), _) => OneTexel::Word(n),
SamplerArg::Heap(h) => OneTexel::Heap(h),
SamplerArg::Static(SamplerRef::Slot(_), _) | SamplerArg::Heap(_) => true,
},
SampleOp::Bicubic(_) | SampleOp::Lod { .. } | SampleOp::QueryLevel { .. } => {
OneTexel::Never
}
SampleOp::Bicubic(_) | SampleOp::Lod { .. } | SampleOp::QueryLevel { .. } => false,
})
}
+6 -23
View File
@@ -2036,12 +2036,6 @@ fn identity_refusal(plan: &Plan) -> Option<String> {
.to_owned(),
);
}
if t.heap_half {
return Some(
"a sample or gather of an argument buffer's color texture with a half result"
.to_owned(),
);
}
if let Some(s) = t.slots.values().find(|s| !s.identity_lowered()) {
return Some(format!(
"texture argument {:?}: a type the identity arrays hold no element of, or state of \
@@ -2124,25 +2118,20 @@ fn walk_construct_words(
}
/// The constant a [`NoteTest`] reads: a sampler slot's `SamplerState` word or its
/// `NearestPixelSampler` boolean, 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`), or the whole word of the sampler bound at a
/// sampler slot, which none carries either (`SpecKey::BoundSamplerWord`), or whether a texture a
/// stage's handles can name is two-plane YCbCr (`SpecKey::HeapYCbCrTextures`) or held by its raw
/// texels alone (`SpecKey::HeapRawTextures`), or the families of such textures whose texels may
/// hold a NaN (`SpecKey::HeapNanFamilies`), or whether a sampler state an argument buffer can
/// name filters (`SpecKey::FilteringArgumentSampler`), which the plan gives.
/// `NearestPixelSampler` boolean, by the function's slot index, or the class of the format bound
/// at a texture slot, which no constant carries (`SpecKey::BoundTexelFormat`), or the whole word
/// of the sampler bound at a sampler slot, which none carries either (`SpecKey::BoundSamplerWord`),
/// or whether a texture a stage's handles can name is held by its raw texels alone
/// (`SpecKey::HeapRawTextures`), or the families of such textures whose texels may hold a NaN
/// (`SpecKey::HeapNanFamilies`), which the plan gives.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum NoteOn {
Sampler(u32),
NearestPixel(u32),
Unmeasured(u32),
Bound(u32),
BoundSampler(u32),
HeapYCbCr(Stage),
HeapRaw(Stage),
HeapNan(Stage),
ArgumentSamplers,
}
/// A test of one slot's specialization constant `v`: it holds where `(v & mask == bits) == equal`,
@@ -2208,10 +2197,6 @@ fn declared(families: &FamilyPlans, t: NoteTest) -> Option<SpecTest> {
return None;
}
let key = match t.on {
NoteOn::Unmeasured(index) => {
let s = families.texture.slots.get(&index)?;
s.unmeasured.then_some(SpecKey::UnmeasuredTexels(s.slot))?
}
// Read from the bound texture by the runtime, never a constant: every slot has one.
NoteOn::Bound(index) => SpecKey::BoundTexelFormat(families.texture.slots.get(&index)?.slot),
// Given by the plan from the bound sampler, never a constant: every runtime slot has one.
@@ -2219,10 +2204,8 @@ fn declared(families: &FamilyPlans, t: NoteTest) -> Option<SpecTest> {
SpecKey::BoundSamplerWord(families.sampler.slots.get(&index)?.slot)
}
// Given by the plan from what the command's handles can name, never a constant.
NoteOn::HeapYCbCr(stage) => SpecKey::HeapYCbCrTextures(stage),
NoteOn::HeapRaw(stage) => SpecKey::HeapRawTextures(stage),
NoteOn::HeapNan(stage) => SpecKey::HeapNanFamilies(stage),
NoteOn::ArgumentSamplers => SpecKey::FilteringArgumentSampler,
NoteOn::Sampler(index) => {
let r = families.sampler.slots.get(&index)?;
let fields = r.fields();
+1 -1
View File
@@ -36,7 +36,7 @@ fn keys(families: &FamilyPlans) -> BTreeSet<SpecKey> {
.texture
.slots
.values()
.filter(|s| s.declares_texel_format())
.filter(|s| s.texel_format)
.map(|s| SpecKey::TexelFormat(s.slot))
.collect()
}
+5 -130
View File
@@ -10,13 +10,12 @@ use crate::pipeline::sym::Stage;
use crate::spirv::builder::constructs::{ArmEnd, ArmFn, LoopFn, LoopSpec, Merged};
use crate::spirv::builder::FunctionBuilder;
use crate::spirv::error::BResult;
use crate::spirv::ids::{ConstId, FuncId, TypeId, Value as SValue};
use crate::spirv::ids::{ConstId, TypeId, Value as SValue};
use crate::spirv::ir::{
BinOp, ConstBits, Constant, ConvOp, Dim, GlslOp, ImageOperands, ImageQuery, ImageUsage,
MemAccess, MemoryOrder, Scope, Semantics, TexelMemory, Type as SType, UnOp,
};
use super::half::{TexelLanes, TexelOrigin};
use super::slice::Slice;
use super::slot::Parts;
use super::{
@@ -1105,15 +1104,13 @@ fn srgb_codes(fb: &mut FunctionBuilder<'_>, form: TexelForm, x: SValue) -> BResu
}
/// The held AIR texel of image texel `x` (a `vec4` of the image's sampled type), read as one
/// texel: a `half` one converted by the bound format's class (`half`), a `float` one where the
/// read takes `float`; an 8-bit sRGB format's codes decoded by the device's transfer
/// (`SrgbEncode`, [`srgb_texel`]).
/// texel: a `half` one rounded to nearest even, a `float` one where the read takes `float`; an
/// 8-bit sRGB format's codes decoded by the device's transfer (`SrgbEncode`, [`srgb_texel`]).
fn from_image(
fb: &mut FunctionBuilder<'_>,
decl: &ImageDecl,
form: TexelForm,
x: SValue,
half: Option<HalfClass>,
) -> BResult<SValue> {
if r64(decl) {
return ulong_texel(fb, x);
@@ -1144,24 +1141,12 @@ fn from_image(
true => x_channel_read(fb, decl, x)?,
false => x,
};
// A `half` texel of a slot that converts by the bound format's class: a read's lanes are one
// texel's.
let x = match half {
Some(h) => {
let lanes = TexelLanes::Texel.value(fb)?;
h.convert(fb, x, lanes, TexelOrigin::Image)?
}
None => x,
};
let x = if form.lanes == 1 {
fb.composite_extract(x, &[0])?
} else {
x
};
match half {
Some(_) => Ok(x),
None => held_texel(fb, decl.held_class(), form, x),
}
held_texel(fb, decl.held_class(), form, x)
}
/// The held texel (`form`, a `half` or `float` result) of texel `x` (a `vec4` of `f32`) of an
@@ -1220,113 +1205,6 @@ pub(crate) const SRGB_TEXEL: [bool; 4] = [true, true, true, false];
pub(crate) const SRGB_DECODE_WORDS: u32 =
crate::lower::arith::pack::SRGB_DECODE_TEXEL_WORDS + 64 + 4 * 4 + 8;
/// The conversion of a slot's `half` texels by the bound format's class: the module's routine and
/// the slot's `TexelFormat` specialization constant; or of a heap color texture's by the class its
/// handle carries, read from the handle.
#[derive(Clone, Copy, Debug)]
pub(crate) struct HalfClass {
routine: FuncId,
class: ClassOf,
/// The slot's `PlainHalfTexels` specialization, where it declares one.
plain: Option<SValue>,
}
/// Where a [`HalfClass`]'s class comes from.
#[derive(Clone, Copy, Debug)]
enum ClassOf {
/// A slot's `TexelFormat` specialization constant.
Slot(ConstId),
/// A heap texture's class, read from its handle (`heap_texel_class`).
Heap(SValue),
}
impl HalfClass {
/// 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,
lanes: SValue,
origin: TexelOrigin,
) -> BResult<SValue> {
let class = match self.class {
ClassOf::Slot(c) => fb.module().const_value(c)?,
ClassOf::Heap(v) => v,
};
use crate::lower::arith::legal::{FloatFmt, Form, Held};
use crate::spirv::error::{BuildError, OperandRule};
let routine = self.routine;
let plain = match (origin, self.plain) {
(TexelOrigin::Image, Some(plain)) => plain,
_ => return super::half::convert(fb, routine, x, class, lanes),
};
let half = Form {
held: Held::Float(FloatFmt::Half),
lanes: 4,
};
let then: ArmFn<'_, ()> = Box::new(move |fb, _| {
let v = narrow::round_texel(fb, half, x)?;
Ok(ArmEnd::FallThrough(vec![v]))
});
let other: ArmFn<'_, ()> = Box::new(move |fb, _| {
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))?;
merged.first().copied().ok_or(BuildError::Operand {
op: crate::spv::Op::Phi,
rule: OperandRule::Arity,
})
}
}
/// How the `half` texels of a read, gather, or sample of `image` in form `texel` convert: by the
/// bound format's class where the slot takes its `TexelFormat` specialization, else (any other
/// result, a heap element, a depth texture) through [`held_texel`].
pub(crate) fn half_class(cx: &EmitCx<'_>, image: &ImageRef, texel: TexelForm) -> Option<HalfClass> {
if texel.conv != TexelConv::F16 {
return None;
}
let ImageRef::Slot(index) = *image else {
return None;
};
let t = &cx.decl.families.texture;
Some(HalfClass {
routine: t.half_routine?,
class: ClassOf::Slot(t.half_format.get(&index).copied()?),
plain: t.plain_half.get(&index).copied(),
})
}
/// How the `half` texels of a sample or gather of the heap color texture of handle `handle`
/// convert, in form `texel`: by the class the handle carries, read from it, where the module
/// defines the routine and the class table (`TexturePlan::heap_half`), else `None`.
pub(crate) fn heap_half_class(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
handle: ValueId,
texel: TexelForm,
) -> BResult<Option<HalfClass>> {
let t = &cx.decl.families.texture;
let (true, Some(routine), Some(_)) =
(texel.conv == TexelConv::F16, t.half_routine, t.heap_classes)
else {
return Ok(None);
};
let h = cx.operand(fb, handle)?;
let flags = heap_flags(cx, fb, h)?;
let class = super::heap_texel_class(cx, fb, flags)?;
Ok(Some(HalfClass {
routine,
class: ClassOf::Heap(class),
plain: None,
}))
}
/// The held AIR texel of `x`, `form.lanes` components of an image of sampled type `texel`: a
/// `half` rounded exactly, half subnormals and the decoded NaN kept (`narrow::round_texel`), a
/// signed integer bitcast to its held `u32`s, a 16-bit integer masked, and a `ulong` joined from
@@ -2784,10 +2662,7 @@ fn read_texel(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BR
// the device's transfer.
let texel = match r.raw {
true => srgb_texel(fb, r.texel, texel, SRGB_TEXEL)?,
false => {
let half = half_class(cx, &r.image, r.texel);
from_image(fb, &decl, r.texel, texel, half)?
}
false => from_image(fb, &decl, r.texel, texel)?,
};
// A swizzled texture's swizzle at a storage slot, on the converted texel.
let texel = match (r.storage_swizzle, r.image) {
@@ -1,181 +0,0 @@
//! 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 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`).
//!
//! **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.
//!
//! **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 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.
//!
//! 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::splat;
use crate::lower::arith::texel_round;
use crate::metal::texel_format::TexelFormat;
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::{BResult, BuildError, OperandRule};
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`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TexelOrigin {
/// An image instruction's texel (a read, fetch, sample or gather), or lanes and selections of
/// such texels and constants: no arithmetic computes it.
Image,
/// A value the translation computes from texels (an emulated filter's sum).
Computed,
}
/// 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
/// one level.
Texel,
/// Every lane channel `c` (0 red to 3 alpha) of its own texel: a 2D gather's.
Gathered(u32),
/// A value that may be filtered: a sample through a sampler that may filter, or a cube
/// gather (its corner texels are made up).
Filtered,
}
impl TexelLanes {
/// The routine's `channel` argument: the gathered channel, 4 for a texel, 5 for a value that
/// may be filtered.
pub fn code(self) -> u32 {
match self {
TexelLanes::Gathered(c) => c.min(3),
TexelLanes::Texel => TEXEL_LANES,
TexelLanes::Filtered => FILTERED_LANES,
}
}
/// The argument as a constant of `fb`'s module.
pub fn value(self, fb: &mut FunctionBuilder<'_>) -> BResult<SValue> {
let c = fb.u32_const(self.code())?;
fb.module().const_value(c)
}
}
/// The `channel` argument of one texel's lanes ([`TexelLanes::Texel`]).
pub const TEXEL_LANES: u32 = 4;
/// The `channel` argument of a value that may be filtered ([`TexelLanes::Filtered`]).
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 = 400;
/// 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.
pub const CENSUS_NAME: &str = "texture.half_texel";
fn fform() -> Form {
Form {
held: Held::Float(FloatFmt::F32),
lanes: 4,
}
}
/// The held form of a texel's four lanes as `half`s.
fn hform() -> Form {
Form {
held: Held::Float(FloatFmt::Half),
lanes: 4,
}
}
/// 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 vf = mb.ty(SType::Vector { elem: f32_, len: 4 })?;
let mut fb = mb.function(vf)?;
let x = fb.param(vf)?;
let flags = fb.param(u32_)?;
let channel = fb.param(u32_)?;
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 held `half` texel of image texel `x` (a `vec4` of `f32`), converted by `routine` under the
/// 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,
lanes: SValue,
) -> BResult<SValue> {
// Every call of the routine returns its texel.
fb.call(routine, &[x, flags, lanes])?
.ok_or(BuildError::Operand {
op: crate::spv::Op::FunctionCall,
rule: OperandRule::Callee,
})
}
+28 -272
View File
@@ -159,7 +159,6 @@ mod alpha;
mod atomic;
mod cooperative;
mod emit;
pub mod half;
pub(crate) mod heap_raw;
mod slice;
mod slot;
@@ -169,11 +168,10 @@ pub(crate) use absent::absent_arm;
pub use absent::ABSENT_ARM;
pub use atomic::TexAtomic;
pub(crate) use emit::{
constant_lanes, dispatch, half_class, heap_element, heap_flags, heap_half_class, heap_raw_form,
heap_raw_image, live_or_zero, reinterpret, resident_access, rgb9e5_word, slot_image,
sparse_spec, srgb_raw_tap, srgb_texel, swizzled_float, swizzled_gather, swizzled_held,
tile_map, tiled_word, with_word, HeapFlags, NullLeaf, TileLevel, RGB9E5_WORDS,
SRGB_DECODE_WORDS, SRGB_TAP_WORDS, SRGB_TEXEL,
constant_lanes, dispatch, heap_element, heap_flags, heap_raw_form, heap_raw_image,
live_or_zero, reinterpret, resident_access, rgb9e5_word, slot_image, sparse_spec, srgb_raw_tap,
srgb_texel, swizzled_float, swizzled_gather, swizzled_held, tile_map, tiled_word, with_word,
NullLeaf, TileLevel, RGB9E5_WORDS, SRGB_DECODE_WORDS, SRGB_TAP_WORDS, SRGB_TEXEL,
};
pub use emit::{emit, held_texel, to_image};
pub(crate) use slot::depth_comparison;
@@ -210,8 +208,8 @@ use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::sym::{SampledType, SlotClass, SlotRef};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{ConstId, DemoteTy, FuncId, GlobalId, TypeId, Value as SValue};
use crate::spirv::ir::{BinOp, ConstBits, ExecMode, GlslOp, MemAccess, Type as SType};
use crate::spirv::ids::{DemoteTy, FuncId, GlobalId, TypeId, Value as SValue};
use crate::spirv::ir::{ConstBits, ExecMode, Type as SType};
fn refuse() -> Error {
Unsupported::not_implemented(Feature::Lowering(LowerFamily::Texture)).into()
@@ -397,8 +395,8 @@ pub(crate) const HEAP_UNREADABLE_WORDS: u32 = 24 + crate::memory::handles::INDEX
/// the word's select outside the image, with its own in-bounds test where the shader has none; a
/// read through a sampler's addressing ([`Through::words`]), and a heap element's border texels
/// and the flags its uses then read from its handle-table entry
/// (`memory::handles::INDEXED_FLAGS_WORDS`); a `half` texel's call of the conversion routine or
/// exact rounding, or an sRGB texel's raw decode; the lanes Metal reads as constants; the
/// (`memory::handles::INDEXED_FLAGS_WORDS`); a `half` texel's exact rounding, or an sRGB texel's
/// raw decode; the lanes Metal reads as constants; the
/// reinterpretation of another class's words; and each sibling of a heap read with its class test
/// and branch, and a `half` read's merge of its arms' bits.
fn read_words(r: &Read) -> u32 {
@@ -440,8 +438,6 @@ fn read_words(r: &Read) -> u32 {
SRGB_DECODE_WORDS
} else if r.extended.is_some() {
crate::lower::arith::extended_range::DECODE_WORDS + r.texel.read_words()
} else if r.texel.conv == TexelConv::F16 {
half::CALL_WORDS.max(r.texel.read_words())
} else {
r.texel.read_words()
};
@@ -988,9 +984,6 @@ pub struct TexturePlan {
pub heap_groups: Option<HeapGroups>,
/// Every heap group an operation uses, by group.
pub heap: BTreeMap<u32, HeapPlan>,
/// Some heap color texture's sample or gather has a `half` result, which converts by the
/// class its handle carries (`emit::heap_half_class`): the module defines the `half` routine.
pub heap_half: bool,
/// The results of the heap reads that decode a member of a form a heap reads
/// (`ExtendedRange::HEAP_READ`): `false` a `float` one, `true` a `half` one. The module
/// defines that decode's routine for each ([`heap_raw::define`]).
@@ -1071,24 +1064,11 @@ pub struct Declared {
/// The tile map of each slot with a tile-map arm: a word view of its `ResourceKind::TileMap`
/// binding.
pub tile_maps: BTreeMap<u32, crate::memory::views::View>,
/// The `TexelFormat` specialization constant of each slot whose texels a read, gather, or
/// sample converts to a `half` result by the bound format's class.
pub half_format: BTreeMap<u32, ConstId>,
/// 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 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
/// `LoweringInputs::swizzled_storage` whose reads and writes apply the bound texture's, or
/// extended-range sampled slot of it whose reads, samples and gathers do.
pub swizzle: BTreeMap<u32, SValue>,
/// The module's table of heap texel classes (`metal::texel_format::heap_classes`), a `Private`
/// `uint[]`, where a heap handle carries its class's index (`AccessPlan::heap_class`):
/// [`heap_texel_class`] reads it.
pub heap_classes: Option<GlobalId>,
/// The module's routine decoding a heap member of a form a heap reads, for a `float` result
/// (`false`) and a `half` one (`true`), each where a read takes it ([`heap_raw::define`]).
pub heap_raw: BTreeMap<bool, FuncId>,
@@ -1336,37 +1316,16 @@ pub fn declare(
crate::memory::views::declare_at(mb, sym, crate::memory::views::ViewKind::Storage)?;
d.tile_maps.insert(*index, view);
}
if s.declares_texel_format() {
if s.texel_format {
let u32_ = mb.ty(SType::Int {
width: 32,
signed: false,
})?;
let c = mb.spec(
mb.spec(
crate::pipeline::sym::SpecKey::TexelFormat(s.slot),
u32_,
ConstBits(u64::from(crate::metal::texel_format::TexelFormat::OTHER.0)),
)?;
d.half_format.insert(*index, c);
}
if s.unmeasured {
let b = mb.ty(SType::Bool)?;
mb.spec(
crate::pipeline::sym::SpecKey::UnmeasuredTexels(s.slot),
b,
ConstBits(0),
)?;
}
if s.half_format && d.half_routine.is_none() {
d.half_routine = Some(half::define(mb)?);
}
if s.half_format {
let b = mb.ty(SType::Bool)?;
let c = mb.spec(
crate::pipeline::sym::SpecKey::PlainHalfTexels(s.slot),
b,
ConstBits(1),
)?;
d.plain_half.insert(*index, mb.const_value(c)?);
}
if s.swizzle {
let u32_ = mb.ty(SType::Int {
@@ -1431,98 +1390,9 @@ pub fn declare(
for &half in &plan.families.texture.heap_raw {
d.heap_raw.insert(half, heap_raw::define(mb, half)?);
}
if plan.families.access.heap_class {
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)?);
}
Ok(d)
}
/// Declare the module's table of heap texel classes: a `Private` `uint[N]` initialized with
/// `metal::texel_format::heap_classes`, whose element `i` is the class index `i` names.
fn declare_heap_classes(mb: &mut ModuleBuilder) -> BResult<GlobalId> {
let classes = crate::metal::texel_format::heap_classes();
let u32_ = mb.ty(SType::Int {
width: 32,
signed: false,
})?;
let len = mb.constant(crate::spirv::ir::Constant::Scalar {
ty: u32_,
bits: ConstBits(classes.len() as u64),
})?;
let arr = mb.ty(SType::Array {
elem: u32_,
len,
stride: None,
})?;
let mut parts = Vec::with_capacity(classes.len());
for &class in classes {
parts.push(mb.constant(crate::spirv::ir::Constant::Scalar {
ty: u32_,
bits: ConstBits(u64::from(class)),
})?);
}
let init = mb.constant(crate::spirv::ir::Constant::Composite {
ty: arr,
parts: parts.into(),
})?;
mb.plain_global(crate::spirv::ir::StorageClass::Private, arr, Some(init))
}
/// The words [`heap_texel_class`] emits, at most: the field's shift and mask, the clamp into the
/// table, the access chain and the load, with their constants.
pub(crate) const HEAP_CLASS_WORDS: u32 = 48;
/// The words of the module's table of heap texel classes, counted once: a constant per class, the
/// composite, the array type, and the variable.
pub(crate) fn heap_classes_words() -> u64 {
16 + 4 * crate::metal::texel_format::heap_classes().len() as u64
}
/// The texel class (`metal::texel_format::TexelFormat`'s bits, a `u32`) of the heap texture
/// whose handle's flags are `h` ([`heap_flags`]), of a module whose search carries the class's
/// index ([`HANDLE_TEXEL_CLASS`](crate::memory::handles::HANDLE_TEXEL_CLASS)): the module's
/// table's element at that index, clamped into the table. A null handle's, or a missed id's, is
/// index 0, `TexelFormat::OTHER`.
pub(crate) fn heap_texel_class(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
HeapFlags(h): HeapFlags,
) -> BResult<SValue> {
use crate::memory::handles::HANDLE_TEXEL_CLASS;
let Some(table) = cx.decl.families.texture.heap_classes else {
return Err(cx.fail("a heap texel class without the module's table"));
};
let u32_ = fb.module().ty(SType::Int {
width: 32,
signed: false,
})?;
let k = |fb: &mut FunctionBuilder<'_>, v: u32| -> BResult<SValue> {
let c = fb.module().constant(crate::spirv::ir::Constant::Scalar {
ty: u32_,
bits: ConstBits(u64::from(v)),
})?;
fb.module().const_value(c)
};
let shift = k(fb, HANDLE_TEXEL_CLASS.trailing_zeros())?;
let mask = k(
fb,
HANDLE_TEXEL_CLASS >> HANDLE_TEXEL_CLASS.trailing_zeros(),
)?;
let last = crate::metal::texel_format::heap_classes()
.len()
.saturating_sub(1);
let last = k(fb, u32::try_from(last).unwrap_or(0))?;
let index = fb.binary(BinOp::ShiftRightLogical, h, shift)?;
let index = fb.binary(BinOp::BitwiseAnd, index, mask)?;
let index = fb.glsl(GlslOp::UMin, &[index, last])?;
let base = fb.module().global_value(table)?;
let at = fb.access_chain(base, &[index])?;
fb.load(at, MemAccess::default())
}
/// The set-1 runtime array of heap class `class`, of `decl`'s image type, for stage `stage`.
fn heap_array(
mb: &mut ModuleBuilder,
@@ -1639,85 +1509,6 @@ pub(crate) fn residency(cx: &mut SelectCx<'_>, at: InstId, image: ImageRef) -> R
}
}
/// Whether an access with a `float` or `half` result reads one texel of one level, its value a
/// texel's channels the device converted from their codes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum OneTexel {
/// Always: a read, a 2D gather, a pixel fetch, or a sample through a constexpr sampler that
/// reads one texel of one level (`lower::sampler::linear::unfiltered`).
Always,
/// Never: a sample through a constexpr sampler that filters, a bicubic sample, or a cube
/// gather (whose corner texels are made up).
Never,
/// Where runtime sampler slot `n`'s word states a sampler that reads one texel of one level
/// (its `SamplerState` specialization's filter fields, `SamplerWord::LINEAR_FILTER`).
Word(u32),
/// Where an argument buffer's sampler's word, its table entry's flags for handle `h`, states
/// one; no specialization decides it.
Heap(ValueId),
/// Where the word of the constexpr sampler at the element of a constexpr sampler array (of
/// this many elements) that the sampling's sampler handle names
/// (`lower::sampler::Source::HeapArray`, `ConstexprArray::words`) states one.
Table(u32),
}
/// 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 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,
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,
_ => {
cx.precision.insert(PrecisionNote::HalfTexelConversion);
return Ok(());
}
};
// 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(),
];
// A sample of a 32-bit float texel.
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;
}
cx.facts
.insert(crate::pipeline::facts::RuntimeFact::TexelFormat { slot });
Ok(())
}
/// Record that a `half` read, sample or gather of `image`, of shape `shape`, hands back the
/// device's decode of a NaN texel: `PrecisionNote::DeviceNanEncoding`. Of a color texture slot,
/// only where the class of the format bound there may hold a NaN (none of `TexelFormat::NAN_FREE`'s
@@ -1750,17 +1541,16 @@ pub(crate) fn half_texel_nans(
}
/// Record what a read, gather, or sample of `image`, of shape `shape`, with a `float` result that
/// may read one texel (`one` not [`OneTexel::Never`]) answers on a profile without Metal's own
/// sampler (`VkProperty::MetalSampler`, whose device value is Metal's): the device's conversion of
/// the texel's codes, `PrecisionNote::DeviceTexelConversion`; of a heap's texture buffer, which no
/// class reaches, a half-float texel's NaN the device's decode, `PrecisionNote::DeviceNanEncoding`.
/// may read one texel (`one`) answers: the device's conversion of the texel's codes,
/// `PrecisionNote::DeviceTexelConversion`; of a heap's texture buffer, which no class reaches, a
/// half-float texel's NaN the device's decode, `PrecisionNote::DeviceNanEncoding`.
pub(crate) fn float_texel_notes(
cx: &mut SelectCx<'_>,
image: ImageRef,
shape: ImageShape,
one: OneTexel,
one: bool,
) {
if one == OneTexel::Never || !device_texels(cx) {
if !one {
return;
}
let note = match image.heap() && shape.dim == ImageDim::Buffer {
@@ -1770,18 +1560,6 @@ pub(crate) fn float_texel_notes(
cx.precision.insert(note);
}
/// Whether an access's `float` or `half` texel is the device's conversion: on a profile whose
/// device does not sample through Metal's own texture unit (`VkProperty::MetalSampler`, whose value
/// is Metal's and keeps the conversion). Every access of a kind agrees: the selection states a
/// sample's `half` conversion on the access (`Sampling::half_texel`), which the emission follows.
pub(crate) fn device_texels(cx: &SelectCx<'_>) -> bool {
!cx.profile
.fields()
.enabled
.properties
.contains(&crate::device::requirements::VkProperty::MetalSampler)
}
/// 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,
@@ -1819,9 +1597,7 @@ pub(crate) fn constexpr_address_map(
/// sRGB view: the module records `PrecisionNote::SrgbTexelDecode` where the bound format's class
/// is an sRGB one (`BicubicTexels::SRGB`, a test of the bound format that the runtime announces at
/// a draw or dispatch binding such a texture), and outright for a heap element, whose format is
/// never known. On a device that decodes through Metal's own texture unit
/// (`VkProperty::MetalSampler`: MoltenVK on Apple's GPU) the device's decode is Metal's, so the
/// module requires the property there instead of the note.
/// never known.
pub(crate) fn srgb_texels(
cx: &mut SelectCx<'_>,
image: ImageRef,
@@ -1857,23 +1633,15 @@ pub(crate) fn srgb_texels(
/// An access that reads the device's decode of a texture that may be bound in an 8-bit sRGB
/// format ([`srgb_texels`]): `PrecisionNote::SrgbTexelDecode` where texture slot `index` is bound
/// in such a format, or outright for a heap element (`None`); on a device that decodes through
/// Metal's own texture unit, the requirement of `VkProperty::MetalSampler` instead.
/// in such a format, or outright for a heap element (`None`).
fn device_decode(cx: &mut SelectCx<'_>, index: Option<u32>, m: &mut Meter) -> Result<(), Error> {
use crate::metal::bicubic::BicubicTexels as B;
let metal = cx
.profile
.fields()
.enabled
.properties
.contains(&crate::device::requirements::VkProperty::MetalSampler);
match (metal, index) {
(true, _) => cx.families.sampler.metal_sampler = true,
(false, Some(index)) => {
match index {
Some(index) => {
let srgb = NoteTest::equal(NoteOn::Bound(index), B::SRGB, B::SRGB);
cx.note_when(PrecisionNote::SrgbTexelDecode, vec![[srgb].into()], m)?;
}
(false, None) => {
None => {
cx.precision.insert(PrecisionNote::SrgbTexelDecode);
}
}
@@ -2154,10 +1922,7 @@ fn heap_group(cx: &mut SelectCx<'_>, tex: Value, m: &mut Meter) -> Result<u32, E
/// heap operation masks its handle to its element (an `OpBitwiseAnd`), and a read that selects the
/// out-of-bounds alpha also tests that flag (an `OpBitwiseAnd` and an `OpINotEqual`), with their
/// constants once; the census's for the strategy that asks for them, `texture.read_clamped.heap`
/// where the alpha is carried, else [`HEAP_CLASS_CENSUS`]; with the module's table of heap texel classes
/// ([`heap_classes_words`]) under [`HEAP_CLASS_CENSUS`] where a sample reads it. And the words of
/// the `half` conversion routine (`half`), the census's for [`half::CENSUS_NAME`], where a slot
/// takes it.
/// where the alpha is carried, else [`HEAP_CLASS_CENSUS`].
pub fn routine_words(
texture: &TexturePlan,
access: &crate::lower::access::AccessPlan,
@@ -2170,15 +1935,6 @@ pub fn routine_words(
};
(name, words)
});
let classes = access
.heap_class
.then(|| (HEAP_CLASS_CENSUS, heap_classes_words()));
// The `half` conversion routine, once per module that defines it.
let half = texture
.slots
.values()
.any(|s| s.half_format)
.then_some((half::CENSUS_NAME, half::ROUTINE_WORDS));
// The heap's raw decode, once per result type.
let raw = (!texture.heap_raw.is_empty()).then(|| {
(
@@ -2186,11 +1942,11 @@ pub fn routine_words(
heap_raw::ROUTINE_WORDS * texture.heap_raw.len() as u64,
)
});
flags.into_iter().chain(classes).chain(half).chain(raw)
flags.into_iter().chain(raw)
}
/// The census name of the words a heap texel class costs: the module's table of classes and, where
/// no other flag is carried, the masks of the heap handles.
/// The census name of the words a heap texel class costs: where no other flag is carried, the masks
/// of the heap handles.
pub const HEAP_CLASS_CENSUS: &str = "sampler.heap.texel_class";
/// What a `float` write to texture `image` (of storage class `class`) relies on or records where it
@@ -2982,8 +2738,7 @@ pub(crate) fn mark_result(cx: &mut SelectCx<'_>, image: ImageRef, form: TexelFor
/// bound to a swizzled texture: the function applies the swizzle to the texels it reads there
/// and undoes it on those it writes; or an extended-range sampled slot bound to one, whose decoded
/// texels the function's reads, samples and gathers swizzle; or a packed normalized sampled slot
/// bound to one on a device without Metal's own sampler, whose converted texels they swizzle. A
/// heap element never is.
/// bound to one, whose converted texels they swizzle. A heap element never is.
pub(crate) fn swizzled_storage(cx: &SelectCx<'_>, image: ImageRef) -> Result<bool, Error> {
let ImageRef::Slot(index) = image else {
return Ok(false);
@@ -3444,12 +3199,13 @@ fn select_read_as(
// decoded exactly to `f32`, which a `half` result rounds to nearest even, as Metal answers. A
// read is one texel.
let decoded = raw || srgb_codes || words;
// A `half` texel is the device's `f32` texel rounded to nearest even.
if texel.conv == TexelConv::F16 && !decoded && extended.is_none() {
half_texels(cx, image, shape, false, device_texels(cx), m)?;
cx.precision.insert(PrecisionNote::HalfTexelConversion);
half_texel_nans(cx, image, shape, m)?;
}
if texel.conv == TexelConv::F32 && !decoded && extended.is_none() {
float_texel_notes(cx, image, shape, OneTexel::Always);
float_texel_notes(cx, image, shape, true);
}
// A float read of a sampled heap group of one sample decodes a member of a form a heap reads
// where its handle names one, from the group's unsigned integer class.
+3 -22
View File
@@ -238,19 +238,9 @@ pub struct SlotPlan {
/// function's writes to a sparse texture (`RuntimeFact::SparseTextureWrites`), set by
/// [`finish`].
pub sparse_writes: bool,
/// A read, gather, or sample converts the slot's texels to a `half` result by the bound
/// format's class, which the slot's `TexelFormat` specialization gives
/// (`RuntimeFact::TexelFormat`, `half`).
pub half_format: bool,
/// The slot declares its `TexelFormat` specialization without the conversion routine: a raw
/// linear sample reads the bound format's channels from it (`RuntimeFact::TexelFormat`).
/// Implied by `half_format`.
/// The slot declares its `TexelFormat` specialization: a raw linear sample reads the bound
/// format's channels from it (`RuntimeFact::TexelFormat`).
pub texel_format: 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`
/// specialization, which the note's clause tests.
pub unmeasured: bool,
/// A read of the slot, a texture buffer, applies the bound texture buffer's swizzle, which
/// the slot's `TextureSwizzle` specialization gives (`RuntimeFact::TextureSwizzle`); or the
/// slot, a storage slot of `LoweringInputs::swizzled_storage`, applies the bound texture's to
@@ -298,9 +288,7 @@ impl SlotPlan {
sparse_arm: false,
tile_map: false,
sparse_writes: false,
half_format: false,
texel_format: false,
unmeasured: false,
swizzle: false,
constant_lanes: false,
offset_base: false,
@@ -311,12 +299,6 @@ impl SlotPlan {
}
}
/// Whether the slot declares its `TexelFormat` specialization: a conversion by the bound
/// format's class takes it.
pub fn declares_texel_format(&self) -> bool {
self.half_format || self.texel_format
}
/// Whether the slot is a storage image or storage texel buffer.
pub fn storage(&self) -> bool {
matches!(self.access, AbiAccess::Write | AbiAccess::ReadWrite)
@@ -1772,8 +1754,7 @@ impl SlotPlan {
let state = self.sparse_arm
|| self.tile_map
|| self.sparse_writes
|| self.declares_texel_format()
|| self.unmeasured
|| self.texel_format
|| self.swizzle
|| self.constant_lanes
|| self.offset_base;
+7 -10
View File
@@ -409,14 +409,13 @@ pub const FLAG_OUT_OF_BOUNDS_ALPHA_ONE: u32 = 1 << 1;
/// (`bind::heap::storage_conversions`). A handle carries it beside its class
/// ([`HANDLE_RED_BLUE`]).
pub const FLAG_RED_BLUE: u32 = 1 << 2;
/// The field of a texture entry's flags holding the index of its texel class in
/// `metal::texel_format::heap_classes`: the class a slot bound to the texture would state in its
/// `TexelFormat` specialization, `OTHER` (index 0) for a swizzled texture, by which a function
/// converts or reads the texture's texels where the module reads it (a `half` conversion on Metal's
/// own sampler, a fetched gather, a NaN texel's rule, a raw-held form's emulation). A heap handle
/// carries it in place, in a module whose search carries it ([`Lookup::Flagged`]'s `class`), so
/// [`HANDLE_TEXEL_CLASS`] is this field. Its 12 bits hold every index
/// (`metal::texel_format::heap_classes` has fewer than 4096 classes, which a test checks).
/// The field of a texture entry's flags holding the index of its texel class in the heap's layout
/// (`metal::texel_format::heap_class_index`): the class a slot bound to the texture would state in
/// its `TexelFormat` specialization, `OTHER` (index 0) for a swizzled texture, by which a function
/// converts or reads the texture's texels where the module reads it (a fetched gather, a NaN
/// texel's rule, a raw-held form's emulation). A heap handle carries it in place, in a module whose
/// search carries it ([`Lookup::Flagged`]'s `class`), so [`HANDLE_TEXEL_CLASS`] is this field. Its
/// 12 bits hold every index `metal::texel_format::heap_class_index` gives, which a test checks.
pub const FLAG_TEXEL_CLASS: u32 = 0xfff << 16;
/// The flag of a texture entry whose view in the heap's storage arrays (`bind::heap`) a device
/// that reads storage without a format by the formats' own bits alone cannot read so: the view's
@@ -2047,8 +2046,6 @@ mod tests {
#[test]
fn every_texel_class_index_fits_its_field() {
let field = FLAG_TEXEL_CLASS >> FLAG_TEXEL_CLASS.trailing_zeros();
let classes = crate::metal::texel_format::heap_classes().len();
assert!(classes <= field as usize + 1, "{classes} classes");
for &pf in crate::metal::PixelFormat::ALL {
let index = crate::metal::texel_format::heap_class_index(
pf,
+5 -4
View File
@@ -479,10 +479,11 @@ impl ExtendedRange {
)
}
/// The forms an argument buffer's texture is read in (a heap element), in the order their
/// classes follow `metal::texel_format::heap_classes`' own: a function decodes such a texture's
/// raw texels, read through the heap's unsigned integer array. A heap holds no `_sRGB` form
/// (their heap classes are not built) and no two-plane form, which is held in two planes.
/// The forms an argument buffer's texture is read in (a heap element), in the order their heap
/// class indices follow (`metal::texel_format::heap_extended_base`): a function decodes such a
/// texture's raw texels, read through the heap's unsigned integer array. A heap holds no
/// `_sRGB` form (their heap classes are not built) and no two-plane form, which is held in two
/// planes.
pub const HEAP_READ: [ExtendedRange; 7] = [
ExtendedRange::Bgr10 { srgb: false },
ExtendedRange::Bgra10 { srgb: false },
@@ -1191,7 +1191,7 @@ fn swizzled_views_read_metal_s_opaque_black_border() {
| FormatEmulation::AlphaInRed
)
}) {
let device = crate::metal::sampler::device_opaque_black(c.format, c.components, false);
let device = crate::metal::sampler::device_opaque_black(c.components);
// Metal's: alpha 1, the color's or a missing channel's, but `A8Unorm`'s, the red,
// and `ARGB8Unorm`'s, whose border passes through its byte rotation: blue 1
// (measured on the M3 Max, and an M4).
+21 -54
View File
@@ -450,15 +450,12 @@ pub(crate) fn vk_filtering(
/// (`DeviceProperties::supports_sampler_reduction_mode`).
///
/// Without a mip filter it reads the base level, and its clamp keeps Metal's choice between the
/// two filters (`not_mipmapped_lods`); through Metal's own sampler with anisotropy and equal
/// filters its clamp is `[0, 0]`, where that sampler reads Metal's `NotMipmapped`. With filters
/// that differ there, no clamp reads Metal's answer.
/// two filters (`not_mipmapped_lods`).
///
/// 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.
/// into it and selects and blends levels at its own precision (`PrecisionNote::DeviceSampling`).
/// 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.
///
/// Its `mipLodBias` follows the GPU the device presents ([`SamplerUse::lod_bias`]). Vulkan adds
/// `mipLodBias` to every sample's level, an explicit one's included (the specification's
@@ -528,25 +525,8 @@ pub fn vk_sampler(
} else {
vk::SamplerMipmapMode::LINEAR
};
// 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)
// changes Metal's anisotropic footprint (an Apple M3 Max on macOS 27.0.1, the anisotropic
// lane's 1268 footprints at `maxAnisotropy` 2, 8 and 16, gradients scaled by 1 to 1/32,
// linear and nearest filters, clamps from `[0, 0.25]` to `[3, 8]`: every channel Metal's).
// Equal filters leave the device's level no filter to choose.
let own_anisotropic = max_anisotropy.is_some()
&& desc.min_filter == desc.mag_filter
&& profile
.fields()
.enabled
.properties
.contains(&VkProperty::MetalSampler);
let (mipmap_mode, min_lod, max_lod) = match desc.mip_filter {
_ if use_.unnormalized => (vk::SamplerMipmapMode::NEAREST, 0.0, 0.0),
SamplerMipFilter::NotMipmapped if own_anisotropic => {
(vk::SamplerMipmapMode::NEAREST, 0.0, 0.0)
}
SamplerMipFilter::NotMipmapped => {
let (min_lod, max_lod) = not_mipmapped_lods(lo, hi);
(vk::SamplerMipmapMode::NEAREST, min_lod, max_lod)
@@ -675,10 +655,9 @@ pub fn check_border_swizzle(
/// missing red, green or blue 0 and a missing alpha 1, then the swizzle (`border_texel`). Vulkan
/// replaces a border texel in the view format's channels, opaque black's alpha 1 in every format,
/// `A8_UNORM`'s included, and the view's mapping (the swizzle composed on `mapping`'s,
/// [`TextureSwizzleChannels::compose`]) applies to it as to any texel; a device that samples
/// through Metal's own sampler (`VkProperty::MetalSampler`, MoltenVK) replaces it by Metal's
/// rule. Transparent-black and opaque-white borders are defined through any mapping and read
/// Metal's texel. An **opaque-black** border is exact only when:
/// [`TextureSwizzleChannels::compose`]) applies to it as to any texel. Transparent-black and
/// opaque-white borders are defined through any mapping and read Metal's texel. An **opaque-black**
/// border is exact only when:
///
/// - the device's texel through the view is Metal's. `A8Unorm` through `A8_UNORM` reads alpha 1
/// where Metal reads 0 (measured on RADV, ANV, NVIDIA and lavapipe); there Metal's opaque-black
@@ -690,8 +669,7 @@ pub fn check_border_swizzle(
/// otherwise an implementation may swap alpha with red or blue for the built-in border colors,
/// as Apple GPUs do through their channel-reordered hardware format (Vulkan spec "Texel
/// Replacement"). A custom border color would not swap; the binder creates none (handed back);
/// - read through a mapping other than the identity, the device samples through Metal's sampler
/// (measured exact through six swizzles), or `borderColorSwizzle` and
/// - read through a mapping other than the identity, `borderColorSwizzle` and
/// `borderColorSwizzleFromImage` are enabled (the binder chains no
/// `VkSamplerBorderColorComponentMappingCreateInfoEXT`, whose mapping would have to match every
/// view the sampler meets). Without them Vulkan leaves the texel undefined: NVIDIA, which lacks
@@ -762,7 +740,6 @@ fn border_read(
mapped: bool,
) -> Result<OpaqueBlackBorder, Error> {
let f = profile.fields();
let metal_sampler = f.enabled.properties.contains(&VkProperty::MetalSampler);
let swapped = matches!(
mapping.format,
vk::Format::R4G4B4A4_UNORM_PACK16 | vk::Format::B4G4R4A4_UNORM_PACK16
@@ -773,11 +750,11 @@ fn border_read(
let rgba4 = swapped.then_some(Capability::Property(VkProperty::Rgba4OpaqueBlackSwizzled));
let metal = black_texel(pf, swizzle, BORDER_COLORS[1]);
let view = swizzle.compose(mapping.components);
if device_opaque_black(mapping.format, view, metal_sampler) != metal {
if device_opaque_black(view) != metal {
let unswizzled = swizzle.compose(vk::ComponentMapping::IDENTITY);
let Some(direct) = direct_format(pf).filter(|&d| {
d != mapping.format && device_opaque_black(d, unswizzled, metal_sampler) == metal
}) else {
let Some(direct) = direct_format(pf)
.filter(|&d| d != mapping.format && device_opaque_black(unswizzled) == metal)
else {
return Err(Unsupported::not_implemented(Feature::SamplerBorderColor).into());
};
let need = format_exposure_gap(direct, f.api_version, &f.enabled.extensions)
@@ -793,7 +770,6 @@ fn border_read(
// Through another mapping Vulkan defines the texel only with the border-swizzle features:
// the view's own (`FromImage`), or the sampler's (`Mapped`).
let read = if is_identity(view)
|| metal_sampler
|| (has(&VkFeature::BorderColorSwizzle) && has(&VkFeature::BorderColorSwizzleFromImage))
{
OpaqueBlackBorder::Stated
@@ -845,15 +821,9 @@ fn black_texel(pf: PixelFormat, swizzle: TextureSwizzleChannels, color: [bool; 4
/// The device's opaque-black border texel through a view of `format` with mapping `view`: Vulkan
/// replaces the texel in `format`'s channels with `(0, 0, 0, 1)`, a missing alpha 1 and
/// `A8_UNORM`'s alpha 1 too (measured); a device sampling through Metal's sampler (`metal_sampler`)
/// reads `A8_UNORM`'s alpha from the color's red, 0. Then the mapping.
pub(crate) fn device_opaque_black(
format: vk::Format,
view: vk::ComponentMapping,
metal_sampler: bool,
) -> [bool; 4] {
let alpha = !(metal_sampler && format == vk::Format::A8_UNORM);
through(view, [false, false, false, alpha])
/// `A8_UNORM`'s alpha 1 too (measured). Then the mapping.
pub(crate) fn device_opaque_black(view: vk::ComponentMapping) -> [bool; 4] {
through(view, [false, false, false, true])
}
/// `texel` (`[r, g, b, a]`, each 0 or 1) read through mapping `m`.
@@ -1694,10 +1664,8 @@ mod tests {
}
}
/// Through Metal's own sampler, an anisotropic sampler without a mip filter whose filters
/// agree is clamped to `[0, 0]` whatever its clamps, where that sampler reads Metal's
/// `NotMipmapped`; one whose filters differ, an isotropic one, and every sampler off Metal's
/// sampler keep the clamp that chooses Metal's filter.
/// A comparison sampler takes the descriptor's filters, mip mode, clamps and compare op; the
/// same descriptor without comparison takes no compare op; a NaN or inverted clamp is refused.
#[test]
fn filters_lods_and_compare() {
let dev = device(&[], &[]);
@@ -1789,8 +1757,8 @@ mod tests {
}
}
/// A sampler with a nearest min or mag filter is handed its degree, through Metal's sampler and
/// natively alike, as one with linear filters is.
/// A sampler with a nearest min or mag filter is handed its degree, as one with linear filters
/// is.
#[test]
fn a_nearest_filter_is_handed_its_anisotropy() {
use SamplerMinMagFilter::{Linear, Nearest};
@@ -2376,15 +2344,14 @@ mod tests {
a: S::A,
};
let black = BORDER_COLORS[1];
let rgba = vk::Format::R8G8B8A8_UNORM;
assert!(is_identity(own) && device_opaque_black(rgba, own, false) == black);
assert!(is_identity(own) && device_opaque_black(own) == black);
let splat = vk::ComponentMapping {
r: S::A,
g: S::A,
b: S::A,
a: S::A,
};
assert!(!is_identity(splat) && device_opaque_black(rgba, splat, false) == [true; 4]);
assert!(!is_identity(splat) && device_opaque_black(splat) == [true; 4]);
}
/// A sampler's word holds each descriptor field's raw Metal value at its own bits, so
+27 -174
View File
@@ -109,8 +109,7 @@
//! EOTF to the codes before filtering, within the device's precision), and that is the only form
//! wherever the device samples the format: a texture slot's reads, samples, gathers and bicubic
//! taps take it, recording `PrecisionNote::SrgbTexelDecode` where the bound format's class has
//! [`SRGB`](BicubicTexels::SRGB) on a device that does not decode through Metal's own texture
//! unit (`VkProperty::MetalSampler`, whose decode is Metal's). The class is
//! [`SRGB`](BicubicTexels::SRGB). The class is
//! [`UNORM`](BicubicTexels::UNORM) and [`SRGB`](BicubicTexels::SRGB) with its channels, never
//! [`EXACT`](BicubicTexels::EXACT): a `half` result rounds the device's `float` value, and a
//! bicubic sample sums the device's decoded taps. The formats ([`srgb_coded`]) are
@@ -184,42 +183,6 @@ impl TexelFormat {
/// The [`PACKED`](Self::PACKED) field's mask, in place.
pub const PACKED_MASK: u32 = 0xF << TexelFormat::PACKED;
/// The [`PACKED`](Self::PACKED) field's top bit, set in exactly the fields of the grid `8192`
/// ([`PackedTexels::YCbCr8192`], [`PackedTexels::YCbCrExtended8192`] and
/// [`PackedTexels::Rgb10A2Srgb`]), whose one texel's `half` rounds with ties away from zero: what the `half` routine of a device that
/// samples through Metal's own texture unit reads of the field (`lower::texture::half`), so
/// that every other field's class specializes as a slot bound to nothing does.
pub const YCBCR_8192: u32 = 8 << TexelFormat::PACKED;
/// The bits of a class whose `half` conversion is measured on a device that samples through
/// Metal's own texture unit: a measured family ([`BicubicTexels::LINEAR`],
/// [`BicubicTexels::HALF`], [`BicubicTexels::EXACT`]), an 8-bit sRGB format's
/// ([`BicubicTexels::SRGB`]) or a packed field. A class with none of them
/// ([`unmeasured_on_metal_sampler`](Self::unmeasured_on_metal_sampler)) converts by the
/// `OTHER` arm, whose rounding of Metal's `float` texel Metal's `half` may not be.
pub const MEASURED_ON_METAL_SAMPLER: u32 = BicubicTexels::LINEAR
| BicubicTexels::HALF
| BicubicTexels::EXACT
| BicubicTexels::SRGB
| TexelFormat::PACKED_MASK;
/// Whether the class has none of [`MEASURED_ON_METAL_SAMPLER`](Self::MEASURED_ON_METAL_SAMPLER)'s
/// bits: a format outside the measured families, or a swizzled packed normalized format
/// ([`swizzled`](Self::swizzled)), whose `half` conversion the module notes on such a device
/// (`SpecKey::UnmeasuredTexels`).
pub fn unmeasured_on_metal_sampler(self) -> bool {
self.0 & TexelFormat::MEASURED_ON_METAL_SAMPLER == 0
}
/// 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 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 & TexelFormat::YCBCR_8192 == 0
}
/// The families whose texels decode to no NaN: normalized channels, signed or not
/// ([`BicubicTexels::UNORM`], [`BicubicTexels::SNORM`]), 8-bit sRGB codes
/// ([`BicubicTexels::SRGB`]) and Apple's extended-range codes ([`BicubicTexels::EXTENDED`]).
@@ -232,15 +195,6 @@ impl TexelFormat {
pub const NAN_FREE: u32 =
BicubicTexels::UNORM | BicubicTexels::SNORM | BicubicTexels::SRGB | BicubicTexels::EXTENDED;
/// Whether the class's [`PACKED`](Self::PACKED) field is a two-plane YCbCr format's
/// ([`PackedTexels::ycbcr`]): a texture Metal's own sampler filters as a float texture's
/// texels, not on the field's grid (`lower::sampler::linear`).
pub(crate) fn two_plane_ycbcr(self) -> bool {
PackedTexels::ALL
.iter()
.any(|p| p.ycbcr() && self.0 & TexelFormat::PACKED_MASK == p.class().0)
}
/// Whether the class states channels ([`BicubicTexels::PRESENT`]): a measured family's does,
/// a [`CubeCorner`] alone does not, so the binder states no border texel for it.
pub fn has_channels(self) -> bool {
@@ -658,7 +612,7 @@ pub fn with_border(pf: PixelFormat, swizzle: TextureSwizzleChannels) -> TexelFor
/// The class a heap texture of pixel format `pf` made with `swizzle` carries in its handle-table
/// entry: a texture without a swizzle takes its slot's class ([`with_border`]); a swizzled one
/// takes [`TexelFormat::OTHER`], whose texels the function leaves to the device, so the classes a
/// heap names are [`heap_classes`]' few.
/// heap names are few.
pub fn heap_class(pf: PixelFormat, swizzle: TextureSwizzleChannels) -> TexelFormat {
match reads_unswizzled(pf, swizzle) {
true => with_border(pf, swizzle),
@@ -686,30 +640,22 @@ pub fn reads_unswizzled(pf: PixelFormat, swizzle: TextureSwizzleChannels) -> boo
(0..4).all(|c| sources[c] == own[c] || (!present[c] && sources[c] == lacking[c]))
}
/// Every class a heap texture can carry ([`heap_class`] of each pixel format without a swizzle),
/// sorted and without repeats, so [`TexelFormat::OTHER`] (0) is first: a texture's handle-table
/// entry names its class by its index here ([`heap_class_index`]), which a function reading the
/// class looks up in its own copy of this table. The binder and the function come from one build,
/// whose `SEMANTICS_VERSION` changes with any class.
/// The heap's class layout. First every class a heap texture can carry ([`heap_class`] of each
/// pixel format without a swizzle), sorted and without repeats, so [`TexelFormat::OTHER`] (0) is
/// first: a texture's handle-table entry names its class by its index here ([`heap_class_index`]).
/// The binder and the function come from one build, whose `SEMANTICS_VERSION` changes with any
/// class.
///
/// After them, from [`heap_extended_base`], one [`TexelFormat::OTHER`] per form of
/// `ExtendedRange::HEAP_READ` in its order: the index of a heap texture of that form, whose texels
/// a function decodes from its raw codes where the index names it, and which every routine that
/// reads the class takes as `OTHER`.
/// a function decodes from its raw codes where the index names it.
///
/// After those, from [`heap_numeric_base`], two more `OTHER` entries: the index of a heap texture
/// of a signed and of an unsigned integer color format ([`heap_numeric`]), which a read of another
/// numeric class tests to read the texture in its own class; then, from the own-only base, the
/// classes of the formats such a read does not take ([`crosses_classes`]: depth, stencil,
/// extended-range and two-plane formats), sorted, `OTHER` first, each the class of its own: a float
/// read's routine takes it as the class of the same value among the own ones, and only a crossing
/// float format's texture names an own class.
pub fn heap_classes() -> &'static [u32] {
&heap_layout().classes
}
/// [`heap_classes`] and the indices where its parts start: the forms a heap reads, the numeric
/// markers, and the classes of the formats no read of another class takes.
/// extended-range and two-plane formats), sorted, `OTHER` first, each the class of its own, so only
/// a crossing float format's texture names an own class.
struct HeapLayout {
classes: Vec<u32>,
extended: u32,
@@ -717,7 +663,7 @@ struct HeapLayout {
own_only: u32,
}
/// The heap's classes ([`heap_classes`]), built once.
/// The heap's class layout ([`HeapLayout`]), built once.
fn heap_layout() -> &'static HeapLayout {
static LAYOUT: std::sync::OnceLock<HeapLayout> = std::sync::OnceLock::new();
LAYOUT.get_or_init(|| {
@@ -757,14 +703,14 @@ fn heap_layout() -> &'static HeapLayout {
})
}
/// The index in [`heap_classes`] of the first form of `ExtendedRange::HEAP_READ`: a heap texture's
/// class index at or past it names the form `index - base` of that list.
/// The heap class index ([`heap_class_index`]) of the first form of `ExtendedRange::HEAP_READ`: a
/// heap texture's class index at or past it names the form `index - base` of that list.
pub fn heap_extended_base() -> u32 {
heap_layout().extended
}
/// The index in [`heap_classes`] of a heap texture of a signed integer color format; the next one
/// is an unsigned integer color format's ([`heap_numeric`]).
/// The heap class index ([`heap_class_index`]) of a texture of a signed integer color format; the
/// next one is an unsigned integer color format's ([`heap_numeric`]).
pub fn heap_numeric_base() -> u32 {
heap_layout().numeric
}
@@ -796,12 +742,12 @@ pub fn heap_numeric(pf: PixelFormat) -> Option<crate::pipeline::sym::SampledType
}
}
/// The index in [`heap_classes`] of `A8Unorm`'s class, which no other format's texture carries:
/// a storage read or write through a heap handle carrying it converts the member's texels where
/// the device holds such a texture's alpha in red (`metal::format::alpha_in_red`), which a heap's
/// storage array views without a component mapping. A swizzled `A8Unorm` texture that reads as
/// none carries it too; another swizzle's class is `OTHER`, which a heap's storage array does not
/// hold there (`bind::heap`'s storage elements).
/// The heap class index ([`heap_class_index`]) of `A8Unorm`'s class, which no other format's
/// texture carries: a storage read or write through a heap handle carrying it converts the member's
/// texels where the device holds such a texture's alpha in red (`metal::format::alpha_in_red`),
/// which a heap's storage array views without a component mapping. A swizzled `A8Unorm` texture
/// that reads as none carries it too; another swizzle's class is `OTHER`, which a heap's storage
/// array does not hold there (`bind::heap`'s storage elements).
pub fn heap_alpha_in_red_index() -> u32 {
heap_class_index(PixelFormat::A8Unorm, TextureSwizzleChannels::DEFAULT)
}
@@ -823,11 +769,11 @@ pub fn mode_two_rounds(pf: PixelFormat, halves: bool) -> bool {
|| (halves && half_channels(pf))
}
/// The index in [`heap_classes`] of the class a heap texture of pixel format `pf` made with
/// The index among the heap's classes of the class a heap texture of pixel format `pf` made with
/// `swizzle` carries ([`heap_class`]); for an unswizzled texture of a form of
/// `ExtendedRange::HEAP_READ`, that form's index past [`heap_extended_base`]; for an integer color
/// format, its numeric marker ([`heap_numeric_base`]), and for a format a read of another class
/// does not take, its class among those past the own-only base ([`heap_classes`]).
/// does not take, its class among those past the own-only base.
pub fn heap_class_index(pf: PixelFormat, swizzle: TextureSwizzleChannels) -> u32 {
let layout = heap_layout();
match heap_numeric(pf) {
@@ -1278,7 +1224,7 @@ mod tests {
fn a_heap_texture_names_its_class_by_index() {
use crate::memory::handles::FLAG_TEXEL_CLASS;
use crate::metal::format::ExtendedRange;
let classes = heap_classes();
let classes = &heap_layout().classes;
let base = heap_extended_base() as usize;
assert_eq!(classes.first(), Some(&TexelFormat::OTHER.0));
assert!(classes[..base].windows(2).all(|w| w[0] < w[1]));
@@ -1363,7 +1309,7 @@ mod tests {
fn the_alpha_in_red_heap_class_is_a8_unorms_alone() {
use crate::metal::TextureSwizzle as S;
let a8 = heap_alpha_in_red_index();
assert_ne!(heap_classes()[a8 as usize], TexelFormat::OTHER.0);
assert_ne!(heap_layout().classes[a8 as usize], TexelFormat::OTHER.0);
let swizzles = [
TextureSwizzleChannels::DEFAULT,
TextureSwizzleChannels::new(S::Blue, S::Green, S::Red, S::Alpha),
@@ -1390,7 +1336,8 @@ mod tests {
#[test]
fn a_heap_write_finds_the_half_formats_by_index() {
use crate::metal::bicubic::BicubicTexels;
let half: Vec<u32> = heap_classes()
let half: Vec<u32> = heap_layout()
.classes
.iter()
.enumerate()
.filter(|(_, &c)| {
@@ -1410,98 +1357,4 @@ mod tests {
assert_eq!(half.contains(&i), wanted.contains(&pf), "{pf:?}");
}
}
/// The bits of a class the `half` routine of a device that samples through Metal's own
/// texture unit reads (`lower::texture::half`).
const READ_ON_METAL_SAMPLER: u32 = T::LINEAR | T::SNORM | T::WIDE16 | TexelFormat::YCBCR_8192;
/// [`TexelFormat::YCBCR_8192`] is set in exactly the fields of the grid `8192`, the packed
/// fields whose one texel's `half` rounds with ties away from zero.
#[test]
fn the_ycbcr_8192_bit_names_exactly_the_grid_8192_fields() {
for p in PackedTexels::ALL {
let field = (p as u32) << TexelFormat::PACKED;
assert_eq!(field & TexelFormat::PACKED_MASK, field, "{p:?}");
assert_eq!(
field & TexelFormat::YCBCR_8192 != 0,
matches!(
p,
PackedTexels::YCbCr8192
| PackedTexels::YCbCrExtended8192
| PackedTexels::Rgb10A2Srgb
),
"{p:?}"
);
assert_eq!(
field & TexelFormat::YCBCR_8192 != 0,
p.ties_away() && p != PackedTexels::YCbCr2048,
"{p:?}"
);
}
}
/// A 16-bit grid's class (`WIDE16`) is an exact family's with no packed field, so the Metal
/// sampler's routine, which reads the grid's bit and not the packed field, selects its grid
/// for nothing else.
#[test]
fn a_wide16_class_is_exact_and_unpacked() {
for &pf in PixelFormat::ALL {
let c = texel_format(pf).0;
if c & T::WIDE16 != 0 {
assert_ne!(c & T::EXACT, 0, "{pf:?}");
assert_eq!(c & TexelFormat::PACKED_MASK, 0, "{pf:?}");
assert_eq!(c & T::LINEAR, 0, "{pf:?}");
}
}
}
/// On a device that samples through Metal's own texture unit the 8-bit unsigned normalized,
/// half-float, sRGB, packed, small float and YCbCr-2048 formats' classes, swizzled or not,
/// read as a slot bound to nothing does, and are measured; the 32-bit float and 16-bit grids',
/// an 8-bit signed format's, and a YCbCr-8192 field's do not; a compressed format's class is
/// unmeasured.
#[test]
fn the_metal_sampler_s_read_bits_fold_the_measured_families() {
let folded = [
PixelFormat::RGBA8Unorm,
PixelFormat::BGRA8Unorm,
PixelFormat::R8Unorm,
PixelFormat::RG8Unorm,
PixelFormat::A8Unorm,
PixelFormat::RGBA8UnormSRGB,
PixelFormat::R16Float,
PixelFormat::RGBA16Float,
PixelFormat::B5G6R5Unorm,
PixelFormat::RGB10A2Unorm,
PixelFormat::RG11B10Float,
PixelFormat::RGB9E5Float,
];
for pf in folded {
let c = texel_format(pf);
assert_eq!(c.0 & READ_ON_METAL_SAMPLER, 0, "{pf:?}");
assert!(!c.unmeasured_on_metal_sampler(), "{pf:?}");
assert_eq!(c.swizzled().0 & READ_ON_METAL_SAMPLER, 0, "{pf:?}");
}
for pf in [
PixelFormat::RGBA8Snorm,
PixelFormat::R16Unorm,
PixelFormat::RGBA16Snorm,
PixelFormat::RGBA32Float,
] {
let c = texel_format(pf);
assert_ne!(c.0 & READ_ON_METAL_SAMPLER, 0, "{pf:?}");
assert!(!c.unmeasured_on_metal_sampler(), "{pf:?}");
}
for p in [PackedTexels::YCbCr8192, PackedTexels::YCbCrExtended8192] {
let c = TexelFormat((p as u32) << TexelFormat::PACKED);
assert_ne!(c.0 & READ_ON_METAL_SAMPLER, 0, "{p:?}");
assert!(!c.unmeasured_on_metal_sampler(), "{p:?}");
}
let ycbcr = TexelFormat((PackedTexels::YCbCr2048 as u32) << TexelFormat::PACKED);
assert_eq!(ycbcr.0 & READ_ON_METAL_SAMPLER, 0);
assert!(!ycbcr.unmeasured_on_metal_sampler());
assert!(texel_format(PixelFormat::BC7RGBAUnorm).unmeasured_on_metal_sampler());
assert!(!texel_format(PixelFormat::BC1RGBA).unmeasured_on_metal_sampler());
assert!(TexelFormat(0).unmeasured_on_metal_sampler());
}
}
+35 -109
View File
@@ -535,17 +535,15 @@ pub enum PrecisionNote {
F16IntConvDoubleRounding,
/// Bias sampling emulated with gradients may pick another level and another anisotropic
/// footprint than Metal's: derivatives hoisted out of a per-fragment texture choice, which
/// scale by `2^B` through every sampler, and, on a device that does not sample through Metal's
/// own sampler, a bias whose sum with the sampler's own may lie beyond the device's
/// `maxSamplerLodBias`, which Vulkan clamps, or that an anisotropic sampler applies to its
/// footprint's minor axis alone; and, on a device without `maintenance8`, a fragment's
/// implicit-level sample with a dynamic texel offset, whose derivatives are taken before the
/// switch over the offset's values (`lower::sampler::OffsetArms`). The gradients carry Metal's
/// own reading of the bias, `B`; `Exp2`'s precision and the device's level arithmetic are the device's. A device that samples
/// through Metal's own sampler (MoltenVK) records it only for a constexpr sampler with a bias
/// of its own and for hoisted derivatives, except those of a 2D color sample without a bias, a
/// `min_lod_clamp` or an offset through samplers without a bias of their own, which there are
/// Metal's own sample.
/// scale by `2^B` through every sampler, and a bias whose sum with the sampler's own may lie
/// beyond the device's `maxSamplerLodBias`, which Vulkan clamps, or that an anisotropic sampler
/// applies to its footprint's minor axis alone; and, on a device without `maintenance8`, a
/// fragment's implicit-level sample with a dynamic texel offset, whose derivatives are taken
/// before the switch over the offset's values (`lower::sampler::OffsetArms`). The gradients
/// carry Metal's own reading of the bias, `B`; `Exp2`'s precision and the device's level
/// arithmetic are the device's. Hoisted derivatives of a 2D color sample without a bias, a
/// `min_lod_clamp` or an offset, through samplers without a bias of their own, go to the
/// device's sampler whole (`PrecisionNote::DeviceSampling`) and do not record it.
GradFromBias,
/// Transcendentals answer within Apple's stated bound, not Metal's bits: the device's own
/// functions where they are Metal's (MoltenVK), and the device's precision for a call no
@@ -889,20 +887,7 @@ pub enum PrecisionNote {
///
/// 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,
/// exactly, but writes a `y` face's `x` tangent on both of its tangents, so its `z` tangent is
/// lost: the module hands a `y` face Metal's length of its two tangents, which Metal reads on
/// both, an isotropic sample's footprint kept up to one rounding of `64/91` (measured: every
/// lane Metal's) and an anisotropic one's ellipse laid on the face's diagonal. Sampling a `y`
/// face through a 2D-array view of the cube with the face gradients would give Metal's own
/// anisotropic sample on every lane whose filter stays inside the face (measured), and differ
/// less than the fixup where it crosses the face's edge; the binder does not offer that view
/// yet.
/// Metal's level and taps (`PrecisionNote::AnisotropicFilter`).
///
/// Also recorded for every cube access whose level comes from the fragment's derivatives (an
/// implicit-level sample, one whose gradients a switch-at-use hoisted, or an LOD query): its
@@ -922,60 +907,23 @@ pub enum PrecisionNote {
/// `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 (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 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 `half` is the device's rounding of the
/// step's `float`, announced by the runtime at a draw or dispatch that binds such a texture
/// there. Measured on MoltenVK 1.4.2 over the Apple M3 Max (macOS 27.0.1): toward zero, within
/// one `half` ulp of Metal's (8,409 channels of the `_sRGB` twins over six surfaces and three
/// matrices); unmeasured on other Apple GPUs.
/// Native device sampling (a texel conversion): every access with a `half` result records this
/// note, a heap element's and a depth texture's included. 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`]).
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
/// sampler (`VkProperty::MetalSampler`, MoltenVK) answers otherwise than Metal filters the
/// format bound there: a two-plane YCbCr texture's (`YCBCR8_420_2P` and its kin), whose view
/// holds Metal's reads exactly but which Metal's sampler filters as an `RGBA16Float` or
/// `RGBA32Float` texture's texels, within one step of the format's grid, where Metal sums the
/// steps on the grid, each term truncated (`lower::sampler::linear`). Recorded under the slot's
/// bound format, which a consumer reads at each draw or dispatch
/// ([`StageModule::precision_notes_bound`]), and through a runtime sampler slot under the bound
/// sampler's word
/// (`SpecKey::BoundSamplerWord`, which the plan gives) where it filters: a linear minification
/// or magnification filter, a linear mip filter, anisotropy, or a cubic filter. A sample of a
/// texture an argument buffer holds (a heap's) is recorded where a texture its handles can name
/// is two-plane YCbCr (`SpecKey::HeapYCbCrTextures`), and through an argument buffer's sampler
/// where a sampler state an argument buffer can name filters
/// (`SpecKey::FilteringArgumentSampler`): the plan gives both. A sample through a sampler that
/// reads one texel of one level (nearest minification and magnification, no mip filter or a
/// nearest one, no anisotropy: a constexpr one, or a runtime slot's bound one) and a gather
/// are not filtered and do not carry it. A device that samples natively records
/// [`PrecisionNote::DeviceSampling`] instead.
///
/// On every device, a linear sample of a two-plane YCbCr texture whose planes the function
/// reads in place (`lower::sampler::in_place`) by Vulkan's Y′CbCr model of the codes
/// records it too,
/// under the slot's bound converted 4:2:0 format and, through a runtime sampler slot, the bound
/// word's linear filter that addresses no border. The
/// `float` result's counterpart is [`PrecisionNote::FloatSampleFilter`]. Validation derives no
/// tolerance from it: the class is unbounded.
/// or magnification, a linear mip filter, anisotropy, or a runtime sampler) by Vulkan's Y′CbCr
/// model of the codes of a two-plane YCbCr texture whose planes the function reads in place
/// (`lower::sampler::in_place`), which blends the codes, not Metal's exact filter of the
/// format, on every device: recorded under the slot's bound converted 4:2:0 format and,
/// through a runtime sampler slot, the bound word's linear filter that addresses no border.
/// The `float` result's counterpart is [`PrecisionNote::FloatSampleFilter`]. Validation derives
/// no tolerance from it: the class is unbounded.
HalfSampleFilter,
/// The module reads, samples, or gathers a texture with a `half` or `float` result through
/// the device's sRGB decode, or decodes the device's filter of its codes, where the texture may
@@ -991,9 +939,7 @@ pub enum PrecisionNote {
/// of `SpecKey::BoundTexelFormat` the runtime reads at a draw or dispatch binding such a
/// texture), outright for an argument-buffer (heap) element, whose format is never known,
/// and at the pipeline for a `float` input attachment whose color attachment is an sRGB format
/// (`StageIo::decoded_fetches`). On a device that samples through Metal's own texture unit
/// (`VkProperty::MetalSampler`: MoltenVK on Apple's GPU) the device's decode is Metal's, and
/// the module requires the property instead. Measured over every code of `RGBA8Unorm_sRGB`:
/// (`StageIo::decoded_fetches`). Measured over every code of `RGBA8Unorm_sRGB`:
/// MoltenVK on an Apple M3 Max decodes each as Metal does, bit
/// for bit; lavapipe (LLVM 21.1.8, arm64) each color code within 5.25 table steps (0.00128, a
/// third of a code's `1/255`) of Metal's value, alpha within one `f32` ulp; other devices are
@@ -1014,21 +960,12 @@ pub enum PrecisionNote {
/// it, where MoltenVK's `Pow` read within `1.83e-7` of the transfer through the alias.
/// Validation derives no tolerance from it: the class is unbounded.
SrgbTexelDecode,
/// The module samples a texture with a `float` result through a filter that Metal's own
/// sampler (`VkProperty::MetalSampler`, MoltenVK) answers otherwise than Metal filters the
/// format bound there: a two-plane YCbCr texture's, as for [`PrecisionNote::HalfSampleFilter`]
/// (a depth texture's sample and a comparison's included). A sample is filtered unless its
/// sampler has nearest minification and magnification, no mip filter or a nearest one, and no
/// anisotropy: linear minification or magnification, a linear mip filter, anisotropy, and a
/// cubic filter filter. Recorded under the slot's bound format, and through a runtime sampler
/// slot under the bound sampler's word (`SpecKey::BoundSamplerWord`), whose filter is not
/// known when the function compiles, and for a heap's texture under what its handles and an
/// argument buffer's sampler can name, as [`PrecisionNote::HalfSampleFilter`] is: a consumer
/// reads them at each draw or dispatch ([`StageModule::precision_notes_bound`]). A
/// device that samples natively records [`PrecisionNote::DeviceSampling`] instead. The model's
/// linear sample of planes read in place records it on every device, as
/// [`PrecisionNote::HalfSampleFilter`] states. Validation derives no tolerance from it: the
/// class is unbounded.
/// The module samples a texture with a `float` result through a filter by Vulkan's Y′CbCr
/// model of the codes of a two-plane YCbCr texture whose planes the function reads in place
/// (`lower::sampler::in_place`), as [`PrecisionNote::HalfSampleFilter`] states for a `half`
/// result: a sample is filtered unless its sampler has nearest minification and
/// magnification, no mip filter or a nearest one, and no anisotropy. Validation derives no
/// tolerance from it: the class is unbounded.
FloatSampleFilter,
/// A vertex or fragment function keeps more private memory (its `alloca`s, a call stack among
/// them, or constants held as `Private` variables) than the floor, 16 KiB a thread, on a device
@@ -1528,8 +1465,7 @@ pub enum PrecisionNote {
/// 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.
/// on `R32Float`).
///
/// 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,
@@ -1615,8 +1551,8 @@ pub enum PrecisionNote {
/// `Fma` round the product and then the sum). Validation derives no tolerance from it.
NativeFma,
/// Native device sampling (a texel conversion): the module hands a read, sample or gather
/// with a `float` result the device's own conversion of the texel's codes, off Apple's GPUs
/// (`VkProperty::MetalSampler` keeps Metal's value). Recorded for every such access of a
/// with a `float` result the device's own conversion of the texel's codes. Recorded for every
/// such access of a
/// texture slot or a heap texture (not a heap's texture buffer,
/// [`PrecisionNote::DeviceNanEncoding`]). The recorded bound, of a texel whose access reads
/// one texel of one level:
@@ -1921,16 +1857,6 @@ pub enum PrecisionNote {
/// branch's block (a quad's first lane, a shuffle's source lane, a vote). Nothing else in the
/// stage changes. Validation derives no tolerance from it.
UnmeasuredGroupSpeculation,
/// A sample at an implicit level or with gradients through a constexpr sampler with
/// anisotropy, no mip filter (`mip_filter::none`) and different minification and magnification
/// filters, on a device that samples through Metal's own sampler (MoltenVK on Apple's GPU,
/// `DriverDeviation::MetalSampler`). Vulkan has no sampler without mipmapping: the device's
/// sampler takes a nearest mip filter with the level clamp `[0, 0.25]`, which keeps Metal's
/// choice of filter, but at `maxAnisotropy` 2 to 16 no clamp reads Metal's `NotMipmapped`
/// footprint (`metal::sampler::vk_sampler`). **Residual:** the sample filters another
/// anisotropic footprint than Metal's. A sampler state the runtime makes of that shape is
/// announced as it is made instead. Validation derives no tolerance from it.
NotMipmappedAnisotropicFilter,
/// An extended-range texture's fragment sample at an implicit level and its sample with
/// explicit gradients (`BGR10_XR`, `BGRA10_XR` and their sRGB twins), which read texels in the
/// shader on every device: they take Vulkan's level of detail computed in the shader and then
+7 -22
View File
@@ -3318,14 +3318,8 @@ fn lower_bounded<K>(
precision.push(PrecisionNote::LinkedSamplerNumbering);
precision.sort_unstable();
}
// A sample left to the sampler of a device that samples natively: the device's answer.
let sampled = plan.families.sampler.metal_sampler || plan.families.sampler.device_sampling;
if sampled
&& p.fields()
.enabled
.properties
.contains(&crate::device::requirements::VkProperty::DeviceSampling)
&& !precision.contains(&PrecisionNote::DeviceSampling)
// A sample left to the device's sampler: the device's answer.
if plan.families.sampler.device_sampling && !precision.contains(&PrecisionNote::DeviceSampling)
{
precision.push(PrecisionNote::DeviceSampling);
precision.sort_unstable();
@@ -3363,21 +3357,12 @@ fn lower_bounded<K>(
.properties
.insert(crate::device::requirements::VkProperty::SimdgroupLockstep);
}
// Every sample, gather and comparison is the device's sampler's: Metal's own on a device
// that samples through it, whose answers the stage claims as Metal's, else the device's own,
// which the stage records. The module requires whichever it is.
let sampling = &plan.families.sampler;
if sampling.metal_sampler || sampling.device_sampling {
use crate::device::requirements::VkProperty;
let native = p
.fields()
.enabled
// Every sample, gather and comparison is the device's own sampler's, which the stage records
// and requires.
if plan.families.sampler.device_sampling {
requirements
.properties
.contains(&VkProperty::DeviceSampling);
requirements.properties.insert(match native {
true => VkProperty::DeviceSampling,
false => VkProperty::MetalSampler,
});
.insert(crate::device::requirements::VkProperty::DeviceSampling);
}
// A fragment's simdgroup lane read from its subgroup lane because the device's fragment
// subgroups are Metal's simdgroups.
+2 -6
View File
@@ -286,12 +286,8 @@ pub enum RuntimeFact {
PredicationVote,
/// The function reads the class of the texture (or texture buffer) bound to the slot, which
/// the binder sets from the bound format: the slot's `SpecKey::TexelFormat` specialization
/// (`metal::texel_format::texel_format`). A read, gather or sample with a `half` result on a
/// device that samples through Metal's own sampler converts its texel by it, Metal's conversion
/// depending on the format (a read of a 32-bit float texel rounds to nearest even, a sample of
/// one toward zero; a normalized texel's value is rounded onto its format's grid first); an
/// 8-bit sRGB slot's raw read, a fetched gather and a NaN texel's rule (the NaN switch) read
/// it too.
/// (`metal::texel_format::texel_format`): an 8-bit sRGB slot's raw read, a fetched gather and
/// a NaN texel's rule (the NaN switch) read it.
TexelFormat { slot: SlotRef },
/// The function reads, samples, or gathers the texture bound to the slot with a `half` or
/// `float` result, which an 8-bit sRGB format bound there would decode. Bound in such a
@@ -564,9 +564,8 @@ pub struct LoweringInputs {
/// holds raw codes: the function applies the swizzle to each texel it reads, samples or gathers
/// there after decoding it, a border or out-of-bounds texel included, and a gather of a
/// component gathers the component the swizzle names (a `Zero` or `One` 0 or 1 at every tap),
/// as plain Metal does. And on a device without Metal's own sampler each sampled slot bound to
/// a swizzled packed normalized texture: the function swizzles the texels its class converts,
/// likewise.
/// as plain Metal does. And each sampled slot bound to a swizzled packed normalized texture:
/// the function swizzles the texels its class converts, likewise.
#[cfg_attr(feature = "serde", serde(default))]
pub swizzled_storage: BTreeSet<SlotRef>,
/// The function reads every visible-function table it reads by resource id through the
+3 -5
View File
@@ -221,11 +221,9 @@ pub struct StageIo {
#[cfg_attr(feature = "serde", serde(default))]
pub word_colors: BTreeMap<u32, crate::metal::format::WordAttachment>,
/// The input attachments the fragment function reads as `float` texels through the device's
/// decode, on a device that does not decode through Metal's own texture unit (without
/// `VkProperty::MetalSampler`): a render pipeline whose attachment there has an 8-bit sRGB
/// format records `PrecisionNote::SrgbTexelDecode` for the stage
/// (`color_writes::pipeline_writes`), the device's sRGB decode standing for Metal's
/// twelve-bit table.
/// decode: a render pipeline whose attachment there has an 8-bit sRGB format records
/// `PrecisionNote::SrgbTexelDecode` for the stage (`color_writes::pipeline_writes`), the
/// device's sRGB decode standing for Metal's twelve-bit table.
#[cfg_attr(feature = "serde", serde(default))]
pub decoded_fetches: std::collections::BTreeSet<u32>,
/// The attachments held with their channels rotated (`LoweringInputs::rotated_colors`) that
+15 -46
View File
@@ -763,24 +763,6 @@ pub enum SpecKey {
/// that constant is 1. A slot bound to a texture that is not sparse (`MTLTexture.isSparse`),
/// or to none, takes 0.
ConstantLanes(SlotRef),
/// Boolean: the texture bound to the slot is in a format whose conversion to `half` is not
/// measured on a device that samples through Metal's own texture unit (default false; its
/// class, as `TexelFormat` states it, has no measured family, no 8-bit sRGB bit and no packed
/// field: `metal::texel_format::TexelFormat::unmeasured_on_metal_sampler`). A slot bound to
/// nothing takes false: its zero texel converts alike under every class. On such a device a
/// function notes its `half` conversion of the slot where it holds
/// (`PrecisionNote::HalfTexelConversion`), so the `TexelFormat` bits that only that note read
/// leave the pipeline's key.
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 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
/// drops the class's routine; the class itself stays push data (`SpecKey::TexelFormat`).
PlainHalfTexels(SlotRef),
/// The class of the format of the texture bound to the slot (`u32`, as `TexelFormat` states
/// it: `metal::texel_format::texel_format`), read by a specialized note's test alone
/// ([`SpecTest`](crate::pipeline::SpecTest)): no stage declares it as a constant and no
@@ -832,46 +814,33 @@ pub enum SpecKey {
/// not known, such a test
/// holds. A slot bound to no sampler takes 0.
BoundSamplerWord(SlotRef),
/// Boolean: a texture the stage's handles can name is of a two-plane YCbCr class (its
/// `metal::texel_format::TexelFormat::PACKED` field `YCbCr2048`, `YCbCr8192` or
/// `YCbCrExtended8192`): a heap member of the command reaching the stage, one it makes
/// resident (`BindShape::used`) or binds at a texture slot of the stage
/// (`bind::heap`'s members). Read by a specialized note's test alone
/// ([`SpecTest`](crate::pipeline::SpecTest)), as [`BoundSamplerWord`](Self::BoundSamplerWord)
/// is: a plan gives it (`BindingPlan::specialized_value`), and where it is not known such a
/// test holds. A texture the command neither names nor makes resident, which a handle loaded
/// from memory may still reach and whose read Metal leaves undefined, is not counted.
HeapYCbCrTextures(Stage),
/// Two bits: 1 where a texture the stage's handles can name is one a heap holds by its raw
/// texels alone (`bind::heap::heap_raw_form`: an unswizzled, not sparse texture of one sample
/// of a form of `ExtendedRange::HEAP_READ`, whose texels the function's `float` read, sample
/// or gather decodes by the device's arithmetic, `PrecisionNote::DevicePackConversion`), and 2
/// of a form of `ExtendedRange::HEAP_READ`, whose texels the function's `float` read, sample or
/// gather decodes by the device's arithmetic, `PrecisionNote::DevicePackConversion`), and 2
/// where one such is of a form whose linear sample the function filters by the device's
/// arithmetic (not a bfloat form, whose sample reads the nearest texel under either filter,
/// `PrecisionNote::BicubicFilterArithmetic`): of the heap members of the command reaching the
/// stage, as for [`HeapYCbCrTextures`](Self::HeapYCbCrTextures), and given by a plan, as that
/// is. A stage whose `float` read, sample, gather or query of a heap may meet such a texture
/// declares it as a constant (default 3), whose bit 1 gates the raw arms
/// (`lower::texture::heap_raw_form`): where it is 0 they are dead code at pipeline creation,
/// exactly, since no handle the command names then carries a raw form's class. A pipeline's
/// key carries it there, and a specialized note's test reads it from the key; elsewhere such a
/// test reads the plan's value, as for [`HeapYCbCrTextures`](Self::HeapYCbCrTextures).
/// stage, a member it makes resident (`BindShape::used`) or binds at a texture slot of the
/// stage (`bind::heap`'s members), and given by a plan (`BindingPlan::specialized_value`). A
/// texture the command neither names nor makes resident, which a handle loaded from memory may
/// still reach and whose read Metal leaves undefined, is not counted. A stage whose `float`
/// read, sample, gather or query of a heap may meet such a texture declares it as a constant
/// (default 3), whose bit 1 gates the raw arms (`lower::texture::heap_raw_form`): where it is 0
/// they are dead code at pipeline creation, exactly, since no handle the command names then
/// carries a raw form's class. A pipeline's key carries it there, and a specialized note's test
/// reads it from the key; elsewhere such a test reads the plan's value, and where it is not
/// known such a test holds.
HeapRawTextures(Stage),
/// Four bits: the families of the float textures the stage's handles can name whose texel may
/// hold a NaN a `half` write stores (`lower::texture::half_write_nans`), each a bit of
/// `bind::heap::nan_family`: 1 a 16-bit float format, 2 a 32-bit float one, 4 a packed
/// small float one (`RG11B10Float`, `RGB9E5Float`), 8 a float format of none of those and
/// none whose texels hold no NaN (normalized, sRGB, extended-range); of the heap members of
/// the command reaching the stage, as for [`HeapYCbCrTextures`](Self::HeapYCbCrTextures), and
/// read by a specialized note's test alone, given by a plan, as that is.
/// the command reaching the stage, as for [`HeapRawTextures`](Self::HeapRawTextures), and
/// read by a specialized note's test alone ([`SpecTest`](crate::pipeline::SpecTest)), given
/// by a plan, as [`BoundSamplerWord`](Self::BoundSamplerWord) is.
HeapNanFamilies(Stage),
/// Boolean: a sampler state an argument buffer's sampler handle can name filters: one of the
/// bind state's argument samplers (`BindState::argument_samplers`, every live state, its
/// shape in `BindShape`) has a linear minification, magnification or mip filter, anisotropy,
/// or a cubic filter. Which state an argument buffer holds is in its memory, which no plan
/// reads. Read by a specialized note's test alone, given by a plan, as
/// [`HeapYCbCrTextures`](Self::HeapYCbCrTextures) is.
FilteringArgumentSampler,
/// Boolean: an element that a kernel's `[[stage_in]]` fetch of a thread-position step reads
/// in this dispatch region may lie past the first `2^32` bytes from its bind offset (default
/// true). Each such element is the region's origin plus the thread's position over the step
@@ -23,13 +23,14 @@ impl FunctionBuilder<'_> {
/// kind's non-uniform indexing capability and feature. `base` must point to a `UniformConstant`
/// array of images (not subpass data) or samplers, or a `StorageBuffer` array of blocks. The
/// serializer decorates `NonUniform` the result and every value that carries the element to the
/// instruction consuming it (VUID-RuntimeSpirv-NonUniform-06274): a load of an image or sampler
/// element, an image texel pointer to it, a sampled image of a loaded element, the image of
/// such a sampled image, and a further access chain into a block element, which a load, a
/// store, an atomic, or `OpArrayLength` then reads through. The builder refuses every other use
/// of those values that would carry the element on (a phi, select, copy, store, composite part,
/// or call argument), and an image or sampler element is not indexable further. A value loaded
/// from a block element is data, which carries no element.
/// instruction consuming it (VUID-RuntimeSpirv-None-10148 and
/// VUID-RuntimeSpirv-subgroupSize-10149): a load of an image or sampler element, an image texel
/// pointer to it, a sampled image of a loaded element, the image of such a sampled image, and a
/// further access chain into a block element, which a load, a store, an atomic, or
/// `OpArrayLength` then reads through. The builder refuses every other use of those values that
/// would carry the element on (a phi, select, copy, store, composite part, or call argument),
/// and an image or sampler element is not indexable further. A value loaded from a block
/// element is data, which carries no element.
pub fn access_chain_non_uniform(&mut self, base: Value, index: Value) -> BResult<Value> {
const OP: crate::spv::Op = crate::spv::Op::AccessChain;
let (class, pointee, f) = self.pointer(OP, base)?;
+6 -6
View File
@@ -260,9 +260,9 @@ pub enum Inst {
Undef,
// ---- Memory (builder/ops/memory.rs) ----
/// `OpAccessChain`. `non_uniform` marks an element of a descriptor array chosen by an index
/// that may differ between invocations: the result and every value that carries the element
/// on ([`Inst::carries_non_uniform`]) are decorated `NonUniform`
/// (VUID-RuntimeSpirv-NonUniform-06274), and derivation requires the array kind's non-uniform
/// that may differ between invocations: the result and every value that carries the element on
/// ([`Inst::carries_non_uniform`]) are decorated `NonUniform` (VUID-RuntimeSpirv-None-10148 and
/// VUID-RuntimeSpirv-subgroupSize-10149), and derivation requires the array kind's non-uniform
/// indexing capability instead of its dynamic one.
AccessChain {
base: Value,
@@ -444,9 +444,9 @@ impl Inst {
/// sampler, or sampled image): a non-uniform access chain or a chain into a block element one
/// reached, an opaque load of one (the image or sampler), a texel pointer into one (an image
/// atomic's pointer), a sampled image of such an image or sampler, and the image of such a
/// sampled image. Each result is decorated `NonUniform` (VUID-RuntimeSpirv-NonUniform-06274);
/// the builder refuses the other uses that would carry the element on. Data loaded from a block
/// element carries none.
/// sampled image. Each result is decorated `NonUniform` (VUID-RuntimeSpirv-None-10148 and
/// VUID-RuntimeSpirv-subgroupSize-10149); the builder refuses the other uses that would carry
/// the element on. Data loaded from a block element carries none.
pub fn carries_non_uniform(&self, marked: impl Fn(Value) -> bool, opaque: bool) -> bool {
match self {
Inst::AccessChain {
@@ -53,9 +53,7 @@
//! Function" (`OpFunctionCall`), so each argument's reach is its parameter's, a pointer argument's
//! memory is its parameter's (what either side stores through it the other may load), and the
//! values the callee returns reach the call's result. The callee's instructions are the module's,
//! judged as any other; a callee called from several sites takes the reach of them all. Lowering's
//! texel routines (Metal's conversion of a `half` texel, `lower::texture::half`) are such calls,
//! whose selects carry the texel to the result alone.
//! judged as any other; a callee called from several sites takes the reach of them all.
//!
//! A module that already holds an interlock critical section has none: the variant's entry opens
//! its own. Nor has one with a `Coherent` resource or under the Vulkan memory model: the variant
@@ -1239,7 +1239,7 @@ impl Ser<'_> {
self.decorate(w, self.val(r)?, Decoration::NoContraction, &[])?;
}
// A value carrying a non-uniform descriptor element to its consumer
// (VUID-RuntimeSpirv-NonUniform-06274).
// (VUID-RuntimeSpirv-None-10148 and VUID-RuntimeSpirv-subgroupSize-10149).
if m.non_uniform.contains(&r) && non_uniform.insert(self.val(r)?) {
self.decorate(w, self.val(r)?, Decoration::NonUniform, &[])?;
}
@@ -707,10 +707,10 @@ fn non_uniform_descriptor_array_elements() {
}
/// A non-uniform element reaches the instruction consuming it decorated through every value that
/// carries it (VUID-RuntimeSpirv-NonUniform-06274): the chain, its loaded image, a sampled image
/// of that image and the sampled image's `OpImage`, and an image texel pointer an atomic uses.
/// The builder refuses the uses that would carry one undecorated (a call argument, a composite
/// part).
/// carries it (VUID-RuntimeSpirv-None-10148 and VUID-RuntimeSpirv-subgroupSize-10149): the chain,
/// its loaded image, a sampled image of that image and the sampled image's `OpImage`, and an image
/// texel pointer an atomic uses. The builder refuses the uses that would carry one undecorated (a
/// call argument, a composite part).
#[test]
fn non_uniform_elements_are_decorated_through_what_carries_them() {
use crate::pipeline::sym::{HandleClass, ImageAccess, ImageDim, ImageHandleClass};
+2 -2
View File
@@ -1,8 +1,8 @@
//! The bits of each specialization constant a module can read.
//!
//! A binder sets some constants from words of which a module reads only part: a texture slot's
//! `SpecKey::TexelFormat` class holds its format's family, channels and border texels, and the
//! `half` conversion routine tests only the family and the packed field. Two values that agree on
//! `SpecKey::TexelFormat` class holds its format's family, channels and border texels, of which a
//! module may test only some. Two values that agree on
//! every bit the module can read give the same program, so a binder that clears the other bits
//! makes one pipeline of them, and the driver (and Metal's own caches under MoltenVK) sees one
//! specialization.
@@ -311,11 +311,9 @@ impl Shape {
}
/// Through a sampler without a bias of its own every fragment bias is the `Bias` operand alone, the
/// device's sampler's: on MoltenVK (`VkProperty::MetalSampler`) the device hands it to Metal whole,
/// so Metal applies its own rule (the bias rounded to `half`, floored onto `1/64` and clamped into
/// `[-32, 31.984375]`); elsewhere the device clamps it into `±maxSamplerLodBias`
/// (`VkProperty::DeviceSampling`). A dynamic bias and a constant past the limit alike take no
/// derivatives and no branch, record no `PrecisionNote::GradFromBias`, and require the property.
/// device's sampler's, which clamps it into `±maxSamplerLodBias` (`VkProperty::DeviceSampling`). A
/// dynamic bias and a constant past the limit alike take no derivatives and no branch, record no
/// `PrecisionNote::GradFromBias`, and require the property.
#[test]
fn a_bias_without_the_samplers_own_is_the_bias_operand() {
use crate::device::requirements::VkProperty;
@@ -333,15 +331,7 @@ fn a_bias_without_the_samplers_own_is_the_bias_operand() {
}
for stem in ["moltenvk-m3", "amd-rdna3-radv", "lavapipe", "runtime-floor"] {
let prof = p(stem);
let property = match prof
.fields()
.enabled
.properties
.contains(&VkProperty::MetalSampler)
{
true => VkProperty::MetalSampler,
false => VkProperty::DeviceSampling,
};
let property = VkProperty::DeviceSampling;
for (what, bc, entry) in &fixtures {
let what = format!("{stem}, {what}");
let a = ok(bc, entry, &prof);
@@ -425,10 +415,9 @@ fn a_constant_bias_is_decided_at_compile_time_with_the_samplers_own() {
/// The hoisted derivatives (`fragment_mixed_samplers`, a sampler selected per fragment,
/// `bias(0.5)`) are scaled by the whole bias through the same finite scaling: no clamp of the bias
/// to `maxSamplerLodBias` (formerly `FClamp(bias, ±max)` before `Exp2`). Off Metal's own sampler,
/// the runtime slot among the candidates takes them into Metal's anisotropic filter, emulated where
/// its word states anisotropy on a device without `samplerAnisotropy` (the runtime's floor without
/// it, below that floor).
/// to `maxSamplerLodBias` (formerly `FClamp(bias, ±max)` before `Exp2`). The runtime slot among the
/// candidates takes them into Metal's anisotropic filter, emulated where its word states anisotropy
/// on a device without `samplerAnisotropy` (the runtime's floor without it, below that floor).
#[test]
fn hoisted_derivatives_take_the_whole_bias() {
let Some(bc) = assemble_file("sampling_completion.ll") else {
@@ -1323,7 +1323,7 @@ fn opaque_black_borders_read_exactly_through_their_views() {
/// with the view's mapping with `borderColorSwizzle` alone; without it the pair is refused.
#[test]
fn opaque_black_borders_follow_metal_s_texel_through_the_swizzle() {
use crate::device::requirements::{VkFeature, VkProperty};
use crate::device::requirements::VkFeature;
use crate::metal::sampler::OpaqueBlackBorder as B;
use metal::TextureSwizzle as T;
let Some(bc) = fixture("sampling") else {
@@ -1369,8 +1369,8 @@ fn opaque_black_borders_follow_metal_s_texel_through_the_swizzle() {
assert_eq!(border(&rgba), B::Stated, "{stem}");
let f = dev.profile().fields();
let has = |feature| f.enabled.features.contains(&feature);
let exact = f.enabled.properties.contains(&VkProperty::MetalSampler)
|| (has(VkFeature::BorderColorSwizzle) && has(VkFeature::BorderColorSwizzleFromImage));
let exact =
has(VkFeature::BorderColorSwizzle) && has(VkFeature::BorderColorSwizzleFromImage);
match plan(PixelFormat::RGBA8Unorm, argb) {
Ok(plan) if exact => {
assert_eq!(border(&plan), B::Stated, "{stem}");
+18 -49
View File
@@ -2329,9 +2329,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,
/// 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
/// and the plan takes an anisotropic listed sampler for it (`engine_heap_binder`). Every profile
/// with the
/// sampled heap compiles it and passes L3; it was `ArgumentBufferTextures NotImplemented` before.
#[test]
fn a_cube_gradient_through_an_argument_buffer_sampler_reads_its_own_sampler_array() {
@@ -2393,8 +2392,6 @@ declare { <4 x float>, i8 } @air.sample_texture_cube_grad.v4f32(ptr addrspace(1)
_ => None,
})
.collect();
let metal =
p.fields().cube_gradients.compute == crate::device::profile::CubeGradientRoute::Metal;
assert_eq!(
classes,
vec![HandleClass::Sampler {
@@ -2403,9 +2400,8 @@ declare { <4 x float>, i8 } @air.sample_texture_cube_grad.v4f32(ptr addrspace(1)
}],
"{stem}"
);
assert_eq!(
assert!(
a.precision.contains(&PrecisionNote::CubeGradientFootprint),
!metal,
"{stem}"
);
compiled += 1;
@@ -2706,14 +2702,6 @@ const OP_IMAGE_SAMPLE_DREF_EXPLICIT_LOD: u16 = 90;
const OP_IMAGE_GATHER: u16 = 96;
const OP_IMAGE_DREF_GATHER: u16 = 97;
/// Whether `p`'s device samples through Metal's own sampler, whose comparison is Metal's.
fn metal_sampler(p: &DeviceProfile) -> bool {
p.fields()
.enabled
.properties
.contains(&crate::device::requirements::VkProperty::MetalSampler)
}
/// What [`heap_compare_kernel`] compares through, and [`heap_linear_kernel`] samples through: a
/// constexpr sampler of these words, runtime sampler slot 0, or the sampler its argument buffer
/// holds beside the texture.
@@ -3008,15 +2996,12 @@ define void @k(ptr addrspace(2) %m, ptr addrspace(1) %out{param}, i32 %gid) {{
/// A heap texture's linear sample, through a constexpr sampler of linear filters (2D and 3D), a
/// runtime sampler slot, or the sampler its argument buffer holds, is the device's sample; the
/// census names the sample by its source, and the module states no `TexelFormat`
/// specialization. On a profile that samples through Metal's own sampler a 2D sample records the
/// filter note only under what the command's handles can name (a two-plane YCbCr texture,
/// `SpecKey::HeapYCbCrTextures`), never outright; a 3D one, whose class holds no two-plane
/// texture, records none. A 2D sample through a constexpr or runtime sampler also emulates a raw-held
/// texture's, in a branch on the class the handle carries (the search's flagged form, whose masks
/// and table the census counts under `HEAP_CLASS_CENSUS`). Each validates; a profile without the
/// sampled heap refuses each. (The interpreter models no sample; the runtime lane
/// `argument_linear_samples` reads the values on each device.)
/// census names the sample by its source, and the module states no `TexelFormat` specialization and
/// records no `FloatSampleFilter`, outright or specialized. A 2D sample through a constexpr or
/// runtime sampler also emulates a raw-held texture's, in a branch on the class the handle carries
/// (the search's flagged form, whose masks and table the census counts under `HEAP_CLASS_CENSUS`).
/// Each validates; a profile without the sampled heap refuses each. (The interpreter models no
/// sample; the runtime lane `argument_linear_samples` reads the values on each device.)
#[test]
fn heap_linear_samples_are_the_device_s() {
use crate::lower::texture::HEAP_CLASS_CENSUS;
@@ -3071,20 +3056,8 @@ fn heap_linear_samples_are_the_device_s() {
"{what}"
);
let filter = PrecisionNote::FloatSampleFilter;
assert_eq!(
a.precision.contains(&filter),
!three && metal_sampler(&p),
"{what}"
);
let clauses: Vec<_> = (a.specialized.iter())
.filter(|s| s.note == filter)
.flat_map(|s| &s.when)
.collect();
assert_eq!(clauses.is_empty(), three || !metal_sampler(&p), "{what}");
for c in clauses {
let heap = SpecKey::HeapYCbCrTextures(crate::pipeline::sym::Stage::Kernel);
assert!(c.all.iter().any(|t| t.key == heap), "{what}: {c:?}");
}
assert!(!a.precision.contains(&filter), "{what}");
assert!(!a.specialized.iter().any(|s| s.note == filter), "{what}");
assert!(
!a.interface
.read_keys()
@@ -3152,15 +3125,12 @@ fn heap_plain_half_kernel(through: CompareThrough, gather: bool) -> String {
out
}
/// A heap color texture's sample or gather with a `half` result converts the device's texel (or the
/// fetched one) by the class its handle carries, as a slot's converts by its bound format's, on a
/// profile that samples through Metal's own sampler (`VkProperty::MetalSampler`, whose `float`
/// result the class's rule rounds as Metal does): the module calls the `half` routine once, with
/// the class read from the handle's table, where the same access with a `float` result calls no
/// routine. On any other profile the `half` texel is the device's conversion: no routine. The note
/// stays: the class may be one whose conversion is not measured.
/// A heap color texture's sample or gather with a `half` result is the device's texel (or the
/// fetched one) rounded to nearest even, on every profile: the module calls no routine the same
/// access with a `float` result does not, but the raw-held emulation's twin, and records
/// `PrecisionNote::HalfTexelConversion`.
#[test]
fn heap_half_texels_convert_by_the_handle_s_class() {
fn heap_half_texels_round_the_device_s_texel() {
let cases = [
(CompareThrough::Constexpr(NEAREST_EDGE), false),
(CompareThrough::Constexpr(NEAREST_EDGE), true),
@@ -3189,11 +3159,10 @@ fn heap_half_texels_convert_by_the_handle_s_class() {
// nearest tap both ways for a `half` result (a bfloat form's toward zero, another's
// rounded): one call more than the `float` result's.
let twin = usize::from(!gather && !matches!(through, CompareThrough::Argument));
let routine = usize::from(metal_sampler(&p));
assert_eq!(
count(&a, OP_FUNCTION_CALL),
count(&f, OP_FUNCTION_CALL) + routine + twin,
"{what}: the half routine is called once, the float one where it converts"
count(&f, OP_FUNCTION_CALL) + twin,
"{what}: the float routine's calls, and the twin's"
);
let notes = &a.precision;
assert!(
@@ -2317,12 +2317,6 @@ fn a_cube_gradient_use_takes_an_anisotropic_argument_sampler_by_its_word() {
assert_ne!(stem, "moltenvk-m3", "moltenvk-m3 compiles the use");
continue;
};
let route = dev.profile().fields().cube_gradients.compute;
assert_eq!(
route,
crate::device::profile::CubeGradientRoute::Vulkan,
"{stem}"
);
let arrays: Vec<(u32, HandleClass)> = pipe.layout.sets[1]
.bindings
.iter()
@@ -1,21 +1,19 @@
//! The coordinates a device's gathers and samples read. A gather and a sample through a constexpr
//! normalized sampler are the device's sampler's on every device (Metal's own on MoltenVK), at the
//! coordinate as given: a subnormal coordinate reaches the device unflushed, the border axes'
//! included. A constexpr pixel sampler's sample or gather of a 1D or 2D texture that is no array
//! hands the device's unnormalized sampler the coordinate itself (a nearest sample with an offset,
//! its texel's centre moved by the offset), with no `PixelSamplerScaling`; of an array or a 3D
//! texture its nearest sample hands its texel's centre and the rest the coordinate divided by the
//! level-0 size, noted; a cube reads it as a normalized sampler. A runtime sampler's gather reads
//! only its word's coordinates bit, and its sample also its `NearestPixelSampler` specialization.
//! Every module requires the device's sampler (`VkProperty::MetalSampler` or
//! `VkProperty::DeviceSampling`) and validates on every committed profile, and the plan's word
//! estimate bounds what it emits.
//! normalized sampler are the device's sampler's on every device, at the coordinate as given: a
//! subnormal coordinate reaches the device unflushed, the border axes' included. A constexpr pixel
//! sampler's sample or gather of a 1D or 2D texture that is no array hands the device's
//! unnormalized sampler the coordinate itself (a nearest sample with an offset, its texel's centre
//! moved by the offset), with no `PixelSamplerScaling`; of an array or a 3D texture its nearest
//! sample hands its texel's centre and the rest the coordinate divided by the level-0 size, noted;
//! a cube reads it as a normalized sampler. A runtime sampler's gather reads only its word's
//! coordinates bit, and its sample also its `NearestPixelSampler` specialization. Every module
//! requires the device's sampler (`VkProperty::DeviceSampling`) and validates on every committed
//! profile, and the plan's word estimate bounds what it emits.
//!
//! `llvm-as` assembles the kernels; without it the tests skip visibly.
use std::sync::atomic::{AtomicU64, Ordering};
use crate::device::profile::DeviceProfile;
use crate::device::requirements::VkProperty;
use crate::library::FunctionArtifact;
use crate::pipeline::artifact::PrecisionNote;
@@ -236,19 +234,11 @@ fn uses(a: &FunctionArtifact, name: &str) -> u32 {
a.strategies.entries.get(name).map_or(0, |u| u.uses)
}
/// Whether compiled `a` requires the device's sampler: `VkProperty::MetalSampler` on a profile
/// that samples through Metal's own sampler, `VkProperty::DeviceSampling` on any other.
fn requires_the_sampler(a: &FunctionArtifact, p: &DeviceProfile) -> bool {
let property = match p
.fields()
.enabled
/// Whether compiled `a` requires the device's sampler (`VkProperty::DeviceSampling`).
fn requires_the_sampler(a: &FunctionArtifact) -> bool {
a.requirements
.properties
.contains(&VkProperty::MetalSampler)
{
true => VkProperty::MetalSampler,
false => VkProperty::DeviceSampling,
};
a.requirements.properties.contains(&property)
.contains(&VkProperty::DeviceSampling)
}
/// The kernels of the selection test, each with its access's census name.
@@ -362,7 +352,7 @@ fn normalized_gathers_and_samples_are_the_device_s_sampler_s() {
let a = compile(&bc, "k", p).unwrap_or_else(|e| panic!("{what}: {e}"));
link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(uses(&a, census), 1, "{what}");
assert!(requires_the_sampler(&a, p), "{what}");
assert!(requires_the_sampler(&a), "{what}");
}
}
}
@@ -388,7 +378,7 @@ fn the_fixture_cube_gathers_are_the_device_s() {
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: {e}"));
assert_eq!(uses(&a, "sampler.gather"), 5, "{stem}");
assert_eq!(uses(&a, "sampler.gather_compare"), 4, "{stem}");
assert!(requires_the_sampler(&a, &p), "{stem}");
assert!(requires_the_sampler(&a), "{stem}");
}
}
@@ -605,7 +595,7 @@ fn pixel_samplers_hand_the_device_their_coordinate() {
assert_eq!(a.requirements, b.requirements, "{what}");
}
}
assert!(requires_the_sampler(&a, p), "{what}");
assert!(requires_the_sampler(&a), "{what}");
}
}
}
@@ -658,7 +648,7 @@ fn a_runtime_samplers_gather_and_sample_read_only_its_coordinates() {
let what = format!("{name} on {stem}");
let a = compile(&bc, "k", p).unwrap_or_else(|e| panic!("{what}: {e}"));
link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: {e}"));
assert!(requires_the_sampler(&a, p), "{what}");
assert!(requires_the_sampler(&a), "{what}");
assert_eq!(sampler_fields(&a), SamplerWord::PIXEL_COORDINATES, "{what}");
assert!(
a.precision.contains(&PrecisionNote::PixelSamplerScaling),
@@ -875,7 +865,7 @@ fn a_subnormal_coordinate_reaches_the_device_unflushed() {
assert!(sampled, "{what}: no sample or gather");
assert_eq!(through, !flushed, "{what}");
if !flushed {
assert!(requires_the_sampler(&a, p), "{what}");
assert!(requires_the_sampler(&a), "{what}");
}
}
}
@@ -1002,8 +1002,8 @@ fn gathers_gradients_and_pixel_constexpr_samplers() {
}
/// A `half` sample of a texture slot is the device's texel rounded to nearest even, which records
/// the `HalfTexelConversion` note outright: no `TexelFormat` fact or specialization of the slot,
/// and no call of the module's conversion routine. A `float` sample takes none of them.
/// the `HalfTexelConversion` note outright: no `TexelFormat` fact or specialization of the slot.
/// A `float` sample takes none of them.
#[test]
fn half_samples_take_the_device_s_texel_noted() {
let Some(bc) = fixture() else {
@@ -1015,14 +1015,12 @@ fn half_samples_take_the_device_s_texel_noted() {
assert!(!h.facts.contains(&RuntimeFact::TexelFormat { slot: t }));
assert!(!h.interface.reads_key(SpecKey::TexelFormat(t)));
assert!(h.precision.contains(&PrecisionNote::HalfTexelConversion));
assert!(!h.strategies.entries.contains_key("texture.half_texel"));
let f = ok(&bc, "sample_level", &p);
assert!(f
.facts
.iter()
.all(|x| !matches!(x, RuntimeFact::TexelFormat { .. })));
assert!(!f.precision.contains(&PrecisionNote::HalfTexelConversion));
assert!(!f.strategies.entries.contains_key("texture.half_texel"));
}
/// In a fragment function implicit-LOD samples and LOD queries use the fragment's derivatives; a
@@ -25,7 +25,7 @@
use std::sync::atomic::{AtomicU64, Ordering};
use crate::device::profile::{CubeGradientRoute, DeviceProfile};
use crate::device::profile::DeviceProfile;
use crate::device::requirements::VkFeature;
use crate::device::DevicePolicy;
use crate::device::{Device, DeviceDescription};
@@ -405,7 +405,6 @@ fn an_anisotropic_constexpr_sampler_takes_metals_cube_gradient_footprint() {
/// `AnisotropicFilter`.
#[test]
fn a_cube_gradient_route_takes_the_devices_reading() {
use crate::device::profile::CubeGradients;
let path = engine_dir().join("unk_cube_grad_lod.ll");
let text = std::fs::read_to_string(&path).expect("fixture");
let word: u64 = 34_901_797_601_019_977;
@@ -431,13 +430,6 @@ fn a_cube_gradient_route_takes_the_devices_reading() {
.expect("device")
.profile()
.clone();
assert_eq!(
unmeasured.fields().cube_gradients,
CubeGradients {
graphics: CubeGradientRoute::Vulkan,
compute: CubeGradientRoute::Vulkan,
}
);
for (bc, taps) in [(&iso, false), (&aniso, true)] {
let what = if taps { "anisotropic" } else { "isotropic" };
let u = artifact(bc, "unk_cube_grad_lod", "unmeasured", &unmeasured).expect(what);
@@ -500,7 +492,6 @@ fn a_runtime_samplers_cube_gradients_take_their_footprint_by_its_word() {
let Some(a) = artifact(&bc, "runtime_cube_grad", &stem, &p) else {
continue;
};
let route = p.fields().cube_gradients.compute;
let fields = a.interface.read_keys().into_iter().find_map(|k| match k {
SpecKey::SamplerState { fields, .. } => Some(fields),
_ => None,
@@ -508,7 +499,6 @@ fn a_runtime_samplers_cube_gradients_take_their_footprint_by_its_word() {
let reads = fields.is_some_and(|f| f & SamplerWord::ANISOTROPIC != 0);
let noted = a.precision.contains(&PrecisionNote::CubeGradientFootprint);
let lengths = glsl(&a, GLSL_FMAX) >= 4 || glsl(&a, GLSL_LENGTH) >= 2;
assert_eq!(route, CubeGradientRoute::Vulkan, "{stem}");
assert!(reads, "{stem}: {fields:?}");
assert!(lengths, "{stem}");
assert!(noted, "{stem}");
@@ -99,7 +99,7 @@ fn unread(m: &TypedModule, notes: &[SpecializedNote]) -> u64 {
spec[0].unread_bits
}
/// The half texel routine's reads (`lower::texture::half`): bits under a mask, and a field
/// A routine's reads of its constant argument: bits under a mask, and a field
/// shifted down and masked. The analysis follows the constant into the routine's parameter.
fn bit_tests(fb: &mut FunctionBuilder<'_>, flags: Value) -> BResult<Value> {
let m = k(fb, 0x30D)?;
@@ -299,12 +299,10 @@ fn an_srgb_swizzle_across_alpha_swizzles_in_the_function_on_a_twin() {
/// class (an `RGBA8Unorm_sRGB` or ASTC sRGB texture's, not an `RGBA8Unorm` one's). Under the
/// variant every access decodes what the twin's view reads by the MSL transfer through the
/// device's `Pow`, declaring no table, and notes `SrgbTexelDecode` outright, on both devices. No
/// access records `PrecisionNote::HalfSampleFilter` or `PrecisionNote::FloatSampleFilter`, states
/// `RuntimeFact::TexelFormat` or requires `VkProperty::MetalSampler`. Every form validates on both
/// devices.
/// access records `PrecisionNote::HalfSampleFilter` or `PrecisionNote::FloatSampleFilter` or
/// states `RuntimeFact::TexelFormat`. Every form validates on both devices.
#[test]
fn the_device_decodes_every_access_and_a_twin_takes_its_pow() {
use crate::device::requirements::VkProperty;
let nearest = sampler_words(0, 0, false);
let linear = sampler_words(1, 0, false);
let bicubic = sampler_words(2, 0, false);
@@ -393,12 +391,6 @@ fn the_device_decodes_every_access_and_a_twin_takes_its_pow() {
variant && name != "gather alpha half",
"{what}"
);
assert!(
!a.requirements
.properties
.contains(&VkProperty::MetalSampler),
"{what}"
);
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: {e}"));
}
}
@@ -865,11 +857,10 @@ 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)
/// rounds the device's `f32` texel to nearest even: on lavapipe and MoltenVK, whose decode and
/// conversion are the device's, the pipeline requires no `VkProperty::MetalSampler` and records
/// `PrecisionNote::HalfTexelConversion` outright, which holds under every bound format.
/// conversion are the device's, the pipeline records `PrecisionNote::HalfTexelConversion`
/// outright, which holds under every bound format.
#[test]
fn the_device_s_srgb_decode_converts_to_half_noted() {
use crate::device::requirements::VkProperty;
let Some(bc) = assemble(
"mip linear half",
&kernel(Access::Sample(sampler_words(1, 2, false)), true),
@@ -883,12 +874,6 @@ fn the_device_s_srgb_decode_converts_to_half_noted() {
}
seen += 1;
let p = pipeline(&dev, &bc, &inputs(false));
assert!(
!p.requirements
.properties
.contains(&VkProperty::MetalSampler),
"{stem}"
);
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:?}");
@@ -684,19 +684,13 @@ fn short_texels_sign_extend_and_half_reads_round() {
assert!(ran > 0);
}
/// 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.
/// A `half` read rounds its `f32` texel to nearest even, half denormals kept, on every profile,
/// with no class of the bound format, and records `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]
fn half_reads_convert_by_the_bound_format() {
use crate::device::requirements::VkProperty;
use crate::metal::texel_format::texel_format;
use crate::metal::PixelFormat;
fn half_reads_round_their_texel_to_nearest_even() {
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::sym::{SlotClass, SlotRef};
@@ -708,73 +702,38 @@ fn half_reads_convert_by_the_bound_format() {
class: SlotClass::Texture,
index: 2,
};
let unorm16 = |c: u32| (f64::from(c) / 65535.0) as f32;
let float = [2f32.powi(-20), 65520.0, 1.0 + 1.0 / 4096.0, 3.0];
let cases: [(Option<u32>, [f32; 4], [u16; 4]); 3] = [
(None, float, [0x0010, 0x7C00, 0x3C00, 0x4200]),
(
Some(texel_format(PixelFormat::RGBA32Float).0),
float,
[0x0010, 0x7C00, 0x3C00, 0x4200],
),
(
Some(texel_format(PixelFormat::RGBA16Unorm).0),
[unorm16(65455), unorm16(65519), unorm16(1), unorm16(65535)],
[0x3BFE, 0x3C00, 0x0100, 0x3C00],
),
];
let texel = [2f32.powi(-20), 65520.0, 1.0 + 1.0 / 4096.0, 3.0];
let want: [u16; 4] = [0x0010, 0x7C00, 0x3C00, 0x4200];
let mut ran = 0;
for (stem, p) in profiles() {
let Some((plan, m)) = module(&bc, "short_texels", &stem, &p) else {
continue;
};
let metal = p
.fields()
.enabled
.properties
.contains(&VkProperty::MetalSampler);
assert_eq!(
plan.facts.contains(&RuntimeFact::TexelFormat { slot }),
metal,
assert!(
!plan.facts.contains(&RuntimeFact::TexelFormat { slot }),
"{stem}"
);
assert!(
plan.precision.contains(&PrecisionNote::HalfTexelConversion),
"{stem}"
);
for (class, texel, want) in cases {
if class.is_some() && !metal {
continue;
}
let s = Image::new(texture(0), [2, 2, 1], 1, 1, 1);
let d = Image::new(texture(1), [2, 2, 1], 1, 1, 1);
let mut h = Image::new(texture(2), [4, 4, 2], 1, 2, 1);
for (x, y) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
let at = h.index(1, 0, 0, [x, y, 0]).expect("texel");
h.texels[at] = texel.map(fl);
}
let mut res = resources(&plan, &[vec![0; 8]]);
if let Some(c) = class {
res.spec.insert(SpecKey::TexelFormat(slot), u64::from(c));
res.spec.insert(
SpecKey::PlainHalfTexels(slot),
u64::from(crate::metal::texel_format::TexelFormat(c).plain_on_metal_sampler()),
);
}
let (bufs, _) = run_both(&m, &res, &[s, d, h], [2, 2, 1])
.unwrap_or_else(|e| panic!("{stem}: {e:?}"));
let halves: Vec<u16> = bufs[0]
.as_chunks::<2>()
.0
.iter()
.map(|c| u16::from_le_bytes([c[0], c[1]]))
.collect();
assert_eq!(
halves,
want.map(|h| quantized(&p, h)),
"{stem} class {class:?}"
);
let s = Image::new(texture(0), [2, 2, 1], 1, 1, 1);
let d = Image::new(texture(1), [2, 2, 1], 1, 1, 1);
let mut h = Image::new(texture(2), [4, 4, 2], 1, 2, 1);
for (x, y) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
let at = h.index(1, 0, 0, [x, y, 0]).expect("texel");
h.texels[at] = texel.map(fl);
}
let res = resources(&plan, &[vec![0; 8]]);
let (bufs, _) =
run_both(&m, &res, &[s, d, h], [2, 2, 1]).unwrap_or_else(|e| panic!("{stem}: {e:?}"));
let halves: Vec<u16> = bufs[0]
.as_chunks::<2>()
.0
.iter()
.map(|c| u16::from_le_bytes([c[0], c[1]]))
.collect();
assert_eq!(halves, want.map(|h| quantized(&p, h)), "{stem}");
ran += 1;
}
assert!(ran > 0);
@@ -9353,7 +9353,6 @@ variant metal2vulkan-runtime::PrecisionNote::NativeMinMax NativeMinMax
variant metal2vulkan-runtime::PrecisionNote::NativeMix NativeMix
variant metal2vulkan-runtime::PrecisionNote::NativeNanEncoding NativeNanEncoding
variant metal2vulkan-runtime::PrecisionNote::NativeTranscendentals NativeTranscendentals
variant metal2vulkan-runtime::PrecisionNote::NotMipmappedAnisotropicFilter NotMipmappedAnisotropicFilter
variant metal2vulkan-runtime::PrecisionNote::PixelSamplerScaling PixelSamplerScaling
variant metal2vulkan-runtime::PrecisionNote::QuadsCountedBeforeDiscard QuadsCountedBeforeDiscard
variant metal2vulkan-runtime::PrecisionNote::QuadsSplitByClipping QuadsSplitByClipping
@@ -10272,7 +10271,6 @@ variant metal2vulkan::device::VkProperty::MetalHalfTexelWrites MetalHalfTexelWri
variant metal2vulkan::device::VkProperty::MetalInterpolation MetalInterpolation
variant metal2vulkan::device::VkProperty::MetalNormStorageWrites MetalNormStorageWrites
variant metal2vulkan::device::VkProperty::MetalNormalizedVertexFetch MetalNormalizedVertexFetch
variant metal2vulkan::device::VkProperty::MetalSampler MetalSampler
variant metal2vulkan::device::VkProperty::MetalSmallFloatNans MetalSmallFloatNans
variant metal2vulkan::device::VkProperty::MetalVertexSimdgroups MetalVertexSimdgroups
variant metal2vulkan::device::VkProperty::ProvokingVertexModePerPipeline ProvokingVertexModePerPipeline
@@ -10421,8 +10419,6 @@ variant metal2vulkan::error::DescriptorError::VertexAmplificationCount VertexAmp
variant metal2vulkan::error::DescriptorError::VertexAttribute VertexAttribute { attribute: u32 }
variant metal2vulkan::error::DescriptorError::VertexLayout VertexLayout { layout: u32 }
variant metal2vulkan::error::DescriptorError::VertexStepRate VertexStepRate { step_rate: u32 }
variant metal2vulkan::error::DriverDeviation::CubeGradientRoute CubeGradientRoute
variant metal2vulkan::error::DriverDeviation::GraphicsCubeGradientTangents GraphicsCubeGradientTangents
variant metal2vulkan::error::DriverDeviation::MetalAlphaCoverage MetalAlphaCoverage
variant metal2vulkan::error::DriverDeviation::MetalCenterVaryings MetalCenterVaryings
variant metal2vulkan::error::DriverDeviation::MetalDepth16BiasedStores MetalDepth16BiasedStores
@@ -10436,7 +10432,6 @@ variant metal2vulkan::error::DriverDeviation::MetalHalfTexelWrites MetalHalfTexe
variant metal2vulkan::error::DriverDeviation::MetalInterpolation MetalInterpolation
variant metal2vulkan::error::DriverDeviation::MetalNormStorageWrites MetalNormStorageWrites
variant metal2vulkan::error::DriverDeviation::MetalNormalizedVertexFetch MetalNormalizedVertexFetch
variant metal2vulkan::error::DriverDeviation::MetalSampler MetalSampler
variant metal2vulkan::error::DriverDeviation::MetalSmallFloatNans MetalSmallFloatNans
variant metal2vulkan::error::DriverDeviation::MetalVertexSimdgroups MetalVertexSimdgroups
variant metal2vulkan::error::DriverDeviation::SimdgroupLockstep SimdgroupLockstep
@@ -10938,7 +10933,6 @@ variant metal2vulkan::pipeline::PrecisionNote::NativeMinMax NativeMinMax
variant metal2vulkan::pipeline::PrecisionNote::NativeMix NativeMix
variant metal2vulkan::pipeline::PrecisionNote::NativeNanEncoding NativeNanEncoding
variant metal2vulkan::pipeline::PrecisionNote::NativeTranscendentals NativeTranscendentals
variant metal2vulkan::pipeline::PrecisionNote::NotMipmappedAnisotropicFilter NotMipmappedAnisotropicFilter
variant metal2vulkan::pipeline::PrecisionNote::PixelSamplerScaling PixelSamplerScaling
variant metal2vulkan::pipeline::PrecisionNote::QuadsCountedBeforeDiscard QuadsCountedBeforeDiscard
variant metal2vulkan::pipeline::PrecisionNote::QuadsSplitByClipping QuadsSplitByClipping
@@ -11178,11 +11172,9 @@ variant metal2vulkan::pipeline::SpecKey::BoundSamplerWord BoundSamplerWord(SlotR
variant metal2vulkan::pipeline::SpecKey::BoundTexelFormat BoundTexelFormat(SlotRef)
variant metal2vulkan::pipeline::SpecKey::ConstantLanes ConstantLanes(SlotRef)
variant metal2vulkan::pipeline::SpecKey::DeepThreadgroup DeepThreadgroup
variant metal2vulkan::pipeline::SpecKey::FilteringArgumentSampler FilteringArgumentSampler
variant metal2vulkan::pipeline::SpecKey::FlatLocalSize FlatLocalSize
variant metal2vulkan::pipeline::SpecKey::HeapNanFamilies HeapNanFamilies(Stage)
variant metal2vulkan::pipeline::SpecKey::HeapRawTextures HeapRawTextures(Stage)
variant metal2vulkan::pipeline::SpecKey::HeapYCbCrTextures HeapYCbCrTextures(Stage)
variant metal2vulkan::pipeline::SpecKey::ImageblockHeight ImageblockHeight
variant metal2vulkan::pipeline::SpecKey::ImageblockWidth ImageblockWidth
variant metal2vulkan::pipeline::SpecKey::LocalSize LocalSize(Axis)
@@ -11193,7 +11185,6 @@ variant metal2vulkan::pipeline::SpecKey::ObjectLocalSize ObjectLocalSize(Axis)
variant metal2vulkan::pipeline::SpecKey::ObjectMultiRegion ObjectMultiRegion
variant metal2vulkan::pipeline::SpecKey::OffsetBaseAxes OffsetBaseAxes(SlotRef)
variant metal2vulkan::pipeline::SpecKey::OutOfBoundsAlpha OutOfBoundsAlpha(SlotRef)
variant metal2vulkan::pipeline::SpecKey::PlainHalfTexels PlainHalfTexels(SlotRef)
variant metal2vulkan::pipeline::SpecKey::Presence Presence(SlotRef)
variant metal2vulkan::pipeline::SpecKey::RangeAtBindOffset RangeAtBindOffset(SlotRef)
variant metal2vulkan::pipeline::SpecKey::RenderAreaHeight RenderAreaHeight
@@ -11210,7 +11201,6 @@ variant metal2vulkan::pipeline::SpecKey::TgLength TgLength(u32)
variant metal2vulkan::pipeline::SpecKey::TgOffset TgOffset(u32)
variant metal2vulkan::pipeline::SpecKey::TileGridWidth TileGridWidth
variant metal2vulkan::pipeline::SpecKey::TileThreadgroupLength TileThreadgroupLength
variant metal2vulkan::pipeline::SpecKey::UnmeasuredTexels UnmeasuredTexels(SlotRef)
variant metal2vulkan::pipeline::Stage::Fragment Fragment
variant metal2vulkan::pipeline::Stage::Kernel Kernel
variant metal2vulkan::pipeline::Stage::Mesh Mesh
Can't render this file because it is too large.
-3
View File
@@ -2009,9 +2009,6 @@ bound.
no probe covers. The branch keeps the AIR's lanes, so that operation may answer over the lanes
that take the arm where Metal's answers over the block's. A branch Metal was measured to
speculate is speculated, and one it was measured to keep is kept, with no note.
- `metal2vulkan-degrade-not-mipmapped-anisotropic-filter` (precision).
`PrecisionNote::NotMipmappedAnisotropicFilter`: Recorded by no device: its condition, a device
whose sampler is Metal's own (`DriverDeviation::MetalSampler`), is one no profile takes.
- `metal2vulkan-degrade-device-sample-level` (precision). `PrecisionNote::DeviceSampleLevel`: An
extended-range texture's (`BGR10_XR`, `BGRA10_XR` and their sRGB twins) fragment sample at an
implicit level, or with explicit gradients, on every device: its texels are read in the shader, at