Leave color writes to the device's own conversion

One work packet, landed as 6 commits (886b08c25a..4df472aea2 on archive/development-linear-2026-10-28), in order:

* Leave color writes to the device's own conversion

The owner ruled that the GPU's native arithmetic is the contract and
the exact emulation goes. The fragment stage no longer rounds a float
output to Metal's codes before a color write where the device is not
measured to convert as Metal does: every lane is written as computed
and the device converts it.

Removed: the shader's unorm, snorm, sRGB, packed 16-bit (through half)
and small-float roundings at Metal's default rounding mode, the
draw-selected rule (ChannelWrite::Selected, PushField::ColorWriteRule,
GraphicsState::color_write_rules, StageIo::selected_colors and the
rule words), and the sRGB color-write table
(SyntheticBinding::ColorWriteTable, WriteSource::ColorWriteTable,
bind::color_write_table) with its runtime and validation binders.

Kept: the rounding to nearest even under TextureWriteRoundingMode::
NearestEven (an explicit Metal API mode no device's conversion makes),
word attachments the function encodes, the storage-form blends of
framebuffer fetch, the 16-bit output route, and the notes. A channel
the device converts unmeasured records DeviceColorConversion; a float
NaN to a half-float channel records DeviceNanEncoding where the device
is not measured to store Metal's. A blend of one and zero is dropped
from an attachment whose channels convert by a rule, as before, so a
device without the blend still draws it.

Bumps SEMANTICS_VERSION to 1874, ARTIFACT_FORMAT_VERSION to 457 (codec
lists lose fields and variants) and RUNTIME_VERSION to 1655 (the
binder no longer binds the table).

Verified: cargo clippy --workspace --all-targets --all-features -D
warnings, plain and with --cfg m2v_gpu, clean; cargo nextest (color
writes, link, stage io, fragment, binder, blend8, api_surface, srgb,
extended range, word, fetch, fast_paths, catalogue, degradation,
profile, codec, compile, push): 694 of 694 passed. Device lanes not
run (no device tests in this lane).

* Leave storage-texture writes to the device's own conversion

On the owner's ruling that the GPU's native arithmetic is the contract,
a kernel's (or any stage's) float or half write to a storage texture
no longer rounds to Metal's codes in the shader where the device is
not measured to store them.

Removed: the normalized write's rounding by the bound format's class
(lower/texture/norm_write.rs, NormWrite, the slot's norm_write flag,
the heap's norm routine and its census entry), the 1-bit alpha's
rounding on a device that stores every other normalized channel as
Metal does (StorageImageClass::OneBitAlpha, the heap's one-bit class
test, texel_format::heap_one_bit_indices), ARGB8Unorm's code rounding
(RotateArgb now only rotates), and the half-float write's rounding
toward zero (StorageImageClass::HalfTowardZero): a half-float write
takes Identity where the device stores Metal's NaN, else HalfQuietNan.

Recorded instead: PrecisionNote::DeviceColorConversion for a write
that may reach a normalized format (ARGB8Unorm included) on a device
without MetalNormStorageWrites, or a 1-bit alpha on one with it, and
for a half-float write on a device without MetalHalfStorageWrites;
where measured, the module requires the property. Imageblock slice
writes record the same.

Kept: the HalfBits route (a half-float texture written through its
unsigned integer alias where the device does not keep a half's NaN
bits) as it is, its float texels still rounded toward zero, since the
alias has no conversion of the device's; the NaN quieting classes;
sRGB encodes; extended-range encodes; RGB9E5's word.

The device lanes for normalized and half storage writes, and the
extended-range planes lane's ARGB8 alpha, now hold a channel to
Metal's only where the device is measured to store it, and print the
rest.

Verified: cargo clippy --workspace --all-targets --all-features -D
warnings, plain and with --cfg m2v_gpu, clean; cargo nextest
(engine_handles, engine_extended_range, engine_link, engine_rgbx,
engine_texture, metal::format, texel_format, bind::heap, engine_access,
engine_heap, engine_texel_nans, storage, lower::texture,
lower::arith::tests, fast_paths, catalogue, degradation, profile,
api_surface): 1028 run, 1 failure fixed, then engine_link 26 of 26.
Device lanes not run.

* Leave Depth16Unorm depth stores to the device's own conversion

The owner's ruling ("Just promise the GPU's native arithmetics, no more
'exact' emulation") makes the device's own conversion of a fragment's
depth to a Depth16Unorm code, and its own depth bias, the contract.
The fragment stage no longer rounds its depth to Metal's 16-bit code,
nor adds Metal's bias in the shader, where MetalDepth16Stores or
MetalDepth16BiasedStores is absent: the depth is written as computed
and the attachment's fixed-function bias applies on every device.

Deleted with it: lower/stage_io/depth16.rs and its arith tests, the
engine_depth16_codes tests, the pipeline's depth16 stage form and its
variant key fields, the Depth16 runtime facts and their codec entries,
the DepthBias push field, the binder's depth16 selection and state, the
runtime's sided-bias push and its work count.

Removed public items: Degradation::ShaderUnormDepth and
Degradation::UnormDepthSlope (nothing can record them any more; their
API.md catalogue entries go too), WorkCounts::depth16_sided_draws,
metal::state::depth16_bias and depth16_bias_side, the four RuntimeFact
Depth16 variants, PushField::DepthBias, and the depth16 fields of
VariantKey, BindState and BindShape. UnormDepthBias and
UnormDepthRounding stay: they describe the native answer and are still
announced where the drivers are not measured to give Metal's codes.

The FAST-PATHS "Costs of matching Metal" bullet for Depth16 goes; the
API.md bias and rounding entries now describe the native answer. The
device lane unorm_depth_bias holds Metal's codes only where measured.
The cache versions were already taken for this lane (1874/457/1655).

Verified: cargo clippy --workspace --all-targets --all-features -D
warnings, plain and with --cfg m2v_gpu; rustdoc with -D warnings;
cargo nextest over mechanism, api_tests, bind_shape, pipeline::compile,
link tests, engine_stage_io, engine_fragment, metal::state,
bind::graphics, cache tests, engine_graphics_binder, depth, fast_paths,
catalogue, degradation, profile, api_surface, notice, work_counts,
draw_shape, render_state and codec across metal2vulkan,
metal2vulkan-runtime and metal2vulkan-conformance: 750 passed. Device
lanes not run; refusals regenerate unchanged.

* Drop two doc references to removed colour and depth16 machinery

The runtime's stage digest doc still listed a synthesized depth16
fragment stage among the link's stages, and the sRGB storage lane's
module doc still named bind::color_write_table, both removed on this
branch. The stage list now names only the stages the link still
synthesizes, and the lane's doc names bind::SRGB_RESOLVE_THRESHOLDS,
the table it reads.

Doc comments only; verified by cargo fmt and the rustdoc build below.

* Re-bless the public signatures after the write conversions' removal

The branch removed the Metal colour-write rule selection, the shader's
storage-texture rounding and the shader's Depth16Unorm codes; the
table now drops their 30 public records (ChannelWrite::Selected,
PushField::ColorWriteRule and DepthBias, the ColorWriteTable binding
and write source, bind::color_write_table, GraphicsState's
color_write_rules, the four RuntimeFact Depth16 variants,
StorageImageClass::HalfTowardZero and OneBitAlpha, the depth16 fields
of LoweringInputs, VariantKey, BindState and BindShape,
metal::state::depth16_bias and depth16_bias_side,
Degradation::ShaderUnormDepth and UnormDepthSlope, and
WorkCounts::depth16_sided_draws). Removals only; nothing added or
changed.

Verified: python3 scripts/api-signatures/signatures.py --bless, the
diff read line by line, and cargo nextest over api_signatures and
fast_paths: 17 passed.

* Re-pin the runtime sources at the landing tip

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

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
This commit is contained in:
Anees Iqbal committed 2026-10-28 17:24:20 +02:00
1 parent b7a62be64b
commit 70068f7cc0
80 files changed
+940 -5456

No files matched your search

@@ -1181,16 +1181,16 @@ impl Case for DepthCodes {
// the chip's GPU shares the CPU's memory, it cannot fire at all, which is why no
// recording of this suite declares it.
//
// Two more, both declarations and neither touching a depth code: a `DontCare` depth store
// our side keeps where Metal may drop it (`dont-care-store`), and a normalized depth our
// side writes through the shader where the device's own store is not Metal's
// (`shader-unorm-depth`). Both announced by this row on the 5080 and on llvmpipe (Mesa
// 26.2.4) with the case declaring neither, and `shader-unorm-depth` by this row alone in
// the family.
// Two more, both declarations: a `DontCare` depth store our side keeps where Metal may
// drop it (`dont-care-store`, announced by this row on the 5080 and on llvmpipe, Mesa
// 26.2.4, with the case declaring it nowhere), and a normalized depth the device converts
// where it is not measured to store Metal's code (`unorm-depth-rounding`; expected on
// both, unmeasured since the device's own conversion became the only form). Neither
// loosens a depth code.
vec![
crate::replay::shared_memory_notice(),
crate::replay::notice_allowance(Degradation::DontCareStore.code()),
crate::replay::notice_allowance(Degradation::ShaderUnormDepth.code()),
crate::replay::notice_allowance(Degradation::UnormDepthRounding.code()),
]
}
@@ -1727,7 +1727,6 @@ impl Gpu for Runtime {
("no_copy_lies_read", c.no_copy_lies_read),
("commands_noted_as_before", c.commands_noted_as_before),
("draws_settled", c.draws_settled),
("depth16_sided_draws", c.depth16_sided_draws),
("two_plane_draws", c.two_plane_draws),
("bound_notices_made", c.bound_notices_made),
("argument_tables_retained", c.argument_tables_retained),
@@ -2004,11 +2004,6 @@ fn descriptor(
// The command buffer's status words, the ones every command of it writes, on a device
// that does not address buffers (`status_address` elsewhere).
WriteSource::ExecutionStatus => whole(state.status_words(device)?),
// The fragment stage's sRGB color table, the same bytes for every pipeline.
WriteSource::ColorWriteTable => {
let table = metal2vulkan::bind::color_write_table();
whole(upload(table, padded(table.len()))?)
}
// A read-only binding takes the device's kept zero buffer, made once for its lifetime
// (`neutral.rs`): zeros of a length the device's own limits fix cannot have changed since
// it was made, and before this every draw and dispatch that bound one took a fresh
+11 -31
View File
@@ -319,37 +319,17 @@ degradations! {
read in every run measured";
/// A draw biases a `Depth16Unorm` depth by a constant, or by a slope alone, which brings
/// Metal's constant unit, on a device whose driver is not measured to store Metal's codes
/// so (`DriverDeviation::MetalDepth16BiasedStores`, `render_state.rs`), through a
/// pipeline whose fragment stage does not add the bias itself (more than one sample,
/// early fragment tests, the draw's tests run in the shader, a function that returns its
/// depth or reads its position's depth).
/// so (`DriverDeviation::MetalDepth16BiasedStores`, `render_state.rs`): the device biases
/// and converts the depth.
UnormDepthBias = "unorm-depth-bias", Precision,
"a biased depth can store a code next to Metal's: the device rounds the biased sum \
its own way, and without depthBiasExact counts the bias in its own unit";
/// A draw tests or writes a `Depth16Unorm` depth on a device whose driver is not measured
/// to convert a depth to Metal's code (`DriverDeviation::MetalDepth16Stores`,
/// `render_state.rs`), through a pipeline whose fragment stage cannot write the code
/// itself (more than one sample, early fragment tests, the draw's tests run in the shader,
/// a function that reads its position's depth and returns none), or through one that
/// does, in depth clamp mode, whose range the device clamps the depth to.
/// `render_state.rs`): the device converts the depth.
UnormDepthRounding = "unorm-depth-rounding", Precision,
"a depth near a code's midpoint can store the code below Metal's: the device converts \
the depth to the 16-bit code its own way, where Metal rounds to nearest, a tie up";
/// A draw tests or writes a `Depth16Unorm` depth through a fragment stage that writes each
/// depth as Metal's code, on a device whose driver is not measured to store Metal's codes
/// (`DriverDeviation::MetalDepth16Stores`, or for a biased draw
/// `DriverDeviation::MetalDepth16BiasedStores`; `RuntimeFact::Depth16Codes`,
/// `render_state.rs`); a pipeline without a fragment function draws through a fragment
/// stage of its own.
ShaderUnormDepth = "shader-unorm-depth", Performance,
"the fragment stage writes each depth as Metal's code, about 50 more instructions \
per fragment, which keeps the device from testing the depth before the stage runs";
/// A draw biases a `Depth16Unorm` depth by a slope through a fragment stage that adds
/// Metal's bias itself (`RuntimeFact::Depth16Codes`, `render_state.rs`).
UnormDepthSlope = "unorm-depth-slope", Precision,
"the fragment stage takes the depth's slope from the depths of its 2x2 quad, where \
Metal takes the triangle's own: a biased depth near a code's midpoint can store \
the code next to Metal's";
/// A draw of points keeps Vulkan's clipping of points, where Metal's guard band cannot be
/// emulated: in a rate-mapped pass, on a device without `shaderClipDistance` or with too
/// few clip distances beside the vertex function's own, or through a viewport whose
@@ -543,13 +523,12 @@ degradations! {
sample planes) and writes the resolve texture, where the device would resolve in \
the pass; where the attachment's image takes no input attachment usage, a copy of \
its samples over the render area into a scratch image first";
/// A fragment function writes a float to a normalized, sRGB or half-float color
/// attachment on a device whose own conversion is not Metal's
/// (`StageModule::rounded_colors`).
/// A fragment function writes a float to a half-float color attachment of a pipeline
/// under `TextureWriteRoundingMode::NearestEven`, whose rounding no device's conversion
/// gives (`StageModule::rounded_colors`).
ShaderColorConversion = "shader-color-conversion", Performance,
"the fragment function rounds each such channel to the code Metal stores before it \
writes it: about 35 more instructions per normalized or half-float channel, and \
about 70 and one read of a 4 KiB table per sRGB channel";
"the fragment function rounds each such channel to nearest even before it writes it: \
about 35 more instructions per channel";
/// A fragment function writes a `half` to a half-float color attachment as the bits of
/// the half Metal stores, through a 16-bit output, on a device that does not store a
/// 32-bit output's NaN as Metal does (`StageModule::half_bit_colors`).
@@ -3162,8 +3141,9 @@ impl Device {
(
object(),
format!(
"the device's conversion of a float to the format of color \
attachment(s) {:?} is not Metal's near a tie between two codes",
"the pipeline rounds the half-float channels of color \
attachment(s) {:?} to nearest even (its texture write rounding \
mode), which the device's conversion does not",
stage.rounded_colors
),
)
@@ -2551,12 +2551,11 @@ impl CompiledVariant {
/// **A stage cannot be matched to a function by position.** A pipeline's stages carry the ones
/// the link synthesizes -- a post-tessellation vertex function's vertex and tessellation control
/// stages, the geometry stages a barycentric or layer-selecting function needs, one per topology
/// class, a depth16 fragment stage -- spliced in among the compiled ones, so stage `i` is not
/// function `i`. What matches them is the identity of the words: a compiled stage's words are
/// the very allocation its function's relocation slot holds, which is what
/// `CompiledFunction::relocated_words_digest` answers for and nothing else. A stage no function
/// claims is a synthesized one, whose words no slot ever held, and it is hashed here as every
/// stage was before.
/// class -- spliced in among the compiled ones, so stage `i` is not function `i`. What matches
/// them is the identity of the words: a compiled stage's words are the very allocation its
/// function's relocation slot holds, which is what `CompiledFunction::relocated_words_digest`
/// answers for and nothing else. A stage no function claims is a synthesized one, whose words no
/// slot ever held, and it is hashed here as every stage was before.
fn stage_words_digest(functions: &[CompiledFunction], stage: &StageModule) -> Hash256 {
functions
.iter()
+2 -23
View File
@@ -881,10 +881,6 @@ struct DrawSettings {
/// The pass's colors it zeroes and its own it drops (`ShapeInputs::routed_colors`): the
/// encoder's, held, where it keeps them for its pipeline state in its pass (`Routed`).
routed_colors: Arc<RoutedColors>,
/// Whether the depth it renders against is `Depth16Unorm` (`BindState::depth16_pass`).
depth16_pass: Option<bool>,
/// The side of its depth bias (`BindState::depth16_bias_raises`).
depth16_bias_raises: Option<bool>,
/// Its `VkPipeline` takes the last provoking vertex (`render/provoking.rs`,
/// `FixedState::provoking_last`).
provoking_last: bool,
@@ -5771,7 +5767,6 @@ impl RenderLowering {
});
state.primitive_type = None;
state.depth_range = <[f32; 2]>::default();
state.depth_bias = [0.0; 3];
reshape
}
@@ -7287,7 +7282,6 @@ impl RenderLowering {
let (topology, primitive_restart) = (settings.topology, settings.primitive_restart);
let unsized_points = settings.unsized_points;
let (native, compensation) = (settings.native, settings.compensation);
let bias_effect = settings.bias;
let hidden_depth = settings.hidden;
let (_, stencil) = self.layout.aspects();
let max = pipeline.base().graphics.max_vertex_amplification_count;
@@ -7356,9 +7350,6 @@ impl RenderLowering {
(&mut argument_samplers, &mut unlisted),
(&function_tables, &mut snapshot),
)?;
if plan.variant.depth16_bias_raises.is_some() {
self.core.device().shared().counts.depth16_sided_draw();
}
let planes = |form: &ExtendedRange| matches!(form, ExtendedRange::Planes { .. });
if plan.variant.extended_range.values().any(planes) {
self.core.device().shared().counts.two_plane_draw();
@@ -7423,12 +7414,6 @@ impl RenderLowering {
graphics.writes_depth,
)?;
}
// A fragment stage that adds the draw's depth bias itself reads Metal's factors as push
// data, the draw's Vulkan bias recorded as zero (`render_state::depth16_codes`).
let depth16 = render_state::depth16_codes(&variant.pipeline().dependencies);
if depth16 == Some(true) {
live.state.depth_bias = render_state::depth16_push_bias(bias_effect);
}
let interface = &variant.pipeline().interface;
// A pulled attribute's 32-bit displacement past 4 GiB of its buffer
// (`render/vertex_reach.rs`).
@@ -8419,7 +8404,7 @@ impl RenderLowering {
Some(kept) => {
debug_assert!(
(self.shape_inputs())
.draw_state(graphics, &settings, failed, depth16)
.draw_state(graphics, &settings, failed)
.is_ok_and(|fresh| fresh == kept),
"a draw's state derived again differs from the one kept for its inputs"
);
@@ -8428,7 +8413,7 @@ impl RenderLowering {
None => {
let watch = EachWatch::start();
let inputs = self.shape_inputs();
let shaped = inputs.draw_state(graphics, &settings, failed, depth16)?;
let shaped = inputs.draw_state(graphics, &settings, failed)?;
// Kept where its derivation announced nothing at each occurrence.
if let (Some(token), false) = (shape_token, watch.met()) {
self.shape_memo.keep_state(token, &variant, &shaped);
@@ -9883,12 +9868,6 @@ impl RenderLowering {
);
let colors = &settings.routed_colors;
reshape.field_from(&mut state.zeroed_colors, &colors.zeroed);
reshape.field(&mut state.depth16_pass, settings.depth16_pass);
reshape.field(
&mut state.depth16_biased,
render_state::biases_depth(settings.bias),
);
reshape.field(&mut state.depth16_bias_raises, settings.depth16_bias_raises);
reshape.field(&mut state.primitive_id_indices, primitive_id_indices);
reshape.field(&mut state.quad_primitive_ids, private.quad_primitive_ids);
reshape.field(&mut state.private_list, private.private_list);
@@ -276,13 +276,6 @@ impl ShapeInputs<'_> {
// tests such a draw (its validation stops it; `render_state.rs`).
let ds = self.layout.depth_stencil.as_ref();
let (depth, _) = self.layout.aspects();
// The depth it renders against, whose format decides what the draw stores there whatever
// the pipeline names (`BindState::depth16_pass`): the pass's attachment's, or the hidden
// `float` one's.
let depth16_pass = ds
.and_then(|ds| ds.depth_format)
.or(hidden.then_some(HIDDEN_DEPTH_FORMAT))
.map(|format| format == PixelFormat::Depth16Unorm);
// A compare of `Never` without Metal's depth attachment fails every fragment (probes), the
// hidden depth's too: the draw runs as `FailingDraw` says.
let metal_depth = depth && !ds.is_some_and(|ds| ds.hidden);
@@ -427,12 +420,6 @@ impl ShapeInputs<'_> {
// range (`clamp_draw_depth`).
let compensated = compensation.is_some_and(|c| c.depth.is_some());
let native = native && !compensated;
let depth16_bias_raises = render_state::depth16_bias_side(
self.state,
base.writes_viewport_index,
bias,
compensation,
);
let provoking_last = provoking::natively_last(device, self.state, (pipeline, assembly));
Ok(DrawSettings {
unsized_points,
@@ -448,8 +435,6 @@ impl ShapeInputs<'_> {
bias,
routing,
routed_colors,
depth16_pass,
depth16_bias_raises,
provoking_last,
})
}
@@ -527,9 +512,8 @@ impl ShapeInputs<'_> {
/// The state a draw of `graphics`, its variant's, records with under `settings`
/// ([`DrawState`]: statically, or as dynamic state), failing as `failing` says, its fragment
/// function the stencil test (`shadow`, a shader-side stencil) or the depth test (`tests`),
/// and adding Metal's depth bias itself where `depth16` says so
/// (`render_state::depth16_codes`); with the viewports in Metal's terms and the compensated
/// function the stencil test (`shadow`, a shader-side stencil) or the depth test (`tests`);
/// with the viewports in Metal's terms and the compensated
/// depth range a rate-mapped pass draws each region through (`rate_mapped_pass.rs`). A 16-bit
/// unorm depth's notice and an unclamped bias's are announced.
pub(super) fn draw_state(
@@ -537,7 +521,6 @@ impl ShapeInputs<'_> {
graphics: &GraphicsState,
settings: &DrawSettings,
(failing, shadow, tests): (Option<&FailingDraw>, bool, bool),
depth16: Option<bool>,
) -> Result<ShapedState, Error> {
let device = self.device;
let profile = device.compile_device().profile();
@@ -555,28 +538,14 @@ impl ShapeInputs<'_> {
.as_ref()
.and_then(|ds| ds.depth_format)
.or(settings.hidden.then_some(HIDDEN_DEPTH_FORMAT));
// A fragment stage that adds Metal's bias itself takes none from the device.
let bias = match depth16 {
Some(true) => EncoderState::vk_no_depth_bias(topology, profile)?,
_ => self.state.vk_depth_bias(topology, depth_format, profile)?,
};
let bias = self.state.vk_depth_bias(topology, depth_format, profile)?;
let depth_bias = DepthBiasRecord::of(&bias, device.shared().depth_bias_command)?;
// A 16-bit unorm depth, biased or not, stores Metal's codes where the fragment stage
// writes them or the driver is measured to (`render_state::announce_unorm_depth`).
let sloped =
matches!(bias_effect, Some(DepthBiasEffect::Factors { slope, .. }) if slope != 0.0);
let clamped_inside = render_state::clamps_inside(self.state, selects);
render_state::announce_unorm_depth(
device,
depth_format,
&fixed.depth_stencil,
(&bias, sloped),
(depth16, clamped_inside),
);
// A 16-bit unorm depth, biased or not, stores Metal's codes where the driver is measured
// to (`render_state::announce_unorm_depth`).
render_state::announce_unorm_depth(device, depth_format, &fixed.depth_stencil, &bias);
// In clip mode a natively ranged device clamps a biased depth to `[0, 1]`
// (`EncoderState::depth_range`); one that stores it unclamped without that announces it.
// A fragment stage that adds Metal's bias itself clamps the biased depth to `[0, 1]`.
if depth16 != Some(true) && !graphics.rasterizer_discard {
if !graphics.rasterizer_discard {
let compensated = compensation.is_some_and(|c| c.depth.is_some());
render_state::announce_unclamped_bias(device, self.state, bias_effect, compensated);
}
+9 -149
View File
@@ -111,7 +111,7 @@ use metal2vulkan::error::{Capability, Feature, RuntimeDriverDefect, Unsupported}
use metal2vulkan::metal::{
CullMode, DepthClipMode, PixelFormat, StencilOperation, TriangleFillMode, Winding,
};
use metal2vulkan::pipeline::{GraphicsState, RuntimeDependency, RuntimeFact, ViewportCompensation};
use metal2vulkan::pipeline::{GraphicsState, ViewportCompensation};
/// Metal's most viewports and scissor rectangles.
pub(super) const MAX_VIEWPORTS: usize = 16;
@@ -1105,17 +1105,6 @@ impl EncoderState {
.map_err(device_error)
}
/// No Vulkan depth bias for a pipeline of `topology`, for a draw whose fragment stage adds
/// Metal's bias itself (`RuntimeFact::Depth16Codes`): the bias stays enabled as for any draw,
/// its factors 0.
pub(super) fn vk_no_depth_bias(
topology: metal2vulkan::vk::PrimitiveTopology,
profile: &DeviceProfile,
) -> Result<metal2vulkan::metal::state::DepthBias, Error> {
metal2vulkan::metal::state::depth_bias(topology, 0.0, 0.0, 0.0, None, profile)
.map_err(device_error)
}
/// `Unsupported(LayeredRendering)` needing `multiViewport` on a device without it, for a
/// draw that would select among more than one viewport.
pub(super) fn needs_viewports(profile: &DeviceProfile) -> Result<(), Error> {
@@ -1960,153 +1949,24 @@ fn clamp_range(viewport: &Viewport) -> [f32; 2] {
range.map(|z| z as f32)
}
/// How a draw's fragment stage writes a `Depth16Unorm` depth: its variant's
/// `RuntimeFact::Depth16Codes` among `dependencies`, `Some(biased)` where the stage writes Metal's
/// codes itself (`LoweringInputs::depth16_codes`), `biased` where it adds the draw's bias, so the
/// draw records a Vulkan bias of zero and pushes Metal's (`BindState::depth_bias`). `None` where
/// the device converts the depth itself.
pub(super) fn depth16_codes(dependencies: &[RuntimeDependency]) -> Option<bool> {
dependencies.iter().find_map(|d| match d.fact {
RuntimeFact::Depth16Codes { biased } => Some(biased),
_ => None,
})
}
/// Whether a draw whose primitives take `bias` biases their depths by Metal's factors
/// (`BindState::depth16_biased`): a constant or slope factor other than 0, for triangles whose
/// viewports take no bias.
pub(super) fn biases_depth(bias: Option<DepthBiasEffect>) -> bool {
matches!(
bias,
Some(DepthBiasEffect::Factors { constant, slope, .. }) if constant != 0.0 || slope != 0.0
)
}
/// The side of the depth bias a fragment stage that adds it itself takes for a draw whose
/// primitives take `bias` through the viewports it uses (all where the pipeline `selects` one)
/// under `compensation` (`BindState::depth16_bias_raises`): Metal's factors of a known side
/// (`metal::state::depth16_bias_side`), where every Vulkan depth range of the draw lies inside
/// `[0, 1]`. A used viewport's range inside it is its Vulkan range and gives a Vulkan depth clamp
/// of `[0, 1]` (`EncoderState::draw_viewports`, `EncoderState::depth_range`); a compensated depth's
/// Vulkan range must lie inside it too. `None` for any other draw, which keeps the stage that
/// declares no side.
pub(super) fn depth16_bias_side(
state: &EncoderState,
selects: bool,
bias: Option<DepthBiasEffect>,
compensation: Option<Compensation>,
) -> Option<bool> {
let Some(DepthBiasEffect::Factors {
constant,
slope,
clamp,
}) = bias
else {
return None;
};
let inside = |z: f32| (0.0..=1.0).contains(&z);
let compensated = compensation
.and_then(|c| c.depth)
.is_some_and(|range| !range.into_iter().all(inside));
if compensated || state.used_viewports(selects).iter().any(outside_depth) {
return None;
}
metal2vulkan::metal::state::depth16_bias_side(constant, slope, clamp)
}
/// The depth bias a fragment stage that adds it itself pushes for a draw whose primitives take
/// `bias` (`BindState::depth_bias`): Metal's factors (`metal::state::depth16_bias`), and none for
/// points and lines or a bias the draw's viewports take (saturated or offset), which its
/// `FragCoord.z` carries.
pub(super) fn depth16_push_bias(bias: Option<DepthBiasEffect>) -> [f32; 3] {
match bias {
Some(DepthBiasEffect::Factors {
constant,
slope,
clamp,
}) => metal2vulkan::metal::state::depth16_bias(constant, slope, clamp),
_ => [0.0; 3],
}
}
/// Whether a draw in depth clamp mode clamps its depth to a range one of whose ends lies inside
/// `(0, 1)`, among the viewports it uses (`selects`: its vertex function chooses one): the device
/// clamps a depth there to that end and converts it its own way, past a fragment stage that
/// writes Metal's code (`announce_unorm_depth`).
pub(super) fn clamps_inside(state: &EncoderState, selects: bool) -> bool {
state.clip_mode == DepthClipMode::Clamp
&& state
.used_viewports(selects)
.iter()
.flat_map(clamp_range)
.any(|end| end > 0.0 && end < 1.0)
}
/// Announce once what a draw of `depth_stencil` stores in a `Depth16Unorm` depth
/// (`depth_format`), whose fragment stage writes it as `codes` says ([`depth16_codes`]) under the
/// Vulkan bias `bias`, Metal's slope factor being nonzero where `sloped`.
///
/// Where the fragment stage writes Metal's codes, the draw tests or writes through it
/// (`shader-unorm-depth`), a biased stage adding a slope takes it from the quad's depths
/// (`unorm-depth-slope`), and a draw that clamps the depth to a range end inside `(0, 1)`
/// (`clamped_inside`, [`clamps_inside`]) stores the device's conversion of that end
/// (`unorm-depth-rounding`).
///
/// Elsewhere the device converts the depth: a constant bias, or a slope alone, which brings
/// Metal's constant unit, stores Metal's codes only where the profile takes
/// `DriverDeviation::MetalDepth16BiasedStores` (`unorm-depth-bias`), and any depth it tests or
/// writes only where the profile takes `DriverDeviation::MetalDepth16Stores`
/// (`unorm-depth-rounding`). A biased draw on a profile that takes the second but not the first
/// runs the variant whose fragment stage adds the bias (`BindState::depth16_biased`), unless its
/// fragment stage cannot write the code. Metal biases by `c ± 1` units of 1/65535 as `float`
/// (`metal::state::depth_bias`), adds the bias to the depth rounded toward zero, and stores the
/// sum rounded to nearest, a tie up (probes).
/// (`depth_format`) under the Vulkan bias `bias`: the device converts the depth, so a constant
/// bias, or a slope alone, which brings Metal's constant unit, stores Metal's codes only where the
/// profile takes `DriverDeviation::MetalDepth16BiasedStores` (`unorm-depth-bias`), and any depth it
/// tests or writes only where the profile takes `DriverDeviation::MetalDepth16Stores`
/// (`unorm-depth-rounding`). Metal biases by `c ± 1` units of 1/65535 as `float`
/// (`metal::state::depth_bias`), adds the bias to the depth rounded toward zero, and stores the sum
/// rounded to nearest, a tie up (probes).
pub(super) fn announce_unorm_depth(
device: &Device,
depth_format: Option<PixelFormat>,
depth_stencil: &metal2vulkan::metal::state::DepthStencilState,
(bias, sloped): (&metal2vulkan::metal::state::DepthBias, bool),
(codes, clamped_inside): (Option<bool>, bool),
bias: &metal2vulkan::metal::state::DepthBias,
) {
use metal2vulkan::metal::state::DepthBiasUnit;
if depth_format != Some(PixelFormat::Depth16Unorm) {
return;
}
if let Some(biased) = codes {
if depth_stencil.depth_test_enable {
device.degrade(Degradation::ShaderUnormDepth, || {
(
"a draw testing or writing a Depth16Unorm depth".to_owned(),
"the device is not measured to store Metal's 16-bit codes".to_owned(),
)
});
}
if depth_stencil.depth_test_enable && clamped_inside {
device.degrade(Degradation::UnormDepthRounding, || {
(
"a draw clamping a Depth16Unorm depth to a viewport depth range in depth \
clamp mode"
.to_owned(),
"the device clamps a depth past the range to its end, an end inside (0, 1), \
and converts that end to its 16-bit code its own way, where Metal rounds it \
to nearest, a tie up"
.to_owned(),
)
});
}
if biased && sloped {
device.degrade(Degradation::UnormDepthSlope, || {
(
"a draw biasing a Depth16Unorm depth by a slope".to_owned(),
"the fragment stage takes the depth's slope from the depths of its 2x2 quad, \
where Metal takes the triangle's own: a biased depth near a code's midpoint \
can store the code next to Metal's"
.to_owned(),
)
});
}
return;
}
use metal2vulkan::error::DriverDeviation::{MetalDepth16BiasedStores, MetalDepth16Stores};
let profile = device.compile_device().profile();
let stores = profile.takes_driver_deviation(MetalDepth16Stores);
@@ -47,12 +47,8 @@ const UNRELATED: [Degradation; 10] = [
/// The kinds a `Depth16Unorm` draw's state announces (`render_state::announce_unorm_depth`),
/// which of them depending on the device's profile.
const UNORM_DEPTH: [Degradation; 4] = [
Degradation::ShaderUnormDepth,
Degradation::UnormDepthRounding,
Degradation::UnormDepthSlope,
Degradation::UnormDepthBias,
];
const UNORM_DEPTH: [Degradation; 2] =
[Degradation::UnormDepthRounding, Degradation::UnormDepthBias];
/// The notices a device announced.
type Heard = Arc<Mutex<Vec<DegradeNotice>>>;
@@ -229,7 +229,6 @@ pub(crate) struct Counters {
no_copy_lies_read: AtomicU64,
commands_noted_as_before: AtomicU64,
draws_settled: AtomicU64,
depth16_sided_draws: AtomicU64,
two_plane_draws: AtomicU64,
provoking_last_pipeline_draws: AtomicU64,
provoking_listed_draws: AtomicU64,
@@ -1600,12 +1599,6 @@ impl Counters {
self.draws_settled.fetch_add(1, Ordering::Relaxed);
}
/// A draw ran the variant whose fragment stage declares its `Depth16Unorm` depth bias's side
/// (`VariantKey::depth16_bias_raises`).
pub(crate) fn depth16_sided_draw(&self) {
self.depth16_sided_draws.fetch_add(1, Ordering::Relaxed);
}
/// A draw ran a variant that takes a slot bound to a two-plane extended-range texture
/// (`VariantKey::extended_range`).
pub(crate) fn two_plane_draw(&self) {
@@ -3877,11 +3870,6 @@ pub struct WorkCounts {
/// Draws that settled their variant and plan from their bind shapes: none for a draw whose
/// bind shape is one of the latest its pipeline state settled in the same buffer forms.
pub draws_settled: u64,
/// Draws that ran the variant whose fragment stage adds a `Depth16Unorm` depth's bias itself
/// and declares its side (`DepthGreater` or `DepthLess`), where the bias's side is known: the
/// device may then test the depth before the stage runs, which a stage that writes its depth
/// otherwise keeps it from.
pub depth16_sided_draws: u64,
/// Draws that ran a variant taking a texture slot bound to a two-plane extended-range texture
/// (`RGB10A8_2P_XR10` or its sRGB twin), read or sampled: the variant's function reads the
/// slot's raw texels and decodes them, and filters each linear sample of the slot itself over
@@ -5061,7 +5049,6 @@ impl Device {
no_copy_lies_read: counters.no_copy_lies_read.load(Ordering::Relaxed),
commands_noted_as_before: counters.commands_noted_as_before.load(Ordering::Relaxed),
draws_settled: counters.draws_settled.load(Ordering::Relaxed),
depth16_sided_draws: counters.depth16_sided_draws.load(Ordering::Relaxed),
two_plane_draws: counters.two_plane_draws.load(Ordering::Relaxed),
provoking_last_pipeline_draws: counters
.provoking_last_pipeline_draws
@@ -1 +1 @@
edae53caf8da1803d1376c29fea6c6379d3f650f78fbb5b067d46c05cac19023
8dfdbe852e2042225ae5ecaa4677869e32417533984dbe01f946d00bbdc2bce9
@@ -513,12 +513,6 @@ impl<'a> PlanResources<'a> {
.range(ExecutionStatus::BYTES as u64),
)
}
// The fragment stage's sRGB color table.
WriteSource::ColorWriteTable => {
let table = metal2vulkan::bind::color_write_table();
let buffer = self.buffer(context, "color write table", table)?;
whole(buffer)
}
WriteSource::Texture { slot, view } => {
let (image, layout) = self.image(TextureKey::Slot(*slot))?;
let view = self.view(context, image, view)?;
@@ -43,13 +43,14 @@
//! `DriverDeviation::MetalFloatColorNans` and `MetalHalfColorNans`, or to store a 16-bit output's
//! bits, `HalfColorOutputBits`, through which MoltenVK writes a `half` output), and for every other
//! channel, a NaN's class included, the lane is exact. A case written through a 16-bit output says
//! so. On every device but MoltenVK on Apple's GPUs, which converts as Metal does, the fragment
//! function rounds the output by these rules itself, except where the driver is measured to convert
//! a kind of channel as Metal does (`DriverDeviation::MetalSmallFloatColorWrites`, a `float` output
//! to a half-float or `RG11B10Float` channel, and `MetalNorm16ColorWrites`, an output to a 16-bit
//! unorm or snorm channel), where it writes the output as computed, a NaN chosen: a case whose
//! fragment stage rounds nothing says so, and the lane then holds the device's own conversion to
//! Metal's, the measurement of the deviation on that device.
//! so. The fragment function writes the output as computed and the device converts it: where the
//! device is measured to convert the kind of channel as Metal does (MoltenVK on Apple's GPUs,
//! `DriverDeviation::MetalColorWrites`; `MetalSmallFloatColorWrites`, a `float` output to a
//! half-float or `RG11B10Float` channel; `MetalNorm16ColorWrites`, an output to a 16-bit unorm or
//! snorm channel) the lane holds the device's conversion to Metal's, the measurement of the
//! deviation on that device; elsewhere the fragment stage records the device's conversion
//! (`PrecisionNote::DeviceColorConversion`), and the lane prints the channels that differ from
//! Metal's without holding them. A word the fragment function encodes is held to Metal's rule.
use super::degrade_notices::counts;
use super::resolves::{lane, quiet, Lane};
@@ -58,7 +59,9 @@ use crate::runtime_lane::buffer_with;
use metal2vulkan::bind::SRGB_RESOLVE_THRESHOLDS;
use metal2vulkan::error::DriverDeviation;
use metal2vulkan::metal::format::WordAttachment;
use metal2vulkan::metal::{BlendFactor, ColorWriteMask, PixelFormat, PrimitiveType, TextureUsage};
use metal2vulkan::metal::{
BlendFactor, ColorWriteMask, PixelFormat, PrimitiveType, TextureUsage, TextureWriteRoundingMode,
};
use metal2vulkan::pipeline::{
ColorAttachmentDescriptor, PrecisionNote, Reconvergence, RenderPipelineDescriptor, StageSource,
};
@@ -714,9 +717,9 @@ struct Drawn {
/// Whether the fragment stage declares the `StorageInputOutput16` capability: its color output
/// is written as the bits of the half Metal stores, through a 16-bit output.
sixteen: bool,
/// Whether the fragment stage rounds the attachment's output to Metal's codes itself
/// (`rounded_colors`), rather than leaving its conversion to the device.
rounded: bool,
/// Whether the fragment stage records `PrecisionNote::DeviceColorConversion`: the device's own
/// conversion of the attachment's channels, printed against Metal's and not held to it.
converted: bool,
}
/// `OpCapability StorageInputOutput16`: the instruction's first word (two words, opcode 17) and
@@ -781,7 +784,9 @@ fn drawn(
.precision_notes
.contains(&PrecisionNote::DeviceNanEncoding);
let sixteen = fragment.spirv.windows(2).any(|w| w == IO16_CAPABILITY);
let rounded = fragment.rounded_colors.contains(&0);
let converted = fragment
.precision_notes
.contains(&PrecisionNote::DeviceColorConversion);
let pipeline = device
.new_render_pipeline_state(&pipeline, &PipelineOptions::default())
.map_err(|e| format!("unsupported: the pipeline ({e})"))?;
@@ -824,11 +829,12 @@ fn drawn(
stored,
noted,
sixteen,
rounded,
converted,
})
}
/// Every format, plain and blended, printed against Metal's conversion and held to it.
/// Every format, plain and blended, printed against Metal's conversion, and held to it where the
/// fragment stage does not record the device's own conversion (`DeviceColorConversion`).
#[test]
fn draws_store_metals_codes() {
let (messages, _cache, lane) = lane();
@@ -858,7 +864,7 @@ fn draws_store_metals_codes() {
stored,
noted,
sixteen,
rounded,
converted,
} = match drawn(&lane, case, &values, blend, None) {
Ok(drawn) => drawn,
Err(why) => {
@@ -911,22 +917,24 @@ fn draws_store_metals_codes() {
} else if sixteen {
eprintln!("color write {label} on {name}: written through a 16-bit output");
}
if !rounded && !sixteen {
eprintln!(
"color write {label} on {name}: the device's own conversion (the shader \
rounds nothing)"
);
}
let recorded = match converted {
true => " (DeviceColorConversion, recorded)",
false => "",
};
if wrong == 0 {
eprintln!(
"color write {label} on {name}: Metal's, 0 of {channels} channels differ"
"color write {label} on {name}: Metal's, 0 of {channels} channels \
differ{recorded}"
);
} else {
eprintln!(
"color write {label} on {name}: {wrong} of {channels} channels differ: {}",
"color write {label} on {name}: {wrong} of {channels} channels \
differ{recorded}: {}",
examples.join("; ")
);
differ.push(format!("{label}: {wrong} of {channels}"));
if !converted {
differ.push(format!("{label}: {wrong} of {channels}"));
}
}
}
}
@@ -936,7 +944,8 @@ fn draws_store_metals_codes() {
/// A packed 16-bit or two-channel 8-bit sRGB format's draw under a write mask of some of its
/// channels, over a pass that clears it: each written channel stores Metal's code of the output
/// and each kept one the code of the clear (Metal's rule of both). A format the device holds but
/// and each kept one the code of the clear (Metal's rule of both), held so where the fragment
/// stage does not record the device's own conversion (`DeviceColorConversion`). A format the device holds but
/// does not render must draw so through the view of its word (`metal::format::WordAttachment`),
/// which the fragment function merges into the texel's, in the pixel interlock or over the
/// attachment's input attachment on a device that orders fetch through them (lavapipe; an 8-bit
@@ -967,16 +976,17 @@ fn partly_masked_packed_formats_keep_their_fields() {
let word = WordAttachment::of(case.pf, &profile);
for mask in masks {
let label = format!("{:?} under {mask:?}", case.pf);
let stored = match drawn(&lane, case, &values, DrawBlend::Off, Some((mask, clear))) {
Ok(drawn) => drawn.stored,
Err(why) => {
eprintln!("masked color write {label} on {name}: {why}");
if word.is_some() {
differ.push(format!("{label}: not drawn through its word: {why}"));
let (stored, converted) =
match drawn(&lane, case, &values, DrawBlend::Off, Some((mask, clear))) {
Ok(drawn) => (drawn.stored, drawn.converted),
Err(why) => {
eprintln!("masked color write {label} on {name}: {why}");
if word.is_some() {
differ.push(format!("{label}: not drawn through its word: {why}"));
}
continue;
}
continue;
}
};
};
if word.is_some() {
eprintln!("masked color write {label} on {name}: its word merged into the texel's");
}
@@ -1018,7 +1028,9 @@ fn partly_masked_packed_formats_keep_their_fields() {
"masked color write {label} on {name}: {wrong} of {channels} channels differ: {}",
examples.join("; ")
);
differ.push(format!("{label}: {wrong} of {channels}"));
if !converted {
differ.push(format!("{label}: {wrong} of {channels}"));
}
}
}
}
@@ -1166,13 +1178,14 @@ fn channel_lane(pf: PixelFormat, offset: u32) -> usize {
}
/// Render pipeline states, each made twice, announce their fragment stage's color writes once,
/// with their stages' other kinds not announced before, and nothing else. A fragment function writing `float4` to an
/// `RGBA8Unorm` attachment announces `shader-color-conversion` where the device does not convert
/// as Metal does (every venue but MoltenVK), its fragment stage listing the attachment as rounded
/// exactly there. One writing `half4` to an `RGBA16Float` attachment announces
/// `shader-half-color-bits` where the device writes it as the half's bits through a 16-bit output
/// (MoltenVK, `HalfColorOutputBits`), its stage listing the attachment as written so exactly there
/// and never as rounded.
/// with their stages' other kinds not announced before, and nothing else. A fragment function
/// writing `float4` to an `RGBA16Float` attachment under `TextureWriteRoundingMode::NearestEven`
/// announces `shader-color-conversion` on every device, its fragment stage listing the attachment
/// as rounded (the one rounding the function makes: no device's conversion rounds a half to
/// nearest even). One writing `half4` to an `RGBA16Float` attachment at Metal's default mode
/// announces `shader-half-color-bits` where the device writes it as the half's bits through a
/// 16-bit output (MoltenVK, `HalfColorOutputBits`), its stage listing the attachment as written so
/// exactly there and never as rounded.
#[test]
fn pipeline_states_announce_the_shader_conversion_once() {
let (messages, _cache, lane) = lane();
@@ -1185,24 +1198,21 @@ fn pipeline_states_announce_the_shader_conversion_once() {
.function_descriptor()
};
let compile = device.compile_device();
let metal = compile
.profile()
.takes_driver_deviation(DriverDeviation::MetalColorWrites);
let bits = compile
.profile()
.takes_driver_deviation(DriverDeviation::HalfColorOutputBits);
// Each kind is announced once per device: the second state's are those the first did not.
let mut seen = BTreeSet::new();
for (fragment, pf, kind, listed) in [
for (fragment, rounding, kind, listed) in [
(
"rt6_fill_rgba32float",
PixelFormat::RGBA8Unorm,
TextureWriteRoundingMode::NearestEven,
Degradation::ShaderColorConversion,
!metal,
true,
),
(
"rt6_fill_rgba16float",
PixelFormat::RGBA16Float,
TextureWriteRoundingMode::TowardZero,
Degradation::ShaderHalfColorBits,
bits,
),
@@ -1210,7 +1220,9 @@ fn pipeline_states_announce_the_shader_conversion_once() {
let mut descriptor =
RenderPipelineDescriptor::new(StageSource::Function(function("rt6_fill_vertex")));
descriptor.fragment = Some(StageSource::Function(function(fragment)));
descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(pf));
descriptor.color_attachments[0] =
Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA16Float));
descriptor.texture_write_rounding_mode = rounding;
let compiled = compile
.compile_render_pipeline(&descriptor, &Budget::standard())
.unwrap();
@@ -69,10 +69,9 @@
//! vertex-stage reads in place of bytes a fragment stage of the pass wrote in `pass_start_reads`
//! ([`IN_PLACE_VERTEX_READS`]) and a vertex stage's write of bytes one wrote there
//! ([`FRAGMENTS_BEFORE_GEOMETRY`]), constant biases of 16-bit unorm depths the device converts
//! past a fragment stage that tests first, where the profile is not measured to store Metal's
//! biased codes, in `unorm_depth_bias` ([`UNORM_DEPTH_BIAS`]), 16-bit unorm depths the device converts without the profile's
//! deviation ([`UNORM_DEPTH_ROUNDING`]) and those the fragment stage writes Metal's codes of
//! ([`SHADER_UNORM_DEPTH`]),
//! where the profile is not measured to store Metal's biased codes, in `unorm_depth_bias`
//! ([`UNORM_DEPTH_BIAS`]), 16-bit unorm depths the device converts without the profile's
//! deviation ([`UNORM_DEPTH_ROUNDING`]),
//! draws of points in a rate-mapped pass, which keep Vulkan's clipping of points, in
//! `wide_points` ([`POINT_GUARD_BAND`]), draws whose fragment function writes a depth in depth
//! clamp mode through a range above 0 that keep the device's clamp, in `viewport_ranges`
@@ -214,7 +213,7 @@ use super::texture_blits::{MIPMAPS, UPLOADS};
use super::tile_dispatches::TILE_DISPATCHES;
use super::topology_classes::UNSIZED_POINTS;
use super::two_plane_copies::TWO_PLANE_COPIES;
use super::unorm_depth_bias::{SHADER_UNORM_DEPTH, UNORM_DEPTH_BIAS, UNORM_DEPTH_ROUNDING};
use super::unorm_depth_bias::{UNORM_DEPTH_BIAS, UNORM_DEPTH_ROUNDING};
use super::view_reinterpretation::VIEW_SHADOWS;
use super::viewport_ranges::{NAN_DEPTH, UNCLAMPED_BIAS, VERTEX_CLAMPS};
use super::visibility::REPEATED_STARTS;
@@ -513,7 +512,6 @@ fn every_kind_has_a_site_a_lane_test_takes() {
&FRAGMENTS_BEFORE_GEOMETRY,
&UNORM_DEPTH_BIAS,
&UNORM_DEPTH_ROUNDING,
&SHADER_UNORM_DEPTH,
&POINT_GUARD_BAND,
&NAN_DEPTH,
&UNCLAMPED_BIAS,
@@ -12,10 +12,15 @@
//! [`METAL_BYTES`] beside the SHA-256 of each the probes printed (an Apple M3 Max under macOS 26.7
//! and an Apple M4 under 27.0.1 wrote them from the same inputs, plain and under Metal's
//! validation layer, which keep the bytes). A differing output names its first differing texel on
//! an `XR-PLANES-DIFFERS` line.
//! an `XR-PLANES-DIFFERS` line. The split's alpha plane is an `ARGB8Unorm` write, which the device
//! converts: it is held to Metal's bytes where the device is measured to store Metal's codes
//! (`DriverDeviation::MetalNormStorageWrites`), and elsewhere printed without being held (the
//! module records `PrecisionNote::DeviceColorConversion`; the RTX 3090 stores the code below for 22
//! of the 1,024 alpha values whose product lies just above a half).
use super::degrade_notices::on_device;
use crate::air_library::AirLibrary;
use metal2vulkan::error::DriverDeviation;
use metal2vulkan::metal::{PixelFormat, TextureUsage};
use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource};
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
@@ -350,10 +355,15 @@ fn the_inputs_and_the_outputs_are_the_harness_s() {
}
/// Every output texture of both kernels, for every pairing of plane 0's and the joined texture's
/// formats, holds Metal's bytes.
/// formats, holds Metal's bytes, the split's alpha plane where the device is measured to store
/// Metal's codes (the module docs).
#[test]
fn two_extended_range_planes_join_and_split_as_metal_does() {
on_device(|device, _| {
let measured = device
.compile_device()
.profile()
.takes_driver_deviation(DriverDeviation::MetalNormStorageWrites);
let queue = device.new_command_queue().unwrap();
let join = state(device, "xr_planes_join");
let split = state(device, "xr_planes_split");
@@ -379,7 +389,13 @@ fn two_extended_range_planes_join_and_split_as_metal_does() {
_ => texel_bytes(ALPHA),
};
if let Some(unlike) = unlike_metal(&bytes, want, texel as usize) {
wrong.push(format!("{kernel} {color:?} {joined:?} {what}: {unlike}"));
let line = format!("{kernel} {color:?} {joined:?} {what}: {unlike}");
match what == "alpha" && !measured {
true => {
println!("XR-PLANES-DEVICE-CONVERSION {}: {line}", device.name())
}
false => wrong.push(line),
}
}
}
}
@@ -732,17 +732,12 @@ fn other_blends_masks_and_the_blend_color_store_metals_blend() {
quiet(lane, &messages);
}
/// Metal's sRGB byte of each twelve-bit index (the first indices of `bind::color_write_table`,
/// Metal's encode thresholds).
/// Metal's sRGB byte of each twelve-bit index: the number of Metal's encode thresholds at or
/// below it (`bind::SRGB_RESOLVE_THRESHOLDS`, byte `c`'s first index at `c - 1`).
pub(super) static SRGB_BYTES: std::sync::LazyLock<Vec<u8>> = std::sync::LazyLock::new(|| {
let first: Vec<u32> = metal2vulkan::bind::color_write_table()
.as_chunks::<16>()
.0
.iter()
.map(|e| u32::from_le_bytes([e[0], e[1], e[2], e[3]]))
.collect();
use metal2vulkan::bind::SRGB_RESOLVE_THRESHOLDS;
(0..4096u32)
.map(|i| (1..256).rev().find(|&b| first[b] <= i).unwrap_or(0) as u8)
.map(|i| SRGB_RESOLVE_THRESHOLDS.partition_point(|&t| u32::from(t) <= i) as u8)
.collect()
});
@@ -20,10 +20,16 @@
//! `device-nan-encoding` (the recorded near-equivalent).
//!
//! The product writes through the storage choice's class (`metal::format::half_storage_class`):
//! as computed on MoltenVK (`DriverDeviation::MetalHalfStorageWrites` and
//! `MetalHalfStorageNans`), its NaN quieted to `0x7fc00000` on RADV, ANV, NVIDIA's measured
//! GPUs and lavapipe from Mesa 26.0.8 through 26.2.4 (`HalfQuietNan`; ANV then stores `0xfe00`
//! and announces the note), and rounded by the shader elsewhere (`HalfTowardZero`).
//! as computed on MoltenVK (`DriverDeviation::MetalHalfStorageNans`), and its NaN quieted to
//! `0x7fc00000` elsewhere (`HalfQuietNan`; ANV then stores `0xfe00` and announces the note), the
//! device's conversion rounding every other value; or, on a device not measured to store a
//! written `half`'s NaN as its bits, as the bits the shader rounds toward zero, through the
//! texture's unsigned integer alias (`StorageImageClass::HalfBits`). A case is held to Metal's
//! rounding where the device is measured to make it (`DriverDeviation::MetalHalfStorageWrites`:
//! RADV, ANV, NVIDIA's measured GPUs, lavapipe from Mesa 26.0.8 through 26.2.4 and MoltenVK), the
//! measurement of the deviation on that device; elsewhere the module records the device's
//! conversion (`PrecisionNote::DeviceColorConversion`), and the lane prints the channels that
//! differ without holding them.
use super::color_writes::{
half, half_toward_zero, specials, unsigned_float, unsigned_float_toward_zero,
@@ -31,6 +37,7 @@ use super::color_writes::{
use super::degrade_notices::{on_device, on_device_with};
use super::{buffer_with, layer_reported_nothing, read_buffer, Messages, WAIT};
use crate::air_library::AirLibrary;
use metal2vulkan::error::DriverDeviation;
use metal2vulkan::metal::{PixelFormat, ResourceUsage, TextureUsage};
use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource};
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
@@ -241,7 +248,8 @@ fn nan(h: u16) -> bool {
h & 0x7c00 == 0x7c00 && h & 0x3ff != 0
}
/// Every form into every format, printed against Metal's conversion and held to it. Every case
/// Every form into every format, printed against Metal's conversion and held to it where the
/// device is measured to make it (the module docs). Every case
/// runs on one device, which announces `DeviceNanEncoding` at each dispatch that binds a variant
/// taking it (a device announces a kind once unless its options ask for each occurrence), so
/// each case reads its own notice as on a device of its own; its validation messages fail it by
@@ -342,7 +350,11 @@ fn judge(
{away} of them one step away from zero: {}",
examples.join("; ")
);
Some(format!("{label}: {wrong} of {channels_written}"))
let measured = device
.compile_device()
.profile()
.takes_driver_deviation(DriverDeviation::MetalHalfStorageWrites);
measured.then(|| format!("{label}: {wrong} of {channels_written}"))
}
/// `RG11B10Float`'s fields: each one's offset in the texel and fraction bits.
@@ -15,7 +15,13 @@
//! value) through `half_storage_writes`' kernels (`access::write`, `access::read_write`, a texture
//! buffer and an argument buffer's texture), reads the texels back and compares every channel with
//! Metal's code. A case whose format the runtime refuses for storage is printed and skipped. A
//! channel that differs is counted, with examples, on a `NORM-STORAGE-WRITE` line.
//! channel that differs is counted, with examples, on a `NORM-STORAGE-WRITE` line. The kernel
//! writes the value as computed and the device converts it: the lane holds a channel to Metal's
//! code where the device is measured to store it (`DriverDeviation::MetalNormStorageWrites`, but
//! for a 1-bit channel, which RADV rounds up at one half), the measurement of the deviation on
//! that device; elsewhere the module records the device's conversion
//! (`PrecisionNote::DeviceColorConversion`) and the lane prints the channels that differ without
//! holding them.
//!
//! [`kernel_writes_store_each_channel_in_its_field`] writes texels whose channels differ into the
//! 10:10:10:2 formats, whose fields Metal orders red first (`RGB10A2Unorm`) and blue first
@@ -26,6 +32,7 @@ use super::color_writes::{field, metal, round_product, Channel, Output, CASES};
use super::degrade_notices::on_device;
use super::half_storage_writes::{written, written_texels, Form};
use super::layer_reported_nothing;
use metal2vulkan::error::DriverDeviation;
use metal2vulkan::metal::PixelFormat;
/// Metal's stored code of `x` in `channel` (the module docs); `None` for a channel of another
@@ -43,8 +50,8 @@ fn stored_code(channel: Channel, x: f32) -> Option<u64> {
}
/// Every form into every normalized format of `color_writes`' cases, printed against Metal's
/// conversion and held to it. The cases share one device (they read no notice), and each case's
/// validation messages fail it by name.
/// conversion and held to it where the device is measured to store it (the module docs). The cases
/// share one device (they read no notice), and each case's validation messages fail it by name.
#[test]
fn kernel_writes_store_metals_normalized_codes() {
let mut differ = Vec::new();
@@ -59,6 +66,10 @@ fn kernel_writes_store_metals_normalized_codes() {
});
on_device(|device, messages| {
let name = device.name().to_owned();
let measured = device
.compile_device()
.profile()
.takes_driver_deviation(DriverDeviation::MetalNormStorageWrites);
for case in normalized {
let values = (case.values)();
for form in Form::ALL {
@@ -69,7 +80,7 @@ fn kernel_writes_store_metals_normalized_codes() {
eprintln!("NORM-STORAGE-WRITE {label} on {name}: refused");
continue;
};
let (mut wrong, mut examples) = (0usize, Vec::new());
let (mut wrong, mut held, mut examples) = (0usize, 0usize, Vec::new());
for (i, &x) in values.iter().enumerate() {
let texel = &stored[i * case.bytes..(i + 1) * case.bytes];
for &(offset, channel) in case.channels {
@@ -81,6 +92,9 @@ fn kernel_writes_store_metals_normalized_codes() {
continue;
}
wrong += 1;
if measured && !matches!(channel, Channel::HalfUnorm(1)) {
held += 1;
}
if examples.len() < 8 {
examples.push(format!(
"{x:e} ({:#010x}) at bit {offset}: {got:#x}, Metal's {want:#x}",
@@ -92,11 +106,11 @@ fn kernel_writes_store_metals_normalized_codes() {
let channels = values.len() * case.channels.len();
eprintln!(
"NORM-STORAGE-WRITE {label} on {name}: {wrong} of {channels} channels differ \
from Metal's: {}",
from Metal's ({held} held to it): {}",
examples.join("; ")
);
if wrong > 0 {
differ.push(format!("{label}: {wrong} of {channels}"));
if held > 0 {
differ.push(format!("{label}: {held} of {channels}"));
}
}
}
@@ -11,9 +11,10 @@
//! 255 rounded to nearest even, the X field of `RGBX8Unorm_sRGB` green's byte: every texel equal
//! to `pack_float_to_srgb_unorm4x8` of the same values. A read (`read_write`, `float4` and
//! `half4`) of code `c` answers its twelve-bit step `k / 4095` correctly rounded (alpha `c / 255`,
//! 1 for `RGBX8Unorm_sRGB`; a channel the format lacks 0, alpha 1). The tables are Metal's own: the first encode indices are the color
//! table's (`bind::color_write_table`), the steps `round(decode(c / 255) * 4095)` of the sRGB
//! transfer (every one at least `1.6e-4` of a step from a half step).
//! 1 for `RGBX8Unorm_sRGB`; a channel the format lacks 0, alpha 1). The tables are Metal's own:
//! the first encode indices are its encode thresholds (`bind::SRGB_RESOLVE_THRESHOLDS`), the
//! steps `round(decode(c / 255) * 4095)` of the sRGB transfer (every one at least `1.6e-4` of a
//! step from a half step).
//!
//! The values are the probe's, in its order: the `f32`s around each twelve-bit index's half step
//! (three ulps either side), each step's value and its neighbours, each alpha code's half step
@@ -73,17 +74,12 @@ const FORMATS: [(PixelFormat, bool, usize, [Option<usize>; 4]); 5] = [
),
];
/// The byte of each twelve-bit index: the largest whose first encode index (the color table's
/// first word of each entry, `bind::color_write_table`) is at or below it.
/// The byte of each twelve-bit index: the number of Metal's encode thresholds at or below it
/// (`bind::SRGB_RESOLVE_THRESHOLDS`, byte `c`'s first index at `c - 1`).
fn encode_bytes() -> Vec<u8> {
let first: Vec<u32> = metal2vulkan::bind::color_write_table()
.as_chunks::<16>()
.0
.iter()
.map(|e| u32::from_le_bytes([e[0], e[1], e[2], e[3]]))
.collect();
use metal2vulkan::bind::SRGB_RESOLVE_THRESHOLDS;
(0..4096u32)
.map(|i| (1..256).rev().find(|&b| first[b] <= i).unwrap_or(0) as u8)
.map(|i| SRGB_RESOLVE_THRESHOLDS.partition_point(|&t| u32::from(t) <= i) as u8)
.collect()
}
@@ -14,24 +14,19 @@
//! (every code the rule's), and found that a slope alone brings the one unit: [`SLOPE_ALONE`], flat
//! triangles (so the slope adds nothing itself) under a constant of 0.
//!
//! Where the profile takes `DriverDeviation::MetalDepth16Stores`, the device converts an unbiased
//! depth, and where it also takes `DriverDeviation::MetalDepth16BiasedStores` a biased one: the
//! runtime records Metal's bias where the device pins Vulkan's unit (`metal::state::depth_bias`),
//! and the device rounds the sum and converts it its own way. RADV (Mesa 26.2.4, the Radeon 780M)
//! stored every code Metal's, and MoltenVK (1.4.1, an M4), which hands Metal its constant, too
//! (both deviations). ANV (Mesa 26.2.4) stored every unbiased code Metal's (the first), but
//! rounded some biased sums near a code's midpoint to nearest, storing the code next to Metal's,
//! so a biased draw there runs the variant whose fragment stage adds the bias
//! (`VariantKey::depth16_biased`).
//!
//! Elsewhere the fragment stage writes Metal's codes itself (`LoweringInputs::depth16_codes`),
//! its bias added in the shader, and every code is Metal's (`shader-unorm-depth`; a sloped bias
//! takes its slope from the quad's depths, `unorm-depth-slope`). Without it lavapipe (Mesa 26.0.8
//! and 26.2.4) scaled every depth by 65535 as a `float` and rounded a tie to even (0.9 as 58982),
//! and NVIDIA's (615.71.09) stored the code below Metal's for a depth up to 0.55 of a code above
//! a midpoint (0.5 as 32767). A biased draw whose fragment stage cannot add the bias (one that
//! declares early fragment tests, here) keeps the device's conversion, which the runtime
//! announces as `unorm-depth-bias` where the profile lacks the second deviation.
//! The device converts every depth, biased or not: the runtime records Metal's bias where the
//! device pins Vulkan's unit (`metal::state::depth_bias`), and the device rounds the sum and
//! converts it its own way. Where the profile takes `DriverDeviation::MetalDepth16Stores` an
//! unbiased depth stores Metal's code, and where it takes `DriverDeviation::MetalDepth16BiasedStores`
//! a biased one: RADV (Mesa 26.2.4, the Radeon 780M) stored every code Metal's, and MoltenVK (1.4.1,
//! an M4), which hands Metal its constant, too (both deviations). ANV (Mesa 26.2.4) stored every
//! unbiased code Metal's (the first), but rounded some biased sums near a code's midpoint to
//! nearest, storing the code next to Metal's. Lavapipe (Mesa 26.0.8 and 26.2.4) scaled every depth
//! by 65535 as a `float` and rounded a tie to even (0.9 as 58982), and NVIDIA's (615.71.09) stored
//! the code below Metal's for a depth up to 0.55 of a code above a midpoint (0.5 as 32767). Where
//! the profile lacks a deviation the runtime announces it, `unorm-depth-rounding` for any depth
//! tested or written and `unorm-depth-bias` for a biased one, and the lane prints the codes that
//! differ from Metal's without holding them.
//!
//! The render pass's depth decides what a draw stores, whatever the pipeline names: the cases
//! drawn by a pipeline that names no depth store the same codes.
@@ -46,15 +41,10 @@ use super::render_state::{quiet, validated, Pipe, Probe, PASS, WHITE};
use crate::air_library::AirLibrary;
use metal2vulkan::device::VkFeature;
use metal2vulkan::error::DriverDeviation;
use metal2vulkan::metal::{
CompareFunction, DepthClipMode, PixelFormat, PrimitiveType, TextureUsage,
};
use metal2vulkan::metal::{CompareFunction, DepthClipMode, PixelFormat, PrimitiveType};
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
use metal2vulkan_runtime::{
Degradation, LoadAction, PipelineOptions, RenderPassDescriptor, ResourceOptions, ScissorRect,
StoreAction, TextureDescriptor, Viewport,
};
use metal2vulkan_runtime::{Degradation, PipelineOptions, ScissorRect, Viewport};
/// The side of each probe's pass: a pixel per case.
const SIDE: u64 = 32;
@@ -377,30 +367,20 @@ fn grid<const N: usize>(factors: &[f32; N], rows: &[(u32, [u16; N])]) -> Vec<(f3
}
/// The kinds `unorm_depth_bias` takes: a constant bias on a 16-bit unorm depth the device
/// converts where the profile lacks `DriverDeviation::MetalDepth16BiasedStores`, past a fragment
/// stage that cannot add it (one that declares early fragment tests).
/// converts where the profile lacks `DriverDeviation::MetalDepth16BiasedStores`.
pub(super) const UNORM_DEPTH_BIAS: [Degradation; 1] = [Degradation::UnormDepthBias];
/// The kinds `unorm_depth_bias` takes: a 16-bit unorm depth the device converts its own way where
/// the profile lacks `DriverDeviation::MetalDepth16Stores`, here a depth clamped to a viewport
/// range's end inside `(0, 1)` past a fragment stage that writes Metal's codes.
/// the profile lacks `DriverDeviation::MetalDepth16Stores`.
pub(super) const UNORM_DEPTH_ROUNDING: [Degradation; 1] = [Degradation::UnormDepthRounding];
/// The kinds `unorm_depth_bias` takes where the fragment stage writes Metal's 16-bit codes: a
/// depth tested or written so, and a slope it takes from the quad's depths.
pub(super) const SHADER_UNORM_DEPTH: [Degradation; 2] =
[Degradation::ShaderUnormDepth, Degradation::UnormDepthSlope];
/// Every code probes 7 and 7b and [`SLOPE_ALONE`] measured is Metal's rule's ([`metal_code`]),
/// and every row stores Metal's code. The device converts an unbiased row (a constant and a slope
/// factor of 0) where the profile takes `DriverDeviation::MetalDepth16Stores`, and a biased one
/// where it also takes `DriverDeviation::MetalDepth16BiasedStores`; elsewhere the fragment stage
/// writes the row's code, and the draws announce `shader-unorm-depth` and, for the sloped rows,
/// `unorm-depth-slope` once. No draw announces `unorm-depth-bias`. Either way a pipeline that
/// names no depth stores the same codes: the pass's depth decides them. Where the fragment stage
/// writes a biased row's code, every row whose bias has a known side
/// (`metal::state::depth16_bias_side`) runs the variant that declares it, counted
/// (`WorkCounts::depth16_sided_draws`), and stores Metal's code all the same.
/// Every code probes 7 and 7b and [`SLOPE_ALONE`] measured is Metal's rule's ([`metal_code`]).
/// Every row is the device's conversion: an unbiased row (a constant and a slope factor of 0) is
/// held to Metal's code where the profile takes `DriverDeviation::MetalDepth16Stores`, and a
/// biased one where it takes `DriverDeviation::MetalDepth16BiasedStores`; elsewhere a row off
/// Metal's code is printed, and the draws announce `unorm-depth-rounding` (any row) and
/// `unorm-depth-bias` (a biased row) once, each only where the profile lacks its deviation.
/// Either way a pipeline that names no depth stores the same codes: the pass's depth decides them.
#[test]
fn a_constant_bias_on_a_16_bit_unorm_depth_stores_metals_codes() {
let slope_alone: Vec<_> = SLOPE_ALONE
@@ -423,61 +403,42 @@ fn a_constant_bias_on_a_16_bit_unorm_depth_stores_metals_codes() {
let profile = probe.device.compile_device().profile();
let stores = profile.takes_driver_deviation(DriverDeviation::MetalDepth16Stores);
let biased_stores = profile.takes_driver_deviation(DriverDeviation::MetalDepth16BiasedStores);
// The fragment stage writes Metal's codes, its bias included, wherever the device does not:
// every row's where it converts no depth so, a biased row's where it converts only unbiased
// ones so.
let shader = !stores || !biased_stores;
let d16 = WHITE.depth(PixelFormat::Depth16Unorm);
let sided_before = probe.device.work_counts().depth16_sided_draws;
let mut sided_rows = 0u64;
let mut differ = Vec::new();
for (name, cases) in &probes {
let drawn: Vec<(f32, f32, f32)> = cases.iter().map(|&(z, c, s, _)| (z, c, s)).collect();
sided_rows += drawn
.iter()
.filter(|&&(_, c, s)| {
metal2vulkan::metal::state::depth16_bias_side(c, s, 0.0).is_some()
})
.count() as u64;
let stored = stored_codes(&probe, d16, &drawn);
let unnamed = stored_codes(&probe, WHITE, &drawn);
assert_eq!(
unnamed, stored,
"{name} on {device}: a pipeline that names no depth stores other codes"
);
let off: Vec<String> = cases
let off: Vec<(bool, String)> = cases
.iter()
.zip(stored)
.filter(|&(&(.., metal), stored)| stored != metal)
.map(|(&(z, c, s, metal), stored)| {
format!(
let biased = c != 0.0 || s != 0.0;
let line = format!(
"{name} {:#010x} by {c} and slope {s}: {stored}, Metal {metal}",
z.to_bits()
)
);
(if biased { biased_stores } else { stores }, line)
})
.collect();
let examples: Vec<&String> = off.iter().map(|(_, line)| line).take(8).collect();
eprintln!(
"UNORM-DEPTH-BIAS {device} {name}: {} cases, {} off Metal's",
"UNORM-DEPTH-BIAS {device} {name}: {} cases, {} off Metal's: {examples:?}",
cases.len(),
off.len()
);
differ.extend(off);
differ.extend(off.into_iter().filter(|&(held, _)| held).map(|(_, l)| l));
}
// Each row is drawn twice: by the pipeline that names the depth and by the one that names
// none.
let sided = probe.device.work_counts().depth16_sided_draws - sided_before;
eprintln!("UNORM-DEPTH-SIDED {device}: {sided} draws declared their bias's side");
assert_eq!(
sided,
if shader { 2 * sided_rows } else { 0 },
"{device}: draws of a known side through the variant that declares it"
);
let mut kinds = Vec::new();
let mut quiet_kinds = Vec::new();
for (taken, list) in [
(false, &UNORM_DEPTH_BIAS[..]),
(false, &UNORM_DEPTH_ROUNDING[..]),
(shader, &SHADER_UNORM_DEPTH[..]),
(!biased_stores, &UNORM_DEPTH_BIAS[..]),
(!stores, &UNORM_DEPTH_ROUNDING[..]),
] {
match taken {
true => kinds.extend(list),
@@ -485,12 +446,11 @@ fn a_constant_bias_on_a_16_bit_unorm_depth_stores_metals_codes() {
}
}
// The draws under constant biases move their depth (`biased-depth-past-unit-range` where the
// device stores it unclamped; a fragment stage that adds the bias clamps it to `[0, 1]`),
// from a `Shared` buffer, through the white pipelines.
// device stores it unclamped), from a `Shared` buffer, through the white pipelines.
let mut first = forced(&[
(
Degradation::BiasedDepthPastUnitRange,
unclamped_bias(&probe.device) && !shader,
unclamped_bias(&probe.device),
),
(
Degradation::SharedInSystemMemory,
@@ -506,17 +466,20 @@ fn a_constant_bias_on_a_16_bit_unorm_depth_stores_metals_codes() {
.collect();
assert!(
unexpected.is_empty(),
"announced {unexpected:?} where Metal's codes are stored"
"announced {unexpected:?} where the device is measured to store Metal's codes"
);
quiet(probe, &messages);
assert!(differ.is_empty(), "codes not Metal's: {differ:#?}");
assert!(
differ.is_empty(),
"codes not Metal's where measured: {differ:#?}"
);
}
/// A draw in depth clamp mode through a viewport depth range whose near end lies inside `(0, 1)`
/// clamps a depth below it to that end, which the device converts to its code its own way past a
/// fragment stage that writes Metal's codes: such a draw announces `unorm-depth-rounding` once
/// there (and `shader-unorm-depth`), and neither where the profile takes
/// `DriverDeviation::MetalDepth16Stores`. Skipped, printed, on a device without `depthClamp`.
/// clamps a depth below it to that end, which the device converts to its code: such a draw
/// announces `unorm-depth-rounding` once where the profile lacks
/// `DriverDeviation::MetalDepth16Stores`, and nothing there where it takes it. Skipped, printed,
/// on a device without `depthClamp`.
#[test]
fn a_depth_clamped_to_a_range_end_inside_the_unit_range_is_the_device_s_conversion() {
let (messages, _cache, probe) = validated();
@@ -526,7 +489,7 @@ fn a_depth_clamped_to_a_range_end_inside_the_unit_range_is_the_device_s_conversi
eprintln!("UNORM-DEPTH-CLAMP {device}: skipped, the device has no depthClamp");
return;
}
let shader = !profile.takes_driver_deviation(DriverDeviation::MetalDepth16Stores);
let unmeasured = !profile.takes_driver_deviation(DriverDeviation::MetalDepth16Stores);
let d16 = PixelFormat::Depth16Unorm;
let pipe = WHITE.depth(d16);
let stored = probe.run(PASS.depth(d16, 1.0), |p, e, h| {
@@ -545,11 +508,8 @@ fn a_depth_clamped_to_a_range_end_inside_the_unit_range_is_the_device_s_conversi
.map(|t| u16::from_le_bytes([t[0], t[1]]))
.collect();
eprintln!("UNORM-DEPTH-CLAMP {device}: stored {codes:?}");
let kinds: Vec<Degradation> = match shader {
true => vec![
Degradation::ShaderUnormDepth,
Degradation::UnormDepthRounding,
],
let kinds: Vec<Degradation> = match unmeasured {
true => vec![Degradation::UnormDepthRounding],
false => Vec::new(),
};
let mut first = forced(&[(
@@ -559,7 +519,7 @@ fn a_depth_clamped_to_a_range_end_inside_the_unit_range_is_the_device_s_conversi
first.extend(probe.made(pipe));
let announced = assert_made_once(&messages, &kinds, &first);
assert!(
shader || !announced.contains_key(&Degradation::UnormDepthRounding),
unmeasured || !announced.contains_key(&Degradation::UnormDepthRounding),
"announced unorm-depth-rounding on {device}, whose profile takes the deviation"
);
quiet(probe, &messages);
@@ -567,8 +527,8 @@ fn a_depth_clamped_to_a_range_end_inside_the_unit_range_is_the_device_s_conversi
/// A draw biasing a `Depth16Unorm` depth through a fragment function that declares early
/// fragment tests (the owned fixture `cfb_depth_never`'s `cfb_dn_red_early`, a full-screen
/// triangle at depth 0.5) keeps the device's conversion, as no fragment stage that tests first
/// can write the depth: it announces `unorm-depth-bias` once where the profile lacks
/// triangle at depth 0.5) takes the device's conversion, as every draw does: it announces
/// `unorm-depth-bias` once where the profile lacks
/// `DriverDeviation::MetalDepth16BiasedStores`, and `unorm-depth-rounding` where it lacks
/// `DriverDeviation::MetalDepth16Stores`. The stored code is printed.
#[test]
@@ -623,105 +583,3 @@ fn a_bias_a_fragment_stage_testing_first_cannot_add_is_the_device_s() {
assert_made_once(&messages, &kinds, &first);
quiet(probe, &messages);
}
/// The side of the cost test's pass: about a 1080p frame's pixels.
const COST_SIDE: u64 = 1440;
/// The full-screen layers the cost test draws front to back.
const LAYERS: u16 = 16;
/// Command buffers per form of the cost test, of which the median GPU time is printed.
const TIMED: usize = 15;
/// What a fragment stage that writes Metal's 16-bit codes costs against the device's own
/// conversion: [`LAYERS`] full-screen layers drawn front to back (the nearest first, `Less`,
/// written) into a [`COST_SIDE`]² pass, by the white pipeline into a `Depth16Unorm` depth (whose
/// fragment stage writes the codes where the profile lacks `DriverDeviation::MetalDepth16Stores`,
/// or for the biased draws `DriverDeviation::MetalDepth16BiasedStores`, so every layer runs it
/// before the test, but where it declares the bias's side, which a constant of 2 raises:
/// `WorkCounts::depth16_sided_draws`) and into a `Depth32Float` one (which the device tests before
/// the stage runs), unbiased and under a constant bias of 2; each the median GPU time of its
/// command buffers after one untimed, printed with the form. Nothing about the times is asserted.
#[test]
fn the_shader_unorm_depth_costs_against_a_float_depth() {
let (messages, _cache, probe) = validated();
let device = probe.device.name().to_owned();
let profile = probe.device.compile_device().profile();
let form = |deviation| match profile.takes_driver_deviation(deviation) {
true => "the device's conversion",
false => "the fragment stage's codes",
};
let target = |pf: PixelFormat| {
let mut d = TextureDescriptor::texture_2d(pf, COST_SIDE, COST_SIDE, false);
d.usage = TextureUsage::RENDER_TARGET;
d.resource_options = ResourceOptions::private();
probe.device.new_texture(&d).unwrap()
};
let color = target(PixelFormat::RGBA8Unorm);
let state = probe.state(CompareFunction::Less, true, None);
let mut lines = Vec::new();
for depth_format in [PixelFormat::Depth16Unorm, PixelFormat::Depth32Float] {
let depth = target(depth_format);
let pipe = WHITE.depth(depth_format);
for constant in [0.0f32, 2.0] {
let sided_before = probe.device.work_counts().depth16_sided_draws;
let mut times = Vec::with_capacity(TIMED);
for run in 0..=TIMED {
let mut pass = RenderPassDescriptor::new();
let attachment = &mut pass.color_attachments[0];
attachment.texture = Some(color.clone());
attachment.load_action = LoadAction::Clear;
attachment.store_action = StoreAction::Store;
pass.depth_attachment.texture = Some(depth.clone());
pass.depth_attachment.load_action = LoadAction::Clear;
pass.depth_attachment.clear_depth = 1.0;
pass.depth_attachment.store_action = StoreAction::Store;
let command_buffer = probe.queue.command_buffer().unwrap();
let mut encoder = command_buffer.render_command_encoder(&pass).unwrap();
let mut held = Vec::new();
encoder.set_depth_stencil_state(&state).unwrap();
encoder.set_depth_bias(constant, 0.0, 0.0).unwrap();
for layer in 0..LAYERS {
let z = 0.1 + f32::from(layer) * 0.05;
probe.draw(&mut encoder, &mut held, pipe, z, 0.0);
}
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer
.wait_until_completed_for(super::WAIT)
.unwrap();
assert_eq!(command_buffer.error(), None);
if run > 0 {
let start = command_buffer.gpu_start_time().unwrap();
let end = command_buffer.gpu_end_time().unwrap();
times.push((end - start) * 1e6);
}
}
times.sort_by(f64::total_cmp);
let deviation = match constant == 0.0 {
true => DriverDeviation::MetalDepth16Stores,
false => DriverDeviation::MetalDepth16BiasedStores,
};
// A stage that declares its bias's side (`WorkCounts::depth16_sided_draws`) lets the
// device test the depth before it runs.
let sided = probe.device.work_counts().depth16_sided_draws > sided_before;
let through = match depth_format {
PixelFormat::Depth16Unorm if sided => {
"the fragment stage's codes, its side declared"
}
PixelFormat::Depth16Unorm => form(deviation),
_ => "the device's test",
};
lines.push(format!(
"{depth_format:?} biased by {constant} ({through}): {:.0} us",
times[TIMED / 2]
));
}
}
eprintln!(
"UNORM-DEPTH-COST {device}: {COST_SIDE}x{COST_SIDE}, {LAYERS} layers front to back, \
median GPU time of {TIMED}: {}",
lines.join(", ")
);
quiet(probe, &messages);
}
-96
View File
@@ -135,22 +135,6 @@
//! drawn from each primitive's last index first (`BindShape::mesh_last_first`) of an emulated
//! mesh function's pipeline of lines or triangles runs the variant whose synthesized vertex
//! stage reads its corners so (`VariantKey::mesh_last_first`).
//! - **Pass depth**. Plain Metal stores into the render pass's depth whatever depth format the
//! pipeline names: a draw against a `Depth16Unorm` depth whose pipeline names another, or
//! against another depth (the hidden `float` one included) whose pipeline names `Depth16Unorm`
//! (`BindShape::depth16_pass`), runs the variant whose fragment stage takes Metal's 16-bit codes,
//! or leaves the depth to the device, by the pass's depth (`VariantKey::depth16_pass`), where the
//! two forms differ (`compile::depth16_stage_form`).
//! - **Biased depth**. A draw that biases a `Depth16Unorm` depth (`BindShape::depth16_biased`) on
//! a profile whose device stores unbiased depths as Metal's codes but not biased ones
//! (`DriverDeviation::MetalDepth16Stores` without `DriverDeviation::MetalDepth16BiasedStores`)
//! runs the variant whose fragment stage adds Metal's bias and writes Metal's code
//! (`VariantKey::depth16_biased`), where its fragment function writes and reads no depth of its
//! own and declares no early tests; every other draw keeps the device's depth. A biased draw
//! whose fragment stage adds the bias itself (that variant, or any draw where the device stores
//! no depth as Metal's code) and whose bias's side the consumer proved
//! (`BindShape::depth16_bias_raises`) runs the variant whose stage declares the side
//! (`VariantKey::depth16_bias_raises`).
//! - **Tested storage writes**. A fragment function that stores a color through the interlocked
//! storage form and declares no early tests only because it discards
//! (`RuntimeFact::TestedStorageWrites`), in a pipeline with a depth or stencil attachment, stores
@@ -1460,57 +1444,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::MeshLastFirst);
// A draw that biases a `Depth16Unorm` depth on a profile that stores its unbiased depths as
// Metal's codes but not its biased ones: the variant whose fragment stage adds the bias and
// writes Metal's code, where its function can take that form (`LoweringInputs::depth16_codes`):
// it writes and reads no depth of its own (a written depth takes no bias, and one read from
// the position keeps the device's) and declares no early tests.
let named_depth16 = p.graphics.depth_format == Some(vk::Format::D16_UNORM);
let pass_depth16 = shape.depth16_pass.unwrap_or(named_depth16);
let stage_form = |biased| {
crate::pipeline::compile::depth16_stage_form(
!p.graphics.rasterizer_discard,
p.graphics.rasterization_samples.as_raw(),
biased,
profile,
)
};
let depth16_biased = shape.depth16_biased
&& pass_depth16
&& !p.graphics.writes_depth
&& !p.graphics.reads_position_depth
&& !p.graphics.early_fragment_tests
&& stage_form(true)
&& !stage_form(false);
let compiled_biased = p
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::Depth16Biased);
// A biased draw of proven side whose fragment stage adds the bias itself (the variant above,
// or every draw where the device stores no depth as Metal's code): the variant whose stage
// declares the side.
let depth16_bias_raises = shape.depth16_bias_raises.filter(|_| {
shape.depth16_biased
&& pass_depth16
&& !p.graphics.writes_depth
&& !p.graphics.reads_position_depth
&& !p.graphics.early_fragment_tests
&& stage_form(depth16_biased)
});
let compiled_bias_raises = p.dependencies.iter().find_map(|d| match d.fact {
RuntimeFact::Depth16BiasSide { raises } => Some(raises),
_ => None,
});
// A draw against a depth whose format is `Depth16Unorm` where the pipeline names another, or
// the other way round: the variant whose fragment stage takes Metal's codes by the pass's
// depth, where the pipeline's fragment stage can take them at all.
let depth16_pass = shape
.depth16_pass
.filter(|&depth16| depth16 != named_depth16 && stage_form(depth16_biased));
let compiled_depth16_pass = p.dependencies.iter().find_map(|d| match d.fact {
RuntimeFact::Depth16Pass { depth16 } => Some(depth16),
_ => None,
});
// A fragment function that stores a color through the interlocked storage form before the
// depth and stencil tests, since it discards (`RuntimeFact::TestedStorageWrites`), in a
// pipeline with a depth or stencil attachment: Metal's store, as compiled, where the draw's
@@ -1830,12 +1763,8 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
// The encoder's alpha test reference, which instantiation reads from the state.
PushField::AlphaTestReference if stage == Stage::Fragment => {}
PushField::HalfBlendColor if stage == Stage::Fragment => {}
// The draw's depth bias, which instantiation reads from the state.
PushField::DepthBias if stage == Stage::Fragment => {}
// The storage form's kept channels, which instantiation reads from the template.
PushField::StorageKeptChannels if stage == Stage::Fragment => {}
// An attachment's rule word, which instantiation reads from the template.
PushField::ColorWriteRule(_) if stage == Stage::Fragment => {}
// A draw of one amplification's id and offsets, which instantiation writes before
// each draw; the placement order puts them right after the addresses, so the window
// holds them.
@@ -2170,10 +2099,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
}
}
}
// The sRGB color table, the same bytes for every pipeline.
SyntheticBinding::ColorWriteTable if stage == Stage::Fragment => {
WriteSource::ColorWriteTable
}
// The command buffer's status, on a device that does not address buffers.
SyntheticBinding::ExecutionStatus => WriteSource::ExecutionStatus,
// The stage's write-only store sink, which a dropped store through a
@@ -2620,9 +2545,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
variant.depth_clamp_range = depth_clamp_range;
variant.rotated_weights = rotated_weights;
variant.mesh_last_first = mesh_last_first;
variant.depth16_pass = depth16_pass;
variant.depth16_biased = depth16_biased;
variant.depth16_bias_raises = depth16_bias_raises;
variant.read_only_tests = read_only_tests;
variant.shader_tests = shader_tests;
variant.shader_stencil = shader_stencil;
@@ -2666,9 +2588,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
|| compiled_range != depth_clamp_range
|| compiled_rotated != rotated_weights
|| compiled_last_first != mesh_last_first
|| compiled_depth16_pass != depth16_pass
|| compiled_biased != depth16_biased
|| compiled_bias_raises != depth16_bias_raises
|| compiled_tests != read_only_tests
|| compiled_shader_tests != shader_tests
|| compiled_shader_stencil != shader_stencil
@@ -2709,7 +2628,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
deindexed: primitive_id_indices,
private_list,
storage_kept: storage_kept(p)?,
color_write_rules: p.graphics.color_write_rules.clone(),
}),
views,
})
@@ -4577,13 +4495,6 @@ fn instantiate(
.flat_map(|v| v.to_le_bytes())
.collect(),
PushField::StorageKeptChannels => FieldBytes::of(&t.storage_kept.to_le_bytes()),
// The attachment's rule word, as link derived it from the pipeline's attachment.
PushField::ColorWriteRule(color) => {
match t.color_write_rules.iter().find(|(c, _)| *c == color) {
Some((_, word)) => FieldBytes::of(&word.to_le_bytes()),
None => return Err(internal("a color write rule link gave no word")),
}
}
// The blend color as an extended-range blend reads it, and one minus it.
PushField::BlendColor => FieldBytes::words(
crate::lower::arith::extended_range::blend_color::constant_words(
@@ -4600,13 +4511,6 @@ fn instantiate(
.iter()
.flat_map(|c| c.to_bits().to_le_bytes())
.collect(),
// The draw's depth bias, and a zero word.
PushField::DepthBias => state
.depth_bias
.iter()
.chain(&[0.0])
.flat_map(|v| v.to_bits().to_le_bytes())
.collect(),
// The first amplification's; `amplifications` writes each before its draw.
PushField::AmplificationId
| PushField::AmplificationLayerOffset
@@ -608,7 +608,6 @@ fn instantiation_bounds_a_draw_by_its_index_buffer() {
deindexed: None,
private_list: false,
storage_kept: 0,
color_write_rules: Vec::new(),
};
let state = BindState::default();
let past = indexed_in(vk::IndexType::UINT32, 40, 8, 10);
@@ -658,7 +657,6 @@ fn a_draw_of_no_index_binds_inside_the_buffer() {
deindexed: None,
private_list: false,
storage_kept: 0,
color_write_rules: Vec::new(),
};
let state = BindState::default();
let bound = |cmds: &DrawCommands| match cmds.draw {
@@ -743,7 +741,6 @@ fn an_unbounded_indexed_indirect_draw_reads_its_arguments() {
deindexed: None,
private_list: false,
storage_kept: 0,
color_write_rules: Vec::new(),
};
let state = BindState::default();
for robust in [false, true] {
@@ -802,7 +799,6 @@ fn draws_bind_vertex_buffers_at_aligned_offsets_with_their_windows() {
deindexed: None,
private_list: false,
storage_kept: 0,
color_write_rules: Vec::new(),
};
let state = |offsets: (u64, u64), stride| {
let buffer = |offset, attribute_stride| BoundBuffer::Buffer {
@@ -894,7 +890,6 @@ fn inline_vertex_bytes_bind_the_strides_a_dynamic_layout_reads() {
deindexed: None,
private_list: false,
storage_kept: 0,
color_write_rules: Vec::new(),
};
let state = |attribute_stride| {
let mut t = StageTable::default();
@@ -1530,7 +1525,6 @@ fn mesh_template(flat: bool, multiples: Vec<u32>) -> GraphicsTemplate {
deindexed: None,
private_list: false,
storage_kept: 0,
color_write_rules: Vec::new(),
}
}
+2 -4
View File
@@ -435,15 +435,13 @@ fn member_view(
let use_ = heap_storage_use(profile);
let c = storage_choice(pixel_format, use_, profile).map_err(bind_error)?;
// The class's one formatless declaration cannot convert per element, but for a
// half-float format's rounding, which a heap write takes from the class its handle
// carries: such a member is viewed through its own format.
// half-float format's NaN, which a heap write takes from the class its handle carries:
// such a member is viewed through its own format.
let per_element = matches!(
c.class,
StorageImageClass::Identity
| StorageImageClass::HalfTowardZero
| StorageImageClass::HalfQuietNan
| StorageImageClass::SmallFloatQuietNan
| StorageImageClass::OneBitAlpha
| StorageImageClass::HalfBits
);
// A half-float member's writes take the class its handle carries, as before: the alias
+1 -3
View File
@@ -208,9 +208,6 @@ pub use color_resolve::{
ResolveSource, SRGB_RESOLVE_LINEAR, SRGB_RESOLVE_THRESHOLDS,
};
pub use compressed_blit::{compressed_blit_module, CompressedBlit, CompressedBlitModule};
pub use etc_decode::{etc_decode_module, EtcDecode, EtcTexels};
// The bytes of `WriteSource::ColorWriteTable`'s buffer.
pub use crate::lower::arith::srgb::color_write_table;
pub use depth_stencil_copy::{
depth_split_module, depth_stencil_copy_modules, stencil_split_module, CopySource,
DepthSplitModule, DepthStandInForm, DepthStencilCopy, DepthStencilCopyModules, StencilBit,
@@ -221,6 +218,7 @@ pub use depth_stencil_resolve::{
ResolveWrite,
};
pub use dispatch::{Dispatch, DispatchCommands, DispatchRegion, IndirectArgs};
pub use etc_decode::{etc_decode_module, EtcDecode, EtcTexels};
pub use extended_shadow::{extended_shadow_module, ExtendedShadowModule};
pub use graphics::{
DrawCall, DrawCommands, IndexOverrun, MeshDispatch, MeshGroups, MeshRecordsRegion,
-10
View File
@@ -235,11 +235,6 @@ pub struct GraphicsTemplate {
/// write.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) storage_kept: u32,
/// `PushField::ColorWriteRule`: the rule word of each color attachment whose rules the
/// fragment function selects, by color index (`GraphicsState::color_write_rules`), which its
/// draws write.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) color_write_rules: Vec<(u32, u32)>,
}
/// What a mesh draw of a mesh render pipeline instantiates: the pipeline's specialization layout
@@ -810,11 +805,6 @@ pub enum WriteSource {
/// zero ([`ExecutionStatus::initial`](crate::bind::ExecutionStatus::initial)). The consumer
/// reads it once the command buffer completes.
ExecutionStatus,
/// The fragment stage's sRGB color table (`SyntheticBinding::ColorWriteTable`): a read-only
/// buffer holding exactly [`color_write_table`](crate::bind::color_write_table)'s bytes,
/// bound whole, as the write's descriptor type says (a uniform buffer, or a storage buffer).
/// The bytes are the same for every pipeline, so the consumer may keep one such buffer.
ColorWriteTable,
/// The stand-in of the render pass's depth attachment that a fragment function that runs
/// the draw's depth test itself tests and writes (`GraphicsState::shader_tests`): the
/// consumer's `R32_SFLOAT` storage image of the attachment's extent, holding its samples as
-57
View File
@@ -213,30 +213,6 @@ pub struct BindState {
/// for every other draw.
#[cfg_attr(feature = "serde", serde(default))]
pub mesh_last_first: bool,
/// Whether the depth the draw renders against is `Depth16Unorm`: its render pass's depth
/// attachment's format, or `false` for the hidden `float` depth a pass without one tests;
/// `None` where the draw has no depth. Plain Metal stores into that depth whatever format the
/// draw's pipeline names, so a draw whose pipeline names otherwise runs the variant whose
/// fragment stage takes Metal's 16-bit codes by it (`BindShape::depth16_pass`,
/// `VariantKey::depth16_pass`). Part of the shape; `None` for every other encoder.
#[cfg_attr(feature = "serde", serde(default))]
pub depth16_pass: Option<bool>,
/// Whether the draw biases its triangles' depths by Metal's factors: a constant or slope factor
/// other than 0 (`setDepthBias:slopeScale:clamp:`), for a draw of triangles whose viewports
/// take no bias. Where the depth is `Depth16Unorm` and the device stores unbiased depths as
/// Metal's codes but not biased ones, the draw runs the variant whose fragment stage adds the
/// bias itself (`BindShape::depth16_biased`, `VariantKey::depth16_biased`). Part of the shape;
/// `false` for every other draw.
#[cfg_attr(feature = "serde", serde(default))]
pub depth16_biased: bool,
/// The side of the draw's depth bias, where the consumer proved it: `Some(true)` where Metal's
/// biased depth is never below the fragment's own, `Some(false)` where it is never above
/// (`metal::state::depth16_bias_side`). Where the depth is `Depth16Unorm` and the draw's
/// fragment stage adds the bias itself, the draw runs the variant whose stage declares that
/// side (`BindShape::depth16_bias_raises`, `VariantKey::depth16_bias_raises`), so the device
/// may test the depth before the stage runs. Part of the shape; `None` for every other draw.
#[cfg_attr(feature = "serde", serde(default))]
pub depth16_bias_raises: Option<bool>,
/// Allocations a pointer may reach that the consumer lists apart from `used_resources`, at
/// their own lengths: the resident set holds them beside the bound buffers and the used
/// resources, and a replay's extents count them (the runtime's live buffers of their own,
@@ -316,15 +292,6 @@ pub struct BindState {
/// depend on it, so it is not part of the shape.
#[cfg_attr(feature = "serde", serde(default))]
pub stencil_references: [u32; 2],
/// The draw's depth bias as a fragment stage that stores Metal's `Depth16Unorm` codes itself
/// adds it (`PushField::DepthBias`, `RuntimeFact::Depth16Codes`): Metal's constant as a
/// depth (`metal::state::depth16_bias`), then its slope and clamp factors, all 0 where the
/// draw's bias touches no depth (Metal's default, a draw of points or lines, a bias the draw's
/// viewports take). Read only by a draw of such a pipeline, whose consumer records the draw's
/// Vulkan depth bias as zero; only the draw's bytes depend on it, so it is not part of the
/// shape.
#[cfg_attr(feature = "serde", serde(default))]
pub depth_bias: [f32; 3],
}
/// What a draw's depth and stencil tests can do to its fragments (`BindState::fragment_tests`).
@@ -733,9 +700,6 @@ impl BindState {
fragment_tests: self.fragment_tests,
extended_shadows: self.extended_shadows.clone(),
snapshot_textures: self.snapshot_textures.clone(),
depth16_pass: self.depth16_pass,
depth16_biased: self.depth16_biased,
depth16_bias_raises: self.depth16_bias_raises,
primitive_id_indices: self.primitive_id_indices,
quad_primitive_ids: self.quad_primitive_ids,
private_list: self.private_list,
@@ -790,9 +754,6 @@ impl BindState {
fragment_tests,
extended_shadows,
snapshot_textures,
depth16_pass,
depth16_biased,
depth16_bias_raises,
primitive_id_indices,
quad_primitive_ids,
private_list,
@@ -823,9 +784,6 @@ impl BindState {
&& self.fragment_tests == *fragment_tests
&& self.extended_shadows == *extended_shadows
&& self.snapshot_textures == *snapshot_textures
&& self.depth16_pass == *depth16_pass
&& self.depth16_biased == *depth16_biased
&& self.depth16_bias_raises == *depth16_bias_raises
&& self.primitive_id_indices == *primitive_id_indices
&& self.quad_primitive_ids == *quad_primitive_ids
&& self.private_list == *private_list
@@ -1700,21 +1658,6 @@ pub struct BindShape {
/// the pipeline can read through a snapshot so (`VariantKey::snapshot_textures`).
#[cfg_attr(feature = "serde", serde(default))]
pub snapshot_textures: BTreeSet<u32>,
/// `BindState.depth16_pass`: where it differs from the pipeline's depth format, the variant
/// whose fragment stage takes Metal's 16-bit depth codes by the pass's depth
/// (`VariantKey::depth16_pass`).
#[cfg_attr(feature = "serde", serde(default))]
pub depth16_pass: Option<bool>,
/// `BindState.depth16_biased`: against a `Depth16Unorm` depth, on a profile whose device
/// stores unbiased depths as Metal's codes but not biased ones, the variant whose fragment
/// stage adds the draw's bias and writes Metal's code (`VariantKey::depth16_biased`).
#[cfg_attr(feature = "serde", serde(default))]
pub depth16_biased: bool,
/// `BindState.depth16_bias_raises`: where the draw's fragment stage adds a `Depth16Unorm`
/// depth's bias itself, the variant whose stage declares the bias's side
/// (`VariantKey::depth16_bias_raises`).
#[cfg_attr(feature = "serde", serde(default))]
pub depth16_bias_raises: Option<bool>,
/// `BindState.primitive_id_indices`: the primitive ID's de-indexed variant of an indexed
/// draw's index type (`VariantKey::primitive_id_indices`), where the pipeline writes the ID.
#[cfg_attr(feature = "serde", serde(default))]
+4 -14
View File
@@ -58,8 +58,8 @@ use crate::pipeline::lower_inputs::{
};
use crate::pipeline::stage_io::{
CoverageLoop, CoverageLoopRefusal, DepthCompares, DepthMode, Interpolation as IoInterpolation,
IoNumeric, IoRole, IoType, IoVariable, PulledInput, Sampling as IoSampling, SelectedWrite,
StageBuiltin, StageInFetch, StageInInput, StageIo,
IoNumeric, IoRole, IoType, IoVariable, PulledInput, Sampling as IoSampling, StageBuiltin,
StageInFetch, StageInInput, StageIo,
};
use crate::pipeline::sym::{
AccelerationStructureLevel, AirUserKey, Axis, CombinedSampler, HandleClass, ImageAccess,
@@ -839,7 +839,6 @@ codec_enum! {
MeshWork,
TessellationWork,
TessellationRecords,
ColorWriteTable,
DepthStandIn,
StencilStandIn,
StoreSink,
@@ -888,9 +887,7 @@ codec_enum! {
ShaderStencilState,
TextureIntegerChannels(f0),
Specialized(f0),
ColorWriteRule(f0),
HalfBlendColor,
DepthBias,
SnapshotPhase,
VerticesPerPrimitive,
TessellationChunk,
@@ -1134,14 +1131,13 @@ codec_struct! {
early_fragment_tests, extended_range_colors, unattached_colors, half_bit_colors,
sample_mask, rotated_colors, rotated_factors, rotated_blends, srgb_fetches,
half_output_lanes, texture_write_rounding, uniform_outputs, uniform_inputs,
instanced_attributes, selected_colors, half_blend_colors, half_fast_colors,
instanced_attributes, half_blend_colors, half_fast_colors,
float_blend_colors, zero_indices, color_group, word_colors, alpha_in_red_colors,
alpha_test, depth_compares,
}
DepthCompares { samplers, clamped }
ColorGroup { present, width, group }
WordField { shift, bits }
SelectedWrite { lanes, rounds, nans }
ExtendedRangeColor { form, blended, nearest_even }
PulledInput { index, ty, fetch }
StageInInput { index, ty, fetch }
@@ -1177,7 +1173,6 @@ codec_enum! {
Unorm { bits }, Snorm { bits, blended }, Srgb, FloatTowardZero { mantissa, signed }, Device,
FloatNearestEven { mantissa, signed }, BlendedNearestEven { mantissa, signed },
HalfUnorm { bits },
Selected,
}
ExtendedRange {
Bgr10 { srgb }, Bgra10 { srgb }, Planes { srgb }, R10X6, Rg10X12, R10X6Srgb, Rg10X12Srgb,
@@ -1274,10 +1269,6 @@ codec_enum! {
StorageTextureIntegerChannels { slot },
HeapHalfTexelWrites { stage, packed },
MovableStorageWrites { early_variant },
Depth16Codes { biased },
Depth16Pass { depth16 },
Depth16Biased,
Depth16BiasSide { raises },
SynthesizedGeometry { weights, layer, viewport },
ObjectThreadgroupArena { static_bytes, payload },
ExactFormsOverCompilerLimit {
@@ -1382,8 +1373,7 @@ codec_struct! {
writes_point_size, flat_fragment_inputs,
clip_distances, writes_depth, reads_barycentric_coord, reads_primitive_id,
reads_position_depth,
fragment_writes_memory, color_outputs, sample_mask, shader_tests, color_write_rules,
snapshot_reads,
fragment_writes_memory, color_outputs, sample_mask, shader_tests, snapshot_reads,
color_group, logic_op,
}
TessellationState {
+3 -30
View File
@@ -60,7 +60,7 @@ mod tests;
/// unchanged version, and its bless records the version. Independent of the crate's version and of
/// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no
/// history.
pub const SEMANTICS_VERSION: u32 = 1872;
pub const SEMANTICS_VERSION: u32 = 1874;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 1872;
/// 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 = 455;
pub const ARTIFACT_FORMAT_VERSION: u32 = 457;
/// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding
/// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 455;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 1656;
pub const RUNTIME_VERSION: u32 = 1657;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
@@ -324,30 +324,6 @@ pub struct VariantKey {
/// (`RuntimeFact::MeshLastFirst`).
#[cfg_attr(feature = "serde", serde(default))]
pub mesh_last_first: bool,
/// Whether the draw's render pass depth is `Depth16Unorm`, where the render pipeline's depth
/// format says otherwise (`BindShape::depth16_pass`): plain Metal stores into the pass's depth
/// whatever format the pipeline names, so the variant's fragment stage writes Metal's 16-bit
/// codes, or leaves the depth to the device, by the pass's format
/// (`LoweringInputs::depth16_codes`). The plan of a pipeline compiled under it states it
/// (`RuntimeFact::Depth16Pass`).
#[cfg_attr(feature = "serde", serde(default))]
pub depth16_pass: Option<bool>,
/// Whether the draw biases a `Depth16Unorm` depth on a profile that stores the pass's
/// unbiased depths as Metal's codes but not its biased ones (`BindShape::depth16_biased`): the
/// variant's fragment stage adds the draw's bias and writes Metal's code itself
/// (`LoweringInputs::depth16_codes`), where a pipeline compiled without it leaves the depth to
/// the device. The plan of a pipeline compiled under it states it
/// (`RuntimeFact::Depth16Biased`).
#[cfg_attr(feature = "serde", serde(default))]
pub depth16_biased: bool,
/// The side of the draw's bias of a `Depth16Unorm` depth whose fragment stage adds the bias
/// itself, where the runtime proved it (`BindShape::depth16_bias_raises`): `Some(true)` where
/// Metal's biased depth is never below the fragment's own, `Some(false)` where it is never
/// above. The variant's fragment stage declares it (`LoweringInputs::depth16_bias_raises`), so
/// the device may test the depth before the stage runs. The plan of a pipeline compiled under
/// it states it (`RuntimeFact::Depth16BiasSide`).
#[cfg_attr(feature = "serde", serde(default))]
pub depth16_bias_raises: Option<bool>,
/// Storage-image texture slots bound to a texture with a swizzle (`MTLTexture.swizzle` other
/// than the default) whose texels the function reads or writes
/// (`LoweringInputs::swizzled_storage`): a Vulkan storage view takes no swizzle, so the
@@ -576,9 +552,6 @@ impl VariantKey {
&& !self.depth_clamp_range
&& !self.rotated_weights
&& !self.mesh_last_first
&& self.depth16_pass.is_none()
&& !self.depth16_biased
&& self.depth16_bias_raises.is_none()
&& self.swizzled_storage.is_empty()
&& !self.addressed_function_tables
&& self.interlocked_colors.is_empty()
@@ -259,19 +259,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
// The binder holds each half-float member the twin takes there; the consumer announces
// a member it does not take where its heap holds one.
RuntimeFact::HeapHalfTexelWrites { .. } => Mechanism::BinderView,
// The binder pushes the draw's depth bias; the consumer records its Vulkan bias as zero.
RuntimeFact::Depth16Codes { biased: true } => Mechanism::PushConstant,
// The function's returned depth, which Metal does not bias: nothing to meet.
RuntimeFact::Depth16Codes { biased: false } => Mechanism::None,
// A separate compile of the pipeline, which a pass whose depth is or is not
// `Depth16Unorm` where the pipeline names otherwise asks for.
RuntimeFact::Depth16Pass { .. } => Mechanism::Variant,
// A separate compile of the pipeline, which a draw that biases a `Depth16Unorm` depth
// asks for where the device stores its biased depths otherwise than Metal.
RuntimeFact::Depth16Biased => Mechanism::Variant,
// A separate compile of the pipeline, which a draw whose depth bias has a proven side
// asks for where the fragment stage adds the bias itself.
RuntimeFact::Depth16BiasSide { .. } => Mechanism::Variant,
// The pipeline's own stages, which every draw of its class runs; the consumer announces
// them.
RuntimeFact::SynthesizedGeometry { .. } => Mechanism::None,
@@ -247,12 +247,6 @@ fn every_fact() -> Vec<RuntimeFact> {
RuntimeFact::MovableStorageWrites {
early_variant: true,
},
RuntimeFact::Depth16Codes { biased: true },
RuntimeFact::Depth16Codes { biased: false },
RuntimeFact::Depth16Pass { depth16: true },
RuntimeFact::Depth16Biased,
RuntimeFact::Depth16BiasSide { raises: true },
RuntimeFact::Depth16BiasSide { raises: false },
RuntimeFact::SynthesizedGeometry {
weights: true,
layer: false,
@@ -369,21 +363,17 @@ fn variant(f: &RuntimeFact) -> usize {
RuntimeFact::StorageTextureIntegerChannels { .. } => 81,
RuntimeFact::HeapHalfTexelWrites { .. } => 82,
RuntimeFact::MovableStorageWrites { .. } => 83,
RuntimeFact::Depth16Codes { .. } => 84,
RuntimeFact::Depth16Pass { .. } => 85,
RuntimeFact::Depth16Biased => 86,
RuntimeFact::Depth16BiasSide { .. } => 87,
RuntimeFact::SynthesizedGeometry { .. } => 88,
RuntimeFact::ObjectThreadgroupArena { .. } => 89,
RuntimeFact::ExactFormsOverCompilerLimit { .. } => 90,
RuntimeFact::WordInputMerge { .. } => 91,
RuntimeFact::ReplayBindings => 92,
RuntimeFact::MergedDraws => 93,
RuntimeFact::QuadPrimitiveIds => 94,
RuntimeFact::RotatedWeights => 95,
RuntimeFact::PrivateList => 96,
RuntimeFact::MeshLastFirst => 97,
RuntimeFact::YCbCrInPlace { .. } => 98,
RuntimeFact::SynthesizedGeometry { .. } => 84,
RuntimeFact::ObjectThreadgroupArena { .. } => 85,
RuntimeFact::ExactFormsOverCompilerLimit { .. } => 86,
RuntimeFact::WordInputMerge { .. } => 87,
RuntimeFact::ReplayBindings => 88,
RuntimeFact::MergedDraws => 89,
RuntimeFact::QuadPrimitiveIds => 90,
RuntimeFact::RotatedWeights => 91,
RuntimeFact::PrivateList => 92,
RuntimeFact::MeshLastFirst => 93,
RuntimeFact::YCbCrInPlace { .. } => 94,
}
}
@@ -391,7 +381,7 @@ fn variant(f: &RuntimeFact) -> usize {
fn mechanism_is_total_over_every_fact_and_profile() {
let facts = every_fact();
let covered: std::collections::BTreeSet<usize> = facts.iter().map(variant).collect();
assert_eq!(covered, (0..99).collect(), "every_fact misses a variant");
assert_eq!(covered, (0..95).collect(), "every_fact misses a variant");
for (stem, _) in super::committed_profiles() {
let dev = device(&stem);
let p = dev.profile();
@@ -471,9 +461,6 @@ fn mechanism_is_total_over_every_fact_and_profile() {
| RuntimeFact::DepthClampRange
| RuntimeFact::RotatedWeights
| RuntimeFact::MeshLastFirst
| RuntimeFact::Depth16Pass { .. }
| RuntimeFact::Depth16Biased
| RuntimeFact::Depth16BiasSide { .. }
| RuntimeFact::TestedStorageWrites { .. }
| RuntimeFact::MovableStorageWrites { .. }
| RuntimeFact::YCbCrTexture { .. }
@@ -529,15 +516,13 @@ fn mechanism_is_total_over_every_fact_and_profile() {
| RuntimeFact::StorageTextureIntegerChannels { .. }
| RuntimeFact::AccelerationStructureInstanceCount { .. }
| RuntimeFact::ViewportCount
| RuntimeFact::Depth16Codes { biased: true }
// The bound texture's format class, which the binder pushes.
| RuntimeFact::TexelFormat { .. } => Mechanism::PushConstant,
RuntimeFact::AliasedImageblock { .. } => Mechanism::None,
RuntimeFact::CallStackDepth { .. }
| RuntimeFact::AbsentArgumentRead { .. }
| RuntimeFact::SynthesizedGeometry { .. }
| RuntimeFact::ExactFormsOverCompilerLimit { .. }
| RuntimeFact::Depth16Codes { biased: false } => Mechanism::None,
| RuntimeFact::ExactFormsOverCompilerLimit { .. } => Mechanism::None,
};
assert_eq!(m, expected, "{stem}: {fact:?}");
}
@@ -1,25 +1,18 @@
//! A fragment function's float color output rounded to the code Metal stores.
//! A float rounded to the code Metal stores in a color channel, where a translation writes the
//! code itself rather than leaving the conversion to the device.
//!
//! Metal converts a float written to a normalized attachment by the exact product with the
//! format's maximum code, rounded to nearest; to an 8-bit sRGB channel by its twelve-bit encode;
//! and to a half-float channel, or one of `RG11B10Float`'s, rounded toward zero
//! (`LoweringInputs::color_writes`). A Vulkan driver rounds the `f32` product, encodes sRGB by its
//! own approximation, and rounds a half to nearest, so near each tie it stores another code.
//! [`round`] computes Metal's code in the shader and writes the value the device stores as exactly
//! that code:
//! A fragment function's color output is the device's to convert (`LoweringInputs::color_writes`):
//! these rules serve the writes whose value the translation computes, Metal's
//! `textureWriteRoundingMode` 2 (a half-float channel rounded to nearest even), and the blends the
//! shader computes in the storage form of framebuffer fetch, whose result it stores itself:
//!
//! - unorm and snorm ([`ChannelWrite::Unorm`], [`ChannelWrite::Snorm`]): NaN is 0 (a blended
//! snorm NaN is `-1`, whose code is `-m`, as Metal stores it), the value is clamped to
//! `[0, 1]` (`[-1, 1]`), the code `c` is the exact product with `m = 2^k - 1` rounded to
//! nearest (`round_mersenne_product`, about fourteen float instructions; its only ties, at `x =
//! ±0.5`, round to even as Metal's round away from zero), and the value written is `c` times the
//! `f32` nearest `1 / m`: within two `f32` rounding errors of `c / m`, so its product with `m`
//! lies within `2^-7` of `c` (`m < 2^16`) and a device that rounds the product to nearest stores
//! `c`, as Vulkan's conversion does, whatever it does at ties;
//! - sRGB ([`ChannelWrite::Srgb`]): NaN is 0, the value is clamped to `[0, 1]`, the byte is
//! Metal's twelve-bit encode of the exact product with `4095 = 2^12 - 1`, rounded as a unorm
//! channel's, and the value written is that byte's linear value: an estimate and one read of
//! the color table, a buffer of the module's ([`srgb::color_linear`]);
//! - unorm ([`ChannelWrite::Unorm`]): NaN is 0, the value is clamped to `[0, 1]`, the code `c` is
//! the exact product with `m = 2^k - 1` rounded to nearest (`round_mersenne_product`, about
//! fourteen float instructions; its only ties, at `x = 0.5`, round to even as Metal's round away
//! from zero), and the value written is `c` times the `f32` nearest `1 / m`: within two `f32`
//! rounding errors of `c / m`, so its product with `m` lies within `2^-7` of `c` (`m < 2^16`)
//! and a device that rounds the product to nearest stores `c`, as Vulkan's conversion does,
//! whatever it does at ties;
//! - a small float ([`ChannelWrite::FloatTowardZero`]: a half, or an unsigned 11- or 10-bit
//! float): the value rounded toward zero, by integer operations on the bits, to the `f32` that
//! holds it exactly: a finite value past the largest is the largest, an infinity stays, a NaN
@@ -28,110 +21,41 @@
//! - a small float rounded to nearest even ([`ChannelWrite::FloatNearestEven`], a render
//! pipeline's half-float channel under Apple's `textureWriteRoundingMode` 2): the same, but the
//! dropped bits rounded to nearest with ties to even, by integer operations on the bits, and a
//! finite value from the midpoint past the largest infinity;
//! - a packed 16-bit format's unorm channel ([`ChannelWrite::HalfUnorm`]): the value rounded to a
//! half to nearest even as above, then as a unorm channel's.
//! finite value from the midpoint past the largest infinity.
//!
//! A channel without a rule ([`ChannelWrite::Device`] or `None`) is written as computed. A
//! channel the device is measured to convert as Metal does but for a NaN ([`Lane::NanAs`]) is
//! written as computed with a NaN chosen as the value whose store is Metal's.
//!
//! A channel whose rule the draw selects ([`ChannelWrite::Selected`], [`Lane::Selected`]) computes
//! each selectable rule's value and selects one by its code in the attachment's rule word
//! (`pipeline::color_writes::rule_words`): the value as computed for the device's conversion or no
//! rule, the 8-bit unorm channel's rounding, or the half-float channel's.
//! A channel without a rule ([`ChannelWrite::Device`] or `None`) is written as computed.
use crate::lower::arith::legal::{FloatFmt, Form, Held};
use crate::lower::arith::ops::{fsplat, splat, ty};
use crate::lower::arith::srgb;
use crate::pipeline::color_writes::{HALF, HALF_CODE, RULE_BITS, RULE_MASK, UNORM8_CODE};
use crate::pipeline::lower_inputs::ChannelWrite;
use crate::spirv::builder::FunctionBuilder;
use crate::spirv::error::{BResult, BuildError, OperandRule};
use crate::spirv::ids::{GlobalId, TypeId, Value};
use crate::spirv::ids::{TypeId, Value};
use crate::spirv::ir::{BinOp, ConvOp, GlslOp, Type, UnOp};
/// How [`write()`] writes one lane of a color output.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Lane {
/// Rounded to the code Metal stores by the channel's rule ([`round`]).
Rounded(ChannelWrite),
/// Written as computed, a NaN as the `f32` of these bits: the device converts every other
/// value as Metal does (a measured driver deviation), and stores this NaN, or this value, as
/// Metal stores the output's NaN.
NanAs(u32),
/// Written by the rule its code in the attachment's rule word selects
/// ([`ChannelWrite::Selected`]): as computed (no rule, or the device's conversion), rounded
/// as an 8-bit unorm channel, or written as a half-float channel's lane is (`half`).
Selected {
/// How a half-float channel's lane is written from this output.
half: HalfLane,
},
}
/// How a selected lane ([`Lane::Selected`]) is written where its code selects the half-float
/// channel's rule: as the lane of [`ChannelWrite::FloatTowardZero`]'s half would be.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HalfLane {
/// As computed: a `half` output, already a half, or a `float` one the device converts as
/// Metal does, NaN included.
AsComputed,
/// Rounded toward zero to a half ([`small_float`]).
Rounded,
/// As computed, a NaN as the `f32` of these bits ([`Lane::NanAs`]).
NanAs(u32),
}
/// An upper estimate of the SPIR-V words of one lane written as `lane`.
pub fn lane_words(lane: Lane) -> u64 {
match lane {
Lane::Rounded(rule) => channel_words(rule),
// The NaN test and select, and the constant.
Lane::NanAs(_) => 3 * 6,
// The unorm rounding and the half lane, and each code's shift, mask, test and select.
Lane::Selected { half } => {
let half = match half {
HalfLane::AsComputed => 0,
HalfLane::Rounded => channel_words(HALF),
HalfLane::NanAs(_) => 3 * 6,
};
channel_words(ChannelWrite::Unorm { bits: 8 }) + half + 2 * 5 * 6
}
}
}
/// An upper estimate of the SPIR-V words of one channel's rounding by `rule`.
pub fn channel_words(rule: ChannelWrite) -> u64 {
match rule {
// The NaN select, clamp, exact product, scale and sign, their constants included: about
// 31 instructions and the product's nine `NoContraction` decorations.
ChannelWrite::Unorm { .. } | ChannelWrite::Snorm { .. } => 36 * 6,
// The NaN select, clamp, exact product and conversion (about 25 instructions and nine
// decorations), and the byte's estimate, entry read and choice.
ChannelWrite::Srgb => 32 * 6 + u64::from(srgb::COLOR_WORDS),
// The NaN select, clamp, exact product and scale, their constants included: about 31
// instructions and the product's nine `NoContraction` decorations.
ChannelWrite::Unorm { .. } => 36 * 6,
ChannelWrite::FloatTowardZero { .. } => 32 * 6,
// The rounding's bias and the denormal's shift clamped beside the toward-zero rule's.
ChannelWrite::FloatNearestEven { .. } => 36 * 6,
// The half's rounding, then the unorm channel's.
ChannelWrite::HalfUnorm { .. } => 2 * 36 * 6,
// A selected channel's words are its lane's (`Lane::Selected`).
ChannelWrite::Device | ChannelWrite::BlendedNearestEven { .. } | ChannelWrite::Selected => {
0
}
// Written as computed, or no rule [`round`] takes.
_ => 0,
}
}
/// An upper estimate of the SPIR-V words of rounding an output by `rules`, its extracts and
/// construct included.
pub fn words(rules: &[Option<ChannelWrite>; 4]) -> u64 {
write_words(&rules.map(|r| r.map(Lane::Rounded)))
}
/// An upper estimate of the SPIR-V words of writing an output by `lanes` ([`write()`]), its
/// extracts and construct included.
pub fn write_words(lanes: &[Option<Lane>; 4]) -> u64 {
let written = lanes.iter().flatten().count() as u64;
lanes.iter().flatten().map(|&l| lane_words(l)).sum::<u64>()
let written = rules.iter().flatten().count() as u64;
rules
.iter()
.flatten()
.map(|&r| channel_words(r))
.sum::<u64>()
+ written.saturating_add(1).saturating_mul(6)
}
@@ -214,35 +138,14 @@ fn malformed() -> BuildError {
}
/// Output `x` (float lanes of form `f`, a 32-bit container) with each lane `i` rounded by
/// `rules[i]` (see the module docs), an [`Srgb`](ChannelWrite::Srgb) lane through the module's
/// color table `table` ([`srgb::declare_color_table`]).
/// `rules[i]` (see the module docs): a unorm or small float channel's rule, or as computed for
/// [`ChannelWrite::Device`], [`ChannelWrite::BlendedNearestEven`] and `None`. Another rule is
/// malformed.
pub fn round(
fb: &mut FunctionBuilder<'_>,
f: Form,
x: Value,
rules: &[Option<ChannelWrite>; 4],
table: Option<GlobalId>,
) -> BResult<Value> {
write(
fb,
f,
x,
&rules.map(|r| r.map(Lane::Rounded)),
(table, None),
)
}
/// Output `x` (float lanes of form `f`, a 32-bit container) with each lane `i` written as
/// `lanes[i]` says (see the module docs), an [`Srgb`](ChannelWrite::Srgb) lane through the
/// module's color table `table` ([`srgb::declare_color_table`]), and a selected lane
/// ([`Lane::Selected`]) by its code in the attachment's rule word `word` (a `u32`), which
/// such a lane needs.
pub fn write(
fb: &mut FunctionBuilder<'_>,
f: Form,
x: Value,
lanes: &[Option<Lane>; 4],
(table, word): (Option<GlobalId>, Option<Value>),
) -> BResult<Value> {
if f.float_fmt().map(FloatFmt::container) != Some(32) || f.lanes == 0 || f.lanes > 4 {
return Err(malformed());
@@ -252,42 +155,20 @@ pub fn write(
lanes: 1,
};
let mut written = Vec::with_capacity(usize::from(f.lanes));
for (i, lane) in lanes.iter().enumerate().take(usize::from(f.lanes)) {
for (i, rule) in rules.iter().enumerate().take(usize::from(f.lanes)) {
let v = if f.lanes == 1 {
x
} else {
fb.composite_extract(x, &[i as u32])?
};
let rule = match lane {
None => None,
Some(Lane::Rounded(rule)) => Some(rule),
Some(Lane::NanAs(bits)) => {
written.push(nan_as(fb, s, v, *bits)?);
continue;
}
Some(Lane::Selected { half }) => {
let word = word.ok_or_else(malformed)?;
written.push(selected(fb, s, v, (word, i as u32), *half)?);
continue;
}
};
written.push(match rule {
written.push(match *rule {
None | Some(ChannelWrite::Device | ChannelWrite::BlendedNearestEven { .. }) => v,
Some(ChannelWrite::Unorm { bits }) => normalized(fb, s, v, unorm_bits(*bits)?, None)?,
Some(ChannelWrite::Snorm { bits, blended }) => {
normalized(fb, s, v, snorm_bits(*bits)?, Some(*blended))?
}
Some(ChannelWrite::Srgb) => srgb_channel(fb, s, v, table)?,
Some(ChannelWrite::Unorm { bits }) => normalized(fb, s, v, unorm_bits(bits)?)?,
Some(
&rule @ (ChannelWrite::FloatTowardZero { .. }
rule @ (ChannelWrite::FloatTowardZero { .. }
| ChannelWrite::FloatNearestEven { .. }),
) => small_float(fb, s, v, rule)?,
Some(ChannelWrite::HalfUnorm { bits }) => {
let h = float_nearest_even(fb, s, v, 10, true)?;
normalized(fb, s, h, unorm_bits(*bits)?, None)?
}
// A selected channel is written by its lane's form (`Lane::Selected`).
Some(ChannelWrite::Selected) => return Err(malformed()),
Some(_) => return Err(malformed()),
});
}
if let [one] = written.as_slice() {
@@ -297,49 +178,6 @@ pub fn write(
fb.composite_construct(t, &written)
}
/// `v` (an `f32` lane of form `s`) written as channel `i`'s code in the rule word `word` selects
/// ([`Lane::Selected`]): rounded as an 8-bit unorm channel (`UNORM8_CODE`), written as a
/// half-float channel's lane is by `half` (`HALF_CODE`), else as computed. Each rule's value is
/// computed and one selected, so the module is the same for every attachment.
fn selected(
fb: &mut FunctionBuilder<'_>,
s: Form,
v: Value,
(word, i): (Value, u32),
half: HalfLane,
) -> BResult<Value> {
let u = Form {
held: Held::Int {
bits: 32,
container: 32,
},
lanes: 1,
};
let shift = splat(fb, u, u64::from(RULE_BITS * i))?;
let code = fb.binary(BinOp::ShiftRightLogical, word, shift)?;
let mask = splat(fb, u, u64::from(RULE_MASK))?;
let code = fb.binary(BinOp::BitwiseAnd, code, mask)?;
let unorm = normalized(fb, s, v, unorm_bits(8)?, None)?;
let unorm_code = splat(fb, u, u64::from(UNORM8_CODE))?;
let is_unorm = fb.binary(BinOp::IEqual, code, unorm_code)?;
let out = fb.select(is_unorm, unorm, v)?;
let half = match half {
HalfLane::AsComputed => return Ok(out),
HalfLane::Rounded => small_float(fb, s, v, HALF)?,
HalfLane::NanAs(bits) => nan_as(fb, s, v, bits)?,
};
let half_code = splat(fb, u, u64::from(HALF_CODE))?;
let is_half = fb.binary(BinOp::IEqual, code, half_code)?;
fb.select(is_half, half, out)
}
/// `v` (an `f32` lane of form `s`), a NaN written as the `f32` of `bits` ([`Lane::NanAs`]).
fn nan_as(fb: &mut FunctionBuilder<'_>, s: Form, v: Value, bits: u32) -> BResult<Value> {
let is_nan = fb.unary(UnOp::IsNan, v)?;
let nan = splat(fb, s, u64::from(bits))?;
fb.select(is_nan, nan, v)
}
/// The `k` of a unorm channel's maximum code `2^k - 1`.
fn unorm_bits(bits: u8) -> BResult<u32> {
match bits {
@@ -348,14 +186,6 @@ fn unorm_bits(bits: u8) -> BResult<u32> {
}
}
/// The `k` of a snorm channel's maximum code `2^k - 1`.
fn snorm_bits(bits: u8) -> BResult<u32> {
match bits {
2..=16 => Ok(u32::from(bits) - 1),
_ => Err(malformed()),
}
}
/// `a` (`f32` lanes of form `s`, each in `[0, 1]`) times `2^k - 1` (`k` in `1..=16`), rounded to
/// the nearest integer from the exact product, ties to even, as `f32` lanes holding the integer.
/// The product's exact split is `p - w`: `p = fl(2^k a - a)` with `2^k a` exact, and `w = a + (p -
@@ -389,7 +219,7 @@ fn round_mersenne_product(
/// in `1..=16`, a value the shader may compute): `a` times `scale - 1`, rounded to nearest from
/// the exact product, ties to even, by the same instructions, so each lane is exact as the
/// constant scale's is (the split's steps do not depend on `k`'s being constant).
pub(crate) fn round_scaled_product(
fn round_scaled_product(
fb: &mut FunctionBuilder<'_>,
s: Form,
a: Value,
@@ -419,75 +249,26 @@ pub(crate) fn round_scaled_product(
/// the code is the exact product with 255 rounded to nearest ([`round_mersenne_product`]). The
/// private alpha test compares its alpha so (`stage_io::alpha_test`).
pub(crate) fn unorm8_code(fb: &mut FunctionBuilder<'_>, s: Form, v: Value) -> BResult<Value> {
let c = clamped(fb, s, v, 0.0, 0.0)?;
let c = clamped(fb, s, v)?;
round_mersenne_product(fb, s, c, unorm_bits(8)?)
}
/// `v` clamped to `[lo, 1]` with NaN taken as `nan`.
fn clamped(fb: &mut FunctionBuilder<'_>, s: Form, v: Value, nan: f64, lo: f64) -> BResult<Value> {
/// `v` clamped to `[0, 1]` with NaN taken as 0.
fn clamped(fb: &mut FunctionBuilder<'_>, s: Form, v: Value) -> BResult<Value> {
let is_nan = fb.unary(UnOp::IsNan, v)?;
let nan = fsplat(fb, s, nan)?;
let v = fb.select(is_nan, nan, v)?;
let lo = fsplat(fb, s, lo)?;
let zero = fsplat(fb, s, 0.0)?;
let v = fb.select(is_nan, zero, v)?;
let one = fsplat(fb, s, 1.0)?;
fb.glsl(GlslOp::NClamp, &[v, lo, one])
fb.glsl(GlslOp::NClamp, &[v, zero, one])
}
/// A unorm channel of maximum code `2^k - 1` (`snorm: None`), or a snorm one
/// (`Some(blended)`).
fn normalized(
fb: &mut FunctionBuilder<'_>,
s: Form,
v: Value,
k: u32,
snorm: Option<bool>,
) -> BResult<Value> {
let (nan, lo) = match snorm {
None => (0.0, 0.0),
Some(false) => (0.0, -1.0),
Some(true) => (-1.0, -1.0),
};
let v = clamped(fb, s, v, nan, lo)?;
// A unorm channel's clamped value is its magnitude.
let a = match snorm {
None => v,
Some(_) => fb.glsl(GlslOp::FAbs, &[v])?,
};
let c = round_mersenne_product(fb, s, a, k)?;
/// A unorm channel of maximum code `2^k - 1`.
fn normalized(fb: &mut FunctionBuilder<'_>, s: Form, v: Value, k: u32) -> BResult<Value> {
let v = clamped(fb, s, v)?;
let c = round_mersenne_product(fb, s, v, k)?;
let m = (1u32 << k) - 1;
let r = fsplat(fb, s, f64::from(1.0 / m as f32))?;
let q = fb.binary(BinOp::FMul, c, r)?;
if snorm.is_none() {
return Ok(q);
}
let zero = fsplat(fb, s, 0.0)?;
let negative = fb.binary(BinOp::FOrdLessThan, v, zero)?;
let minus = fb.unary(UnOp::FNegate, q)?;
fb.select(negative, minus, q)
}
/// An sRGB color channel: the linear value of the byte Metal's encode gives, from the color
/// table `table`.
fn srgb_channel(
fb: &mut FunctionBuilder<'_>,
s: Form,
v: Value,
table: Option<GlobalId>,
) -> BResult<Value> {
let Some(table) = table else {
return Err(malformed());
};
let v = clamped(fb, s, v, 0.0, 0.0)?;
let i = round_mersenne_product(fb, s, v, 12)?;
let ut = ty(
fb,
s.with(Held::Int {
bits: 32,
container: 32,
}),
)?;
let i = fb.convert(ConvOp::ConvertFToU, i, ut)?;
srgb::color_linear(fb, table, i)
fb.binary(BinOp::FMul, c, r)
}
/// An upper estimate of the SPIR-V words of [`small_float`] by `rule` on `lanes` lanes: one
@@ -525,8 +306,8 @@ pub fn small_float(
}
/// `v` (`f32` lanes of form `s`) rounded to the nearest `half`, ties to even, held in an `f32`: a
/// NaN stays a NaN and a value past the largest finite `half` an infinity (a packed 16-bit
/// format's channel reads it so, `ChannelWrite::HalfUnorm`).
/// NaN stays a NaN and a value past the largest finite `half` an infinity (a packed 16-bit word's
/// channel reads it so, `ChannelWrite::HalfUnorm`).
pub(crate) fn half_rounded(fb: &mut FunctionBuilder<'_>, s: Form, v: Value) -> BResult<Value> {
float_nearest_even(fb, s, v, 10, true)
}
@@ -2620,7 +2620,7 @@ pub fn unorm8_write(fb: &mut FunctionBuilder<'_>, arith: BlendArith, v: Value) -
match arith {
BlendArith::Float => {
let rule = Some(crate::pipeline::lower_inputs::ChannelWrite::Unorm { bits: 8 });
crate::lower::arith::color_write::round(fb, f, v, &[rule; 4], None)
crate::lower::arith::color_write::round(fb, f, v, &[rule; 4])
}
BlendArith::Half => {
let zero = fsplat(fb, f, 0.0)?;
@@ -934,11 +934,6 @@ pub struct ArithPlan {
/// `float` lane, when one of [`ArithPlan::libm`] divides; decided by [`finish`], which adds it
/// to [`ArithPlan::precise`].
pub libm_division: Option<divide::Routine>,
/// Whether a fragment function writes a float to an sRGB attachment by Metal's encode
/// ([`color_write`]), which reads the byte's linear value from the color table, and the
/// buffer the table lives in on the profile, which [`declare`] then declares once
/// ([`srgb::declare_color_table`]).
pub color_table: Option<srgb::ColorTable>,
/// Whether a function reads or writes a texture slot bound in an `_sRGB` extended-range
/// format (`LoweringInputs::extended_range`), through Metal's tables, which [`declare`] then
/// declares once ([`extended_range::declare`]).
@@ -1108,10 +1103,6 @@ pub fn routine_words(plan: &ArithPlan) -> impl Iterator<Item = (&'static str, u6
)
.chain(plan.libm.iter().map(|r| (r.name(), u64::from(r.words()))))
.chain(table)
.chain(
plan.color_table
.map(|_| (COLOR_WRITE_SRGB, u64::from(srgb::COLOR_TABLE_WORDS))),
)
.chain(extended)
.chain(padded)
}
@@ -1134,9 +1125,6 @@ pub const DOT: &str = "arith.dot.fused";
pub const CHUNKED_DOT: &str = "arith.chunked.dot.fused";
/// See [`SRGB_PACK`].
pub const SRGB_UNPACK: &str = "arith.unpack.srgb";
/// The census name of the color table a fragment function's sRGB color writes read
/// ([`ArithPlan::color_table`]).
pub const COLOR_WRITE_SRGB: &str = "arith.color_write.srgb";
/// The census name of Metal's fast division ([`ArithStrategy::FastDivide`]).
pub const FAST_DIVIDE: &str = "arith.fdiv.fast";
/// The census name of a multiply fused into the additions that use it
@@ -1288,8 +1276,6 @@ pub struct Declared {
pub fast: BTreeMap<math::FastDivision, FuncId>,
/// The sRGB table, when [`ArithPlan::srgb`].
pub srgb: Option<GlobalId>,
/// The color table, when [`ArithPlan::color_table`].
pub color_table: Option<GlobalId>,
/// The extended-range sRGB table, when [`ArithPlan::extended_range_srgb`].
pub extended_range_srgb: Option<GlobalId>,
/// The table of each of the plan's [`ArithPlan::padded_srgb`].
@@ -1327,9 +1313,6 @@ pub fn declare(
if plan.families.arith.srgb.is_some() {
decl.srgb = Some(srgb::declare(mb)?);
}
if let Some(class) = plan.families.arith.color_table {
decl.color_table = Some(srgb::declare_color_table(mb, plan.stage, class)?);
}
if plan.families.arith.extended_range_srgb {
decl.extended_range_srgb = Some(extended_range::declare(mb)?);
}
+1 -453
View File
@@ -17,27 +17,11 @@
//! The products and quotients run once per vector in `math::pack` and `math::unpack`, with a
//! per-lane scale; only the table reads are per channel, since a `Private` array is indexed by a
//! scalar.
//!
//! A fragment function's write of a float to an sRGB color attachment reads its own table instead,
//! the **color table**: 256 `uvec4` entries in a buffer the binder fills with
//! [`color_write_table`]'s bytes, entry `b` holding byte `b`'s first encode index, its linear
//! value's bits, and byte `b - 1`'s. The write estimates the byte from the index's square root to
//! within a byte above Metal's ([`ENCODE_ESTIMATE`]) and reads that byte's entry once
//! ([`color_linear`]): the index against the entry's first index chooses between the two linear
//! values. The buffer is a read-only storage buffer, or a uniform buffer where the driver reads one
//! at different addresses faster ([`ColorTable`]).
use crate::device::profile::{DeviceProfile, DriverWorkaround};
use crate::lower::arith::legal::{FloatFmt, Form, Held};
use crate::lower::arith::ops::{fsplat, splat, ty};
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, SyntheticBinding};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{GlobalId, Value};
use crate::spirv::ir::{
natural_layout, BinOp, ConstBits, Constant, ConvOp, GlslOp, LayoutRule, MemAccess,
StorageClass, Type,
};
use crate::spirv::ir::{BinOp, ConstBits, Constant, MemAccess, StorageClass, Type};
/// The decode step of every byte `b`: Metal's `unpack_unorm4x8_srgb_to_float` answers `k / 4095`
/// (correctly rounded) for `k = SRGB_DECODE_STEPS[b]`, which is `round(decode(b / 255) * 4095)`
@@ -88,270 +72,6 @@ pub(crate) const SRGB_ENCODE_FIRST: [u16; 256] = [
4041, 4077,
];
/// The linear value of every sRGB byte `b`: the `f32` nearest `decode(b / 255)` for the sRGB
/// transfer `decode(c) = c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055)^2.4`, as bits. A
/// fragment function that writes a float to an sRGB attachment writes the value of the byte
/// Metal stores (`color_write`): each is within `5e-6` of a step of its byte's center, so a
/// device's encode stores that byte, and Metal's twelve-bit table encodes each to its own byte too.
const SRGB_LINEAR: [u32; 256] = [
0x0000_0000,
0x399F_22B4,
0x3A1F_22B4,
0x3A6E_B40E,
0x3A9F_22B4,
0x3AC6_EB61,
0x3AEE_B40E,
0x3B0B_3E5D,
0x3B1F_22B4,
0x3B33_070A,
0x3B46_EB61,
0x3B5B_518E,
0x3B70_F18F,
0x3B83_E1C6,
0x3B8F_E616,
0x3B9C_87FD,
0x3BA9_C9B6,
0x3BB7_AD6F,
0x3BC6_354A,
0x3BD5_6360,
0x3BE5_39C1,
0x3BF5_BA71,
0x3C03_73B6,
0x3C0C_6153,
0x3C15_A705,
0x3C1F_45BE,
0x3C29_3E6B,
0x3C33_91F7,
0x3C3E_4149,
0x3C49_4D44,
0x3C54_B6C9,
0x3C60_7EB4,
0x3C6C_A5DF,
0x3C79_2D22,
0x3C83_0AA9,
0x3C89_AF9F,
0x3C90_85DC,
0x3C97_8DC6,
0x3C9E_C7C2,
0x3CA6_3433,
0x3CAD_D37D,
0x3CB5_A602,
0x3CBD_AC21,
0x3CC5_E63A,
0x3CCE_54AC,
0x3CD6_F7D5,
0x3CDF_D010,
0x3CE8_DDBA,
0x3CF2_212D,
0x3CFB_9AC3,
0x3D02_A56A,
0x3D07_98DD,
0x3D0C_A7E6,
0x3D11_D2AF,
0x3D17_1964,
0x3D1C_7C30,
0x3D21_FB3C,
0x3D27_96B2,
0x3D2D_4EBB,
0x3D33_2381,
0x3D39_152B,
0x3D3F_23E4,
0x3D45_4FD2,
0x3D4B_991D,
0x3D51_FFEC,
0x3D58_8468,
0x3D5F_26B6,
0x3D65_E6FD,
0x3D6C_C563,
0x3D73_C20E,
0x3D7A_DD24,
0x3D81_0B65,
0x3D84_B793,
0x3D88_732E,
0x3D8C_3E48,
0x3D90_18F4,
0x3D94_0344,
0x3D97_FD49,
0x3D9C_0715,
0x3DA0_20BA,
0x3DA4_4A4A,
0x3DA8_83D6,
0x3DAC_CD6F,
0x3DB1_2727,
0x3DB5_910F,
0x3DBA_0B38,
0x3DBE_95B3,
0x3DC3_3090,
0x3DC7_DBE0,
0x3DCC_97B4,
0x3DD1_641D,
0x3DD6_412B,
0x3DDB_2EEE,
0x3DE0_2D76,
0x3DE5_3CD4,
0x3DEA_5D18,
0x3DEF_8E51,
0x3DF4_D090,
0x3DFA_23E5,
0x3DFF_885E,
0x3E02_7F06,
0x3E05_427F,
0x3E08_0EA2,
0x3E0A_E377,
0x3E0D_C104,
0x3E10_A753,
0x3E13_966A,
0x3E16_8E51,
0x3E19_8F0F,
0x3E1C_98AC,
0x3E1F_AB30,
0x3E22_C6A1,
0x3E25_EB07,
0x3E29_186A,
0x3E2C_4ED0,
0x3E2F_8E42,
0x3E32_D6C5,
0x3E36_2862,
0x3E39_831F,
0x3E3C_E703,
0x3E40_5417,
0x3E43_CA60,
0x3E47_49E6,
0x3E4A_D2AF,
0x3E4E_64C3,
0x3E52_0029,
0x3E55_A4E7,
0x3E59_5305,
0x3E5D_0A89,
0x3E60_CB7A,
0x3E64_95DF,
0x3E68_69BE,
0x3E6C_471F,
0x3E70_2E07,
0x3E74_1E7E,
0x3E78_188B,
0x3E7C_1C33,
0x3E80_14BF,
0x3E82_2039,
0x3E84_308B,
0x3E86_45B8,
0x3E88_5FC3,
0x3E8A_7EB0,
0x3E8C_A281,
0x3E8E_CB3B,
0x3E90_F8DF,
0x3E93_2B72,
0x3E95_62F6,
0x3E97_9F6F,
0x3E99_E0E0,
0x3E9C_274C,
0x3E9E_72B6,
0x3EA0_C321,
0x3EA3_1890,
0x3EA5_7307,
0x3EA7_D288,
0x3EAA_3716,
0x3EAC_A0B6,
0x3EAF_0F68,
0x3EB1_8332,
0x3EB3_FC15,
0x3EB6_7A14,
0x3EB8_FD34,
0x3EBB_8576,
0x3EBE_12DE,
0x3EC0_A56E,
0x3EC3_3D2A,
0x3EC5_DA14,
0x3EC8_7C30,
0x3ECB_2380,
0x3ECD_D008,
0x3ED0_81CA,
0x3ED3_38C9,
0x3ED5_F508,
0x3ED8_B68A,
0x3EDB_7D52,
0x3EDE_4963,
0x3EE1_1ABF,
0x3EE3_F169,
0x3EE6_CD65,
0x3EE9_AEB5,
0x3EEC_955B,
0x3EEF_815C,
0x3EF2_72B8,
0x3EF5_6974,
0x3EF8_6593,
0x3EFB_6716,
0x3EFE_6E00,
0x3F00_BD2B,
0x3F02_460C,
0x3F03_D1A5,
0x3F05_5FF7,
0x3F06_F104,
0x3F08_84CD,
0x3F0A_1B54,
0x3F0B_B499,
0x3F0D_509F,
0x3F0E_EF65,
0x3F10_90EF,
0x3F12_353D,
0x3F13_DC50,
0x3F15_862A,
0x3F17_32CC,
0x3F18_E237,
0x3F1A_946E,
0x3F1C_4970,
0x3F1E_0140,
0x3F1F_BBDE,
0x3F21_794D,
0x3F23_398C,
0x3F24_FC9F,
0x3F26_C285,
0x3F28_8B41,
0x3F2A_56D2,
0x3F2C_253C,
0x3F2D_F67F,
0x3F2F_CA9C,
0x3F31_A194,
0x3F33_7B6A,
0x3F35_581D,
0x3F37_37B0,
0x3F39_1A24,
0x3F3A_FF7A,
0x3F3C_E7B2,
0x3F3E_D2CF,
0x3F40_C0D2,
0x3F42_B1BC,
0x3F44_A58E,
0x3F46_9C49,
0x3F48_95EF,
0x3F4A_9280,
0x3F4C_91FF,
0x3F4E_946C,
0x3F50_99C9,
0x3F52_A216,
0x3F54_AD56,
0x3F56_BB88,
0x3F58_CCAF,
0x3F5A_E0CC,
0x3F5C_F7DF,
0x3F5F_11EA,
0x3F61_2EEF,
0x3F63_4EEE,
0x3F65_71E9,
0x3F67_97E0,
0x3F69_C0D5,
0x3F6B_ECCA,
0x3F6E_1BBF,
0x3F70_4DB5,
0x3F72_82AE,
0x3F74_BAAB,
0x3F76_F5AE,
0x3F79_33B6,
0x3F7B_74C6,
0x3F7D_B8DE,
0x3F80_0000,
];
/// An upper estimate of the SPIR-V words of the table (its 256 constants, the composite, and the
/// variable), charged to every use.
pub const TABLE_WORDS: u32 = 256 * 4 + 262 + 8;
@@ -360,17 +80,6 @@ pub const TABLE_WORDS: u32 = 256 * 4 + 262 + 8;
/// instructions) besides the index.
pub const SEARCH_WORDS: u32 = 8 * 6 * 6;
/// The estimate of the sRGB byte of an encode index `i >= 13` ([`color_linear`]): a quartic in
/// `t = sqrt(i / 4095)`, its coefficients highest power first, fitted to Metal's bytes and raised
/// by one, so that it lies between `b + 1/3` and `b + 5/3` for Metal's byte `b`, in `f32` with or
/// without fused steps (`srgb_estimates_lie_a_byte_above_metals`).
pub(crate) const ENCODE_ESTIMATE: [f32; 5] =
[-76.24396, 209.02275, -236.77495, 368.16998, -8.362507];
/// The estimate's slope below index 13, where the transfer is linear (`x < 0.0031308`, index
/// 12.82): `12.92 * 255 / 4095`. The estimate there is `i` times it plus one.
pub(crate) const ENCODE_LINEAR: f32 = 0.8045421;
/// An upper estimate of the SPIR-V words of one decode's step read (an access chain, a load,
/// and a mask) besides the division.
pub const STEP_WORDS: u32 = 3 * 6;
@@ -405,114 +114,6 @@ pub fn declare(mb: &mut ModuleBuilder) -> BResult<GlobalId> {
mb.plain_global(StorageClass::Private, arr, Some(init))
}
/// An upper estimate of the SPIR-V words of the color table's declaration
/// ([`declare_color_table`]): the vector, array, block and pointer types, the length, the
/// variable, and their decorations, charged once per module.
pub const COLOR_TABLE_WORDS: u32 = 64;
/// An upper estimate of the SPIR-V words of one sRGB channel's estimate, read and choice
/// ([`color_linear`]) besides the index: about 30 instructions and 12 constants.
pub const COLOR_WORDS: u32 = 42 * 6;
/// The buffer a fragment function's color table lives in, by the device's cost of its reads: every
/// lane of a subgroup reads the entry of its own channel's byte, so the reads of one instruction go
/// to many addresses.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ColorTable {
/// A read-only storage buffer, `StorageBuffer { uvec4[256] }`: the cheaper on NVIDIA's GPUs
/// (the RTX 3090 and the RTX 5080 Laptop GPU drew such writes in 3.5 to 8.6 times the time
/// from a uniform buffer) and on lavapipe's 256-bit vectors, and as cheap as a uniform buffer
/// on RADV.
Storage,
/// A uniform buffer, `Uniform { uvec4[256] }` (std140), where the driver reads one at
/// different addresses faster (`DriverWorkaround::UniformReadsOutpaceStorageReads`).
Uniform,
}
impl ColorTable {
/// The color table's buffer on `profile`.
pub fn of(profile: &DeviceProfile) -> ColorTable {
if profile
.fields()
.workarounds
.contains(&DriverWorkaround::UniformReadsOutpaceStorageReads)
{
ColorTable::Uniform
} else {
ColorTable::Storage
}
}
}
/// The binding symbol of `stage`'s color table.
pub fn color_table_symbol(stage: Stage) -> ResourceSlot {
ResourceSlot {
stage,
kind: ResourceKind::Synthetic(SyntheticBinding::ColorWriteTable),
index: 0,
}
}
/// The color table's entries, byte `b` from 0: `(first, linear, prev, 0)`, `first` the byte's
/// first encode index (`SRGB_ENCODE_FIRST`), `linear` its linear value's bits (`SRGB_LINEAR`)
/// and `prev` byte `b - 1`'s (0 for byte 0, whose entry no write reads).
fn entries() -> impl Iterator<Item = [u32; 4]> {
let prev = std::iter::once(0).chain(SRGB_LINEAR);
SRGB_ENCODE_FIRST
.iter()
.zip(SRGB_LINEAR)
.zip(prev)
.map(|((first, linear), prev)| [u32::from(*first), linear, prev, 0])
}
/// The bytes of the color table a fragment function that writes a float to an sRGB color
/// attachment reads (`WriteSource::ColorWriteTable`): 4096 bytes, 256 little-endian `uvec4`
/// entries, entry `b` holding sRGB byte `b`'s first index in Metal's twelve-bit encode table, the
/// bits of the `f32` nearest its linear value, and those of byte `b - 1`'s linear value. The binder
/// binds a buffer holding exactly these bytes, whole, as the binding's descriptor type says (a
/// uniform or a storage buffer); they are the same for every pipeline and device.
pub fn color_write_table() -> &'static [u8] {
static TABLE: std::sync::LazyLock<Vec<u8>> = std::sync::LazyLock::new(|| {
entries()
.flat_map(|e| e.into_iter().flat_map(u32::to_le_bytes))
.collect()
});
&TABLE
}
/// Declare `stage`'s color table in the buffer `class` names: a block of one `uvec4[256]`
/// member at the table's binding symbol ([`color_table_symbol`]).
pub fn declare_color_table(
mb: &mut ModuleBuilder,
stage: Stage,
class: ColorTable,
) -> BResult<GlobalId> {
let u32_ = mb.ty(Type::Int {
width: 32,
signed: false,
})?;
let v4 = mb.ty(Type::Vector { elem: u32_, len: 4 })?;
let len = mb.constant(Constant::Scalar {
ty: u32_,
bits: ConstBits(256),
})?;
let arr = mb.ty(Type::Array {
elem: v4,
len,
stride: Some(16),
})?;
let (storage, rule) = match class {
ColorTable::Uniform => (StorageClass::Uniform, LayoutRule::Std140),
ColorTable::Storage => (StorageClass::StorageBuffer, LayoutRule::Std430),
};
let layout = natural_layout(mb.types(), rule, true, &[arr])?;
let block = mb.ty(Type::Struct {
members: [arr].into(),
layout: Some(layout),
})?;
mb.resource(color_table_symbol(stage), storage, block)
}
/// Word `i` (a `u32` scalar below 256) of `table`.
fn word(fb: &mut FunctionBuilder<'_>, table: GlobalId, i: Value) -> BResult<Value> {
let base = fb.module().global_value(table)?;
@@ -553,56 +154,3 @@ pub fn search(fb: &mut FunctionBuilder<'_>, table: GlobalId, i: Value) -> BResul
}
b.map_or_else(|| k(fb, 0), Ok)
}
/// The linear value (an `f32`) of the sRGB byte Metal's encode gives encode index `i` (a `u32`
/// scalar below 4096: the exact product of the clamped linear channel and 4095, rounded to
/// nearest even), by one read of the color table `table` ([`declare_color_table`]): the estimate
/// `e` ([`ENCODE_ESTIMATE`], [`ENCODE_LINEAR`]) lies between `b + 1/3` and `b + 5/3` for Metal's
/// byte `b`, so `b0 = floor(e)`, clamped to `[1, 255]`, is `b` or `b + 1`, and the byte is `b0`
/// less one exactly where `i` is below `b0`'s first index: entry `b0`'s linear value, else its
/// predecessor's. Its error budget is a third of a byte either side, far above an `f32`
/// evaluation's and a device square root's, so the device's precision cannot move the byte.
pub fn color_linear(fb: &mut FunctionBuilder<'_>, table: GlobalId, i: Value) -> BResult<Value> {
let f = Form {
held: Held::Float(FloatFmt::F32),
lanes: 1,
};
let u = f.with(Held::Int {
bits: 32,
container: 32,
});
let ft = ty(fb, f)?;
let ut = ty(fb, u)?;
let x = fb.convert(ConvOp::ConvertUToF, i, ft)?;
let step = fsplat(fb, f, f64::from(1.0f32 / 4095.0))?;
let c = fb.binary(BinOp::FMul, x, step)?;
let t = fb.glsl(GlslOp::Sqrt, &[c])?;
let [lead, rest @ ..] = ENCODE_ESTIMATE;
let mut e = fsplat(fb, f, f64::from(lead))?;
for a in rest {
let a = fsplat(fb, f, f64::from(a))?;
let m = fb.binary(BinOp::FMul, e, t)?;
e = fb.binary(BinOp::FAdd, m, a)?;
}
let slope = fsplat(fb, f, f64::from(ENCODE_LINEAR))?;
let one = fsplat(fb, f, 1.0)?;
let linear = fb.binary(BinOp::FMul, x, slope)?;
let linear = fb.binary(BinOp::FAdd, linear, one)?;
let knee = fsplat(fb, f, 13.0)?;
let below_knee = fb.binary(BinOp::FOrdLessThan, x, knee)?;
let e = fb.select(below_knee, linear, e)?;
let b0 = fb.convert(ConvOp::ConvertFToU, e, ut)?;
let lo = splat(fb, u, 1)?;
let hi = splat(fb, u, 255)?;
let b0 = fb.glsl(GlslOp::UClamp, &[b0, lo, hi])?;
let base = fb.module().global_value(table)?;
let member = splat(fb, u, 0)?;
let p = fb.access_chain(base, &[member, b0])?;
let entry = fb.load(p, MemAccess::default())?;
let first = fb.composite_extract(entry, &[0])?;
let own = fb.composite_extract(entry, &[1])?;
let prev = fb.composite_extract(entry, &[2])?;
let below = fb.binary(BinOp::ULessThan, i, first)?;
let bits = fb.select(below, prev, own)?;
fb.convert(ConvOp::Bitcast, bits, ft)
}
@@ -560,13 +560,6 @@ fn dispatch_module(
address: None,
bytes: input.iter().flat_map(|w| w.to_le_bytes()).collect(),
},
// The color table a kernel that rounds an sRGB channel declares, bound as the binder
// binds it.
Buffer {
slot: Some(super::srgb::color_table_symbol(Stage::Kernel)),
address: None,
bytes: super::srgb::color_write_table().to_vec(),
},
],
push: Vec::new(),
spec: Default::default(),
@@ -4110,7 +4103,6 @@ mod blend32;
mod blend8;
mod blend_packed;
mod color_write;
mod depth16;
mod divide;
mod fast;
mod float_texel;
@@ -4119,7 +4111,6 @@ mod half_texel;
mod libm;
mod libm_exp;
mod narrow;
mod norm_write;
mod round_texel;
mod snapshot_codes;
mod specials;
@@ -316,7 +316,7 @@ fn a_half_s_code_is_metals() {
"a half lane's code by the general rule",
&[f4],
f4,
&|fb, x| crate::lower::arith::color_write::round(fb, f4, x[0], &[unorm; 4], None),
&|fb, x| crate::lower::arith::color_write::round(fb, f4, x[0], &[unorm; 4]),
&cases,
&reference,
true,
@@ -1,17 +1,15 @@
//! A fragment function's float color output rounded to the code Metal stores
//! (`color_write::round`), on the interpreter, against the rules probes measured on an Apple M3 Max
//! and an M4 (`runtime_lane::color_writes` holds the same rules).
//! A float rounded to the code Metal stores in a color channel (`color_write::round`), on the
//! interpreter, against the rules probes measured on an Apple M3 Max and an M4
//! (`runtime_lane::color_writes` holds the same rules).
//!
//! Each case writes one value to every lane of a four-lane output whose lanes take different
//! rules, so every rule runs beside the others. The reference is the value each rule writes:
//! `c` times the `f32` nearest `1 / m` for Metal's unorm or snorm code `c`, the linear value of
//! Metal's sRGB byte, and the small float Metal stores, widened. A further check asserts that a device
//! which rounds the `f32` product to nearest (every Vulkan driver measured, ties aside) stores
//! each such value as its code.
//! `c` times the `f32` nearest `1 / m` for Metal's unorm code `c`, and the small float Metal
//! stores, widened. A further check asserts that a device which rounds the `f32` product to
//! nearest (every Vulkan driver measured, ties aside) stores each such value as its code.
use super::*;
use crate::lower::arith::color_write;
use crate::lower::arith::srgb::{self, ColorTable};
use crate::pipeline::lower_inputs::ChannelWrite;
/// Metal's code of `x` in a unorm channel of maximum `m`: NaN 0, clamped to `[0, 1]`, the exact
@@ -27,44 +25,6 @@ fn exact_round(x: f64, m: u32) -> u32 {
(x * f64::from(m)).round_ties_even() as u32
}
/// Metal's code of `x` in a snorm channel of maximum `m` (two's complement as `i32`).
fn snorm_code(x: f32, m: u32, blended: bool) -> i32 {
if x.is_nan() {
return if blended { -(m as i32) } else { 0 };
}
let c = exact_round(f64::from(x.abs().min(1.0)), m) as i32;
if x < 0.0 {
-c
} else {
c
}
}
/// The sRGB byte Metal stores for `x`: its twelve-bit index (the exact product with 4095), and
/// the byte the MSL transfer with the exponent `0.41666` gives that index, which reproduces all
/// 4096 of Metal's (`srgb_conversions_answer_with_metals_tables`).
fn srgb_byte(x: f32) -> u32 {
let i = unorm_code(x, 4095);
let c = f64::from(i) / 4095.0;
let v = if c < 0.0031308 {
12.92 * c
} else {
1.055 * c.powf(0.41666) - 0.055
};
(255.0 * v).round_ties_even() as u32
}
/// The `f32` nearest the linear value of sRGB byte `b`.
fn srgb_linear(b: u32) -> f32 {
let c = f64::from(b) / 255.0;
let v = if c <= 0.04045 {
c / 12.92
} else {
((c + 0.055) / 1.055).powf(2.4)
};
v as f32
}
/// Metal's code of `x` in a float channel of a five-bit exponent (bias 15) and `man` fraction
/// bits (a sign bit above where `signed`): rounded toward zero, a finite value past the largest
/// to the largest, an infinity kept, a NaN the quiet NaN, a negative value 0 where unsigned.
@@ -119,16 +79,6 @@ fn small_float_nearest_code(x: f32, man: u32, signed: bool) -> u32 {
small_float_code(v, man, signed)
}
/// `x` rounded to a half to nearest even, widened (a NaN stays a NaN).
fn half_nearest(x: f32) -> f32 {
let c = small_float_nearest_code(x, 10, true);
if x.is_nan() {
x
} else {
small_float_value(c, 10, true) as f32
}
}
/// The value of code `c` of a float channel as [`small_float_code`] describes it (not a NaN).
fn small_float_value(c: u32, man: u32, signed: bool) -> f64 {
let negative = signed && (c >> (man + 5)) & 1 == 1;
@@ -160,23 +110,6 @@ fn written(rule: Option<ChannelWrite>, x: f32) -> u64 {
let m = (1u32 << bits) - 1;
code_value(unorm_code(x, m), m).to_bits()
}
Some(ChannelWrite::Snorm { bits, blended }) => {
let m = (1u32 << (bits - 1)) - 1;
let c = snorm_code(x, m, blended);
let q = code_value(c.unsigned_abs(), m);
if c < 0 || (c == 0 && x < 0.0) {
(-q).to_bits()
} else {
q.to_bits()
}
}
Some(ChannelWrite::Srgb) => srgb_linear(srgb_byte(x)).to_bits(),
// A selected channel writes by the rule its code selects: no reference of its own.
Some(ChannelWrite::Selected) => unreachable!("a selected channel's rule is its code's"),
Some(ChannelWrite::HalfUnorm { bits }) => {
let m = (1u32 << bits) - 1;
code_value(unorm_code(half_nearest(x), m), m).to_bits()
}
Some(
rule @ (ChannelWrite::FloatTowardZero { mantissa, signed }
| ChannelWrite::FloatNearestEven { mantissa, signed }),
@@ -192,16 +125,16 @@ fn written(rule: Option<ChannelWrite>, x: f32) -> u64 {
(small_float_value(c, man, signed) as f32).to_bits()
}
}
Some(rule) => unreachable!("no reference of {rule:?}: `round` takes none"),
};
u64::from(bits)
}
/// The values beside each code and each tie of a channel of maximum `m` (every `step`-th),
/// `n` `f32` steps either side, over `[lo, 1]`.
fn around_codes(m: u32, signed: bool, step: usize, n: u32) -> Vec<f32> {
let lo = if signed { -(m as i64) } else { 0 };
/// `n` `f32` steps either side, over `[0, 1]`.
fn around_codes(m: u32, step: usize, n: u32) -> Vec<f32> {
let mut out = Vec::new();
for k in (lo..=i64::from(m)).step_by(step) {
for k in (0..=m).step_by(step) {
for c in [k as f64, k as f64 + 0.5] {
let x = (c / f64::from(m)) as f32;
for d in 0..=n {
@@ -297,27 +230,7 @@ fn small_float_values(man: u32) -> Vec<f32> {
out
}
/// The sRGB grid: each twelve-bit index's tie with two `f32` steps either side, and each byte's
/// linear value.
fn srgb_values() -> Vec<f32> {
let mut out = Vec::new();
for i in 0..4095u32 {
let t = ((f64::from(i) + 0.5) / 4095.0) as f32;
for d in 0..=2 {
out.push(f32::from_bits(t.to_bits() + d));
out.push(f32::from_bits(t.to_bits() - d));
}
}
out.extend((0..256).map(srgb_linear));
out
}
fn run_rules(what: &str, rules: [Option<ChannelWrite>; 4], values: &[f32]) {
run_rules_in(what, rules, values, ColorTable::Uniform);
}
/// [`run_rules`] with the color table in the buffer `class` names.
fn run_rules_in(what: &str, rules: [Option<ChannelWrite>; 4], values: &[f32], class: ColorTable) {
let f = vec(float(32), 4);
let cases: Vec<Case> = values
.iter()
@@ -327,10 +240,7 @@ fn run_rules_in(what: &str, rules: [Option<ChannelWrite>; 4], values: &[f32], cl
what,
&[f],
f,
&|fb, x| {
let table = srgb::declare_color_table(fb.module(), Stage::Kernel, class)?;
color_write::round(fb, f, x[0], &rules, Some(table))
},
&|fb, x| color_write::round(fb, f, x[0], &rules),
&cases,
&|c| {
let x = f32::from_bits(c[0][0] as u32);
@@ -340,10 +250,6 @@ fn run_rules_in(what: &str, rules: [Option<ChannelWrite>; 4], values: &[f32], cl
);
}
/// Every unorm and snorm code's value written lies within `2^-7` of the code once multiplied
/// by its maximum, exactly and as an `f32` product, so a device that rounds that product to
/// nearest stores the code, whatever it does at ties, and so does Metal; and the linear value of
/// every sRGB byte is that byte's in Metal's encode.
/// A render state's half-float channel under `textureWriteRoundingMode` 2 rounds to nearest even
/// (`color_writes::HALF_NEAREST`): the consumer's spot values on an M3 Max and our probe's
/// on an M4 (1 + 3 * 2^-12 to `0x3C01`, the tie 1 + 3 * 2^-11 to `0x3C02`, 65519 to `0x7BFF`, from
@@ -400,6 +306,9 @@ fn nearest_even_halves_round_to_mode_twos_codes() {
}
}
/// Every unorm code's value written lies within `2^-7` of the code once multiplied by its
/// maximum, exactly and as an `f32` product, so a device that rounds that product to nearest
/// stores the code, whatever it does at ties, and so does Metal.
#[test]
fn written_values_store_their_codes() {
for m in [1u32, 3, 15, 31, 63, 255, 1023, 65535, 127, 32767] {
@@ -422,204 +331,24 @@ fn written_values_store_their_codes() {
);
}
}
for b in 0..256 {
assert_eq!(srgb_byte(srgb_linear(b)), b, "sRGB byte {b}");
}
}
#[test]
fn eight_bit_channels_round_to_metals_codes() {
let mut values = around_codes(255, true, 1, 2);
values.extend(around_codes(255, false, 1, 2));
let mut values = around_codes(255, 1, 2);
values.extend(specials());
let snorm = |blended| Some(ChannelWrite::Snorm { bits: 8, blended });
run_rules(
"unorm8, snorm8, blended snorm8, device",
"unorm8, device, none, unorm8",
[
Some(ChannelWrite::Unorm { bits: 8 }),
snorm(false),
snorm(true),
Some(ChannelWrite::Device),
None,
Some(ChannelWrite::Unorm { bits: 8 }),
],
&values,
);
}
#[test]
fn wide_and_packed_channels_round_to_metals_codes() {
let mut values = around_codes(65535, false, 61, 2);
values.extend(around_codes(32767, true, 37, 2));
values.extend(around_codes(1023, false, 1, 2));
values.extend(around_codes(3, false, 1, 2));
values.extend(specials());
run_rules(
"unorm16, snorm16, unorm10, unorm2",
[
Some(ChannelWrite::Unorm { bits: 16 }),
Some(ChannelWrite::Snorm {
bits: 16,
blended: false,
}),
Some(ChannelWrite::Unorm { bits: 10 }),
Some(ChannelWrite::Unorm { bits: 2 }),
],
&values,
);
}
/// The packed formats' narrow channels (`A1BGR5Unorm`'s alpha, `ABGR4Unorm`'s, `B5G6R5Unorm`'s)
/// and the narrowest snorm channel: the exact product's rounding for every `k` the formats take.
#[test]
fn narrow_channels_round_to_metals_codes() {
let mut values = Vec::new();
for m in [1, 15, 31, 63] {
values.extend(around_codes(m, false, 1, 3));
}
values.extend(around_codes(1, true, 1, 3));
values.extend(specials());
run_rules(
"unorm1, unorm4, unorm5, unorm6, snorm2",
[
Some(ChannelWrite::Unorm { bits: 1 }),
Some(ChannelWrite::Unorm { bits: 4 }),
Some(ChannelWrite::Unorm { bits: 6 }),
Some(ChannelWrite::Snorm {
bits: 2,
blended: false,
}),
],
&values,
);
run_rules(
"unorm5",
[Some(ChannelWrite::Unorm { bits: 5 }), None, None, None],
&values,
);
}
/// The packed 16-bit formats' channels (`ChannelWrite::HalfUnorm`) round the value to a half
/// first, then as unorm channels: our probe's spot values on an M3 Max (`0x3C842FFF`, a
/// half below 1/62, to 5-bit code 0; `0x3D463000` to 2; `0x3EFFFFFF`, whose half is 0.5, to 16
/// of 31 and 32 of 63; 0.5 to 1-bit code 0; `0x3D089000` to 4-bit code 0; `0x3C021000` to 6-bit
/// code 0), then on the interpreter the values beside every code and tie of 1, 4, 5 and 6 bits,
/// the halves either side of each tie, and the specials, beside lanes of the other widths.
#[test]
fn packed_channels_round_through_a_half() {
let code = |x: u32, bits: u32| unorm_code(half_nearest(f32::from_bits(x)), (1 << bits) - 1);
assert_eq!(code(0x3C84_2FFF, 5), 0);
assert_eq!(code(0x3D46_3000, 5), 2);
assert_eq!(code(0x3EFF_FFFF, 5), 16);
assert_eq!(code(0x3EFF_FFFF, 6), 32);
assert_eq!(code(0.5f32.to_bits(), 1), 0);
assert_eq!(code(0x3D08_9000, 4), 0);
assert_eq!(code(0x3C02_1000, 6), 0);
let mut values = Vec::new();
for m in [1u32, 15, 31, 63] {
values.extend(around_codes(m, false, 1, 3));
// The halves nearest each tie and either side of it, and the midpoints between them
// (a half's step is `0x2000` in the `f32` bits there), three `f32` steps either side.
for k in 0..m {
let tie = ((f64::from(k) + 0.5) / f64::from(m)) as f32;
let h = half_nearest(tie).to_bits();
for at in (h - 0x2000..=h + 0x2000).step_by(0x1000) {
values.extend((0..3).flat_map(|d| [at + d, at - d]).map(f32::from_bits));
}
}
}
values.extend(specials());
let packed = |bits| Some(ChannelWrite::HalfUnorm { bits });
run_rules(
"half unorm 1, 4, 5, 6",
[packed(1), packed(4), packed(5), packed(6)],
&values,
);
}
/// The sRGB byte's estimate ([`srgb::color_linear`]) lies between `b + 1/3` and `b + 5/3` for
/// Metal's byte `b` of every encode index, evaluated in `f32` step by step and with every step
/// fused, so `floor` of it, clamped to `[1, 255]`, less one where the index is below that byte's
/// first index, is `b`.
#[test]
fn srgb_estimates_lie_a_byte_above_metals() {
let first = |b: u32| u32::from(srgb::SRGB_ENCODE_FIRST[b as usize]);
for fused in [false, true] {
let step = |a: f32, b: f32, c: f32| if fused { a.mul_add(b, c) } else { a * b + c };
for i in 0..4096u32 {
let metal = (0..256).rev().find(|&b| first(b) <= i).unwrap_or(0);
let x = i as f32;
let e = if i < 13 {
step(x, srgb::ENCODE_LINEAR, 1.0)
} else {
let t = (x * (1.0f32 / 4095.0)).sqrt();
let [lead, rest @ ..] = srgb::ENCODE_ESTIMATE;
rest.iter().fold(lead, |e, &a| step(e, t, a))
};
let above = f64::from(e) - f64::from(metal);
assert!(
(0.333..=1.667).contains(&above),
"index {i} (fused {fused}): estimate {e}, Metal's byte {metal}"
);
let b0 = (e as u32).clamp(1, 255);
let b = if i < first(b0) { b0 - 1 } else { b0 };
assert_eq!(b, metal, "index {i} (fused {fused})");
}
}
}
/// An sRGB channel writes Metal's byte's linear value from the color table in either buffer, beside
/// an 8-bit alpha and a half.
#[test]
fn srgb_and_half_channels_take_metals_values() {
let mut values = srgb_values();
values.extend(half_values());
values.extend(specials());
for class in [ColorTable::Uniform, ColorTable::Storage] {
run_rules_in(
&format!("sRGB, sRGB alpha, half, none ({class:?})"),
[
Some(ChannelWrite::Srgb),
Some(ChannelWrite::Unorm { bits: 8 }),
Some(ChannelWrite::FloatTowardZero {
mantissa: 10,
signed: true,
}),
None,
],
&values,
class,
);
}
}
/// The color table's bytes are 256 little-endian `uvec4` entries, entry `b` holding byte `b`'s
/// first encode index, its linear value's bits and byte `b - 1`'s, so the write's choice between
/// the two linear values by the index against the first index is Metal's encode.
#[test]
fn the_color_table_holds_each_bytes_first_index_and_linear_values() {
let table = srgb::color_write_table();
assert_eq!(table.len(), 256 * 16);
let word = |b: usize, k: usize| {
let at = b * 16 + k * 4;
let bytes: [u8; 4] = table[at..at + 4].try_into().expect("word");
u32::from_le_bytes(bytes)
};
for b in 0..256usize {
assert_eq!(
word(b, 0),
u32::from(srgb::SRGB_ENCODE_FIRST[b]),
"byte {b}"
);
assert_eq!(word(b, 1), srgb_linear(b as u32).to_bits(), "byte {b}");
let prev = if b == 0 {
0
} else {
srgb_linear(b as u32 - 1).to_bits()
};
assert_eq!(word(b, 2), prev, "byte {b}");
assert_eq!(word(b, 3), 0, "byte {b}");
}
}
/// `RG11B10Float`'s unsigned 11- and 10-bit floats, beside a half.
#[test]
fn packed_float_channels_round_toward_zero() {
@@ -666,7 +395,7 @@ fn small_float_codes_give_metals_spot_answers() {
/// A scalar output and a half output (held widened) round as their lanes do.
#[test]
fn scalar_and_half_outputs_round() {
let values: Vec<f32> = around_codes(255, false, 1, 1)
let values: Vec<f32> = around_codes(255, 1, 1)
.into_iter()
.chain(specials())
.collect();
@@ -680,7 +409,7 @@ fn scalar_and_half_outputs_round() {
"scalar unorm8",
&[s],
s,
&|fb, x| color_write::round(fb, s, x[0], &rules, None),
&|fb, x| color_write::round(fb, s, x[0], &rules),
&cases,
&|c| Some(vec![written(rules[0], f32::from_bits(c[0][0] as u32))]),
&|g, w| g == w,
@@ -688,24 +417,14 @@ fn scalar_and_half_outputs_round() {
let h = vec(float(16), 2);
let halves: Vec<u64> = (0u64..0x10000).step_by(3).collect();
let cases: Vec<Case> = halves.iter().map(|b| vec![vec![*b, *b]]).collect();
let rules = [
Some(ChannelWrite::Srgb),
Some(ChannelWrite::Snorm {
bits: 8,
blended: false,
}),
None,
None,
];
let unorm8 = Some(ChannelWrite::Unorm { bits: 8 });
let rules = [unorm8, unorm8, None, None];
let out = vec(float(32), 2);
check_accept(
"half sRGB and snorm8",
"half unorm8",
&[h],
out,
&|fb, x| {
let table = srgb::declare_color_table(fb.module(), Stage::Kernel, ColorTable::Uniform)?;
color_write::round(fb, h, x[0], &rules, Some(table))
},
&|fb, x| color_write::round(fb, h, x[0], &rules),
&cases,
&|c| {
let x = f16_to_f64(c[0][0] as u16) as f32;
@@ -715,116 +434,6 @@ fn scalar_and_half_outputs_round() {
);
}
/// A lane written as computed with its NaN chosen (`Lane::NanAs`) passes every other value through
/// unchanged, a zero's sign, the infinities and the denormals included, and writes every NaN of
/// either sign and any payload as the chosen bits; it runs beside a rounded lane and one written as
/// computed.
#[test]
fn nan_only_lanes_choose_the_nan_alone() {
use color_write::Lane;
let f = vec(float(32), 4);
let minus_one = (-1.0f32).to_bits();
let lanes = [
Some(Lane::NanAs(0x7fc0_0000)),
Some(Lane::NanAs(minus_one)),
Some(Lane::Rounded(ChannelWrite::Unorm { bits: 16 })),
None,
];
let nans = [
0x7fc0_0000u32,
0xffc0_0000,
0x7f80_0001,
0xffff_ffff,
0x7fff_ffff,
];
let values: Vec<f32> = specials()
.into_iter()
.chain(nans.iter().map(|&b| f32::from_bits(b)))
.chain(around_codes(65535, false, 4099, 1))
.collect();
let cases: Vec<Case> = values
.iter()
.map(|x| vec![vec![u64::from(x.to_bits()); 4]])
.collect();
check_accept(
"NaN-only lanes",
&[f],
f,
&|fb, x| color_write::write(fb, f, x[0], &lanes, (None, None)),
&cases,
&|c| {
let x = f32::from_bits(c[0][0] as u32);
let nan_as = |bits: u32| u64::from(if x.is_nan() { bits } else { x.to_bits() });
Some(vec![
nan_as(0x7fc0_0000),
nan_as(minus_one),
written(Some(ChannelWrite::Unorm { bits: 16 }), x),
u64::from(x.to_bits()),
])
},
&|g, w| g == w,
);
let rounded = color_write::words(&[Some(ChannelWrite::Unorm { bits: 16 }); 4]);
let chosen = color_write::write_words(&[Some(Lane::NanAs(0x7fc0_0000)); 4]);
assert!(chosen * 8 < rounded, "{chosen} of {rounded}");
}
/// A lane whose rule the draw selects (`Lane::Selected`) writes what the rule its code in the
/// rule word selects writes: the value as computed for no rule (0) and the device's conversion
/// (1), Metal's 8-bit unorm code (2), and a half-float channel's lane (3) as `half` says (rounded
/// toward zero, as computed, or its NaN chosen). Each lane reads its own code (bits `4i` to
/// `4i + 3`): over four words every lane takes every code, beside lanes of the others, across
/// the unorm grid, the half grid (every third of [`half_values`]) and the specials.
#[test]
fn selected_lanes_write_the_rule_their_code_selects() {
use crate::pipeline::color_writes::{HALF, HALF_CODE, UNORM8_CODE};
use color_write::{HalfLane, Lane};
let f = vec(float(32), 4);
let mut values = around_codes(255, false, 1, 1);
values.extend(half_values().into_iter().step_by(3));
values.extend(specials());
let words = [0x3210u32, 0x2103, 0x1032, 0x0321];
let cases: Vec<Case> = values
.iter()
.flat_map(|x| {
words
.iter()
.map(|&w| vec![vec![u64::from(x.to_bits()); 4], vec![u64::from(w)]])
})
.collect();
for half in [
HalfLane::Rounded,
HalfLane::AsComputed,
HalfLane::NanAs(0x7fc0_0000),
] {
let lanes = [Some(Lane::Selected { half }); 4];
check_accept(
&format!("selected lanes, half {half:?}"),
&[f, int(32)],
f,
&|fb, x| color_write::write(fb, f, x[0], &lanes, (None, Some(x[1]))),
&cases,
&|c| {
let x = f32::from_bits(c[0][0] as u32);
let word = c[1][0] as u32;
let lane = |i: u32| match (word >> (4 * i)) & 0xF {
UNORM8_CODE => written(Some(ChannelWrite::Unorm { bits: 8 }), x),
HALF_CODE => match half {
HalfLane::Rounded => written(Some(HALF), x),
HalfLane::AsComputed => u64::from(x.to_bits()),
HalfLane::NanAs(bits) => {
u64::from(if x.is_nan() { bits } else { x.to_bits() })
}
},
_ => u64::from(x.to_bits()),
};
Some((0..4).map(lane).collect())
},
&|g, w| g == w,
);
}
}
/// `color_write::half_bits` writes each half's own bits: every `half` widened (every NaN payload of
/// either sign, the denormals, both zeros and infinities), each value but a NaN through the
/// conversion to 16 bits and each NaN as `nan_codes`' code; a NaN no half widens to (its top ten
@@ -908,7 +517,7 @@ fn word_attachments_store_metals_words() {
use crate::metal::PixelFormat;
let mut values = Vec::new();
for m in [1, 15, 31, 63] {
values.extend(around_codes(m, false, 1, 2));
values.extend(around_codes(m, 1, 2));
}
values.extend(half_values().into_iter().step_by(5));
values.extend(specials());
@@ -1,309 +0,0 @@
//! A `Depth16Unorm` depth as the fragment stage writes Metal's code (`stage_io::depth16`), on the
//! interpreter, against Metal's rule (probes `depth16` and `depthout` on the M3 Max under macOS
//! 27.0.1; `runtime_lane::unorm_depth_bias` draws the measured rows): a depth `d` of `[0, 1]` stores
//! the exact product `65535 d` rounded to nearest, a tie up; a biased fragment adds
//! `slope · m + units`, each operation rounded on its own, bounded by a nonzero clamp from its
//! side, to its depth rounding toward zero, and clamps the sum to `[0, 1]` first. The stage writes
//! code `c` as `c` times the `f32` nearest 1/65535, which a further check shows a device that
//! rounds to nearest, as Vulkan asks, stores as `c`.
use super::*;
use crate::lower::stage_io::depth16::{code_depth, offset_depth, side_bounded};
/// Metal's code of a depth `d` of `[0, 1]`: the product with 65535, exact in `f64`, rounded to
/// nearest, a tie up.
fn metal_code(d: f32) -> u32 {
(f64::from(d) * 65535.0 + 0.5).floor() as u32
}
/// The `f32` the stage writes for code `c`, as bits: `c` times the `f32` nearest 1/65535.
fn written(c: u32) -> u64 {
u64::from((c as f32 * (1.0f32 / 65535.0)).to_bits())
}
/// Depths of `[0, 1]` beside every `step`-th code and its midpoint, `n` `f32` steps either side.
fn around_codes(step: usize, n: u32) -> Vec<f32> {
let mut out = vec![0.0, 1.0, 0.5, f32::MIN_POSITIVE, 1e-40];
for k in (0..=65535u32).step_by(step) {
for c in [f64::from(k), f64::from(k) + 0.5] {
let x = (c / 65535.0) as f32;
for d in 0..=n {
out.extend([
f32::from_bits(x.to_bits().wrapping_add(d)),
f32::from_bits(x.to_bits().wrapping_sub(d)),
]);
}
}
}
out.retain(|x| (0.0..=1.0).contains(x));
out
}
/// Every code's written value converts back to the code: its product with 65535 lies within
/// 2^-7 of it, so a conversion that rounds to nearest stores the code.
#[test]
fn every_code_written_converts_back_to_the_code() {
for c in 0..=65535u32 {
let v = f64::from(f32::from_bits(written(c) as u32));
let off = (v * 65535.0 - f64::from(c)).abs();
assert!(off < 1.0 / 128.0, "code {c}: {off}");
}
}
/// `code_depth` writes Metal's code of each depth beside the codes and their midpoints, 0.5's
/// tie up among them.
#[test]
fn a_depth_is_written_as_metal_s_code() {
let f = float(32);
let cases: Vec<Case> = around_codes(17, 2)
.into_iter()
.map(|x| vec![vec![u64::from(x.to_bits())]])
.collect();
check(
"code_depth",
&[f],
f,
&|fb, xs| code_depth(fb, xs[0]),
&cases,
&|c| Some(vec![written(metal_code(f32v(c[0][0])))]),
false,
);
}
/// Metal's biased depth of `z` at slope `m` under `[units, slope, clamp]`: the offset
/// `slope · m + units` in `f32`, each operation rounded, a nonzero clamp bounding it from its side,
/// added to `z` rounding toward zero, clamped to `[0, 1]`, and its code. `None` where the sum is
/// not exact in `f64` (no case here).
fn metal_biased_code(z: f32, m: f32, [units, slope, clamp]: [f32; 3]) -> Option<u32> {
let offset = slope * m + units;
let offset = if (clamp > 0.0 && offset > clamp) || (clamp < 0.0 && offset < clamp) {
clamp
} else {
offset
};
let exact = f64::from(z) + f64::from(offset);
if exact - f64::from(z) != f64::from(offset) {
return None;
}
let nearest = exact as f32;
let toward_zero = if f64::from(nearest).abs() > exact.abs() {
f32::from_bits(nearest.to_bits() - 1)
} else {
nearest
};
Some(metal_code(toward_zero.clamp(0.0, 1.0)))
}
/// Metal's `[units, slope, clamp]` for constant `c`, slope factor `s` and clamp `k`
/// (`metal::state::depth16_bias`).
fn factors(c: f32, s: f32, k: f32) -> [f32; 3] {
crate::metal::state::depth16_bias(c, s, k)
}
/// The cases of part `part` of `of`: depths beside codes and midpoints (and the midpoints the
/// offsets land the sums on), under constants, slope factors, slopes and clamps a draw takes.
fn biased_cases(part: usize, of: usize) -> Vec<Case> {
let constants = [
-1000.0, -3.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.5, 100.0, 30000.0,
];
let slopes = [0.0, 0.5, -1.0, 2.0, 1000.0];
let ms = [0.0, 1.0 / 4096.0, 1.0 / 1080.0, 0.0123, 0.5];
let clamps = [0.0, 1.0 / 8192.0, -1.0 / 8192.0];
let depths = around_codes(8191, 1);
let mut cases = Vec::new();
for c in constants {
for s in slopes {
for k in clamps {
let [units, slope, clamp] = factors(c, s, k);
for m in ms {
// The depths whose biased sums land beside a code's midpoint.
let offset = slope * m + units;
let landed = depths
.iter()
.map(|&z| (f64::from(z) - f64::from(offset)) as f32);
for z in depths.iter().copied().chain(landed) {
if !(0.0..=1.0).contains(&z) {
continue;
}
let bits = |v: f32| vec![u64::from(v.to_bits())];
cases.push(vec![
bits(z),
bits(m),
bits(units),
bits(slope),
bits(clamp),
]);
}
}
}
}
}
part_of(cases, part, of)
}
/// `offset_depth` writes Metal's code of each biased depth.
fn biased_grid(part: usize, of: usize) {
let f = float(32);
check(
"offset_depth",
&[f, f, f, f, f],
f,
&|fb, xs| offset_depth(fb, xs[0], xs[1], [xs[2], xs[3], xs[4]]),
&biased_cases(part, of),
&|c| {
let v = |i: usize| f32v(c[i][0]);
metal_biased_code(v(0), v(1), [v(2), v(3), v(4)]).map(|code| vec![written(code)])
},
false,
);
}
parts!(biased_grid, 4;
a_biased_depth_is_written_as_metal_s_code_0 = 0,
a_biased_depth_is_written_as_metal_s_code_1 = 1,
a_biased_depth_is_written_as_metal_s_code_2 = 2,
a_biased_depth_is_written_as_metal_s_code_3 = 3,
);
/// The cases of part `part` of `of` whose bias has side `raises` (`metal::state::depth16_bias_side`):
/// depths beside codes and midpoints, 0 and 1 among them, and the depths whose biased sums land
/// beside a midpoint, under constants, slope factors and slopes, and clamps of 0, past the units,
/// at them and short of them on either side.
fn sided_cases(raises: bool, part: usize, of: usize) -> Vec<Case> {
let constants = [
-30000.0, -1000.0, -3.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.5, 100.0, 30000.0,
];
let slopes = [0.0, -0.0, 0.5, -1.0, 2.0, -1000.0, 1000.0];
let ms = [0.0, 1.0 / 4096.0, 1.0 / 1080.0, 0.0123, 0.5, 64.0];
let depths = around_codes(8191, 1);
let mut cases = Vec::new();
for c in constants {
for s in slopes {
let units = factors(c, s, 0.0)[0];
let clamps = [
0.0,
1.0 / 8192.0,
-1.0 / 8192.0,
units,
-units,
units / 2.0,
-units / 2.0,
units * 2.0,
];
for k in clamps {
if crate::metal::state::depth16_bias_side(c, s, k) != Some(raises) {
continue;
}
let [units, slope, clamp] = factors(c, s, k);
for m in ms {
let offset = slope * m + units;
let landed = depths
.iter()
.map(|&z| (f64::from(z) - f64::from(offset)) as f32);
for z in depths.iter().copied().chain(landed) {
if !(0.0..=1.0).contains(&z) {
continue;
}
let bits = |v: f32| vec![u64::from(v.to_bits())];
cases.push(vec![
bits(z),
bits(m),
bits(units),
bits(slope),
bits(clamp),
]);
}
}
}
}
}
part_of(cases, part, of)
}
/// A bias of known side bounds the written depth by `FragCoord.z` on that side
/// (`side_bounded`), which a stage declaring `DepthGreater` or `DepthLess` must: on every case of
/// that side the bound writes Metal's code unchanged, and that code's written value lies on the
/// side of the fragment's depth (the proof in `side_bounded`'s docs, step 3).
fn sided_grid(raises: bool, part: usize, of: usize) {
let f = float(32);
let cases = sided_cases(raises, part, of);
assert!(cases.len() > 1000, "too few cases: {}", cases.len());
check(
"side_bounded",
&[f, f, f, f, f],
f,
&|fb, xs| {
let stored = offset_depth(fb, xs[0], xs[1], [xs[2], xs[3], xs[4]])?;
side_bounded(fb, stored, xs[0], raises)
},
&cases,
&|c| {
let v = |i: usize| f32v(c[i][0]);
let code = metal_biased_code(v(0), v(1), [v(2), v(3), v(4)])?;
let w = f32::from_bits(written(code) as u32);
let z = v(0);
assert!(
if raises { w >= z } else { w <= z },
"code {code} of {z:e} under {:?} writes {w:e}, past the fragment's depth",
[v(1), v(2), v(3), v(4)]
);
Some(vec![written(code)])
},
false,
);
}
fn raising_grid(part: usize, of: usize) {
sided_grid(true, part, of);
}
fn lowering_grid(part: usize, of: usize) {
sided_grid(false, part, of);
}
parts!(raising_grid, 4;
a_raising_bias_bounded_by_the_fragment_s_depth_writes_metal_s_code_0 = 0,
a_raising_bias_bounded_by_the_fragment_s_depth_writes_metal_s_code_1 = 1,
a_raising_bias_bounded_by_the_fragment_s_depth_writes_metal_s_code_2 = 2,
a_raising_bias_bounded_by_the_fragment_s_depth_writes_metal_s_code_3 = 3,
);
parts!(lowering_grid, 4;
a_lowering_bias_bounded_by_the_fragment_s_depth_writes_metal_s_code_0 = 0,
a_lowering_bias_bounded_by_the_fragment_s_depth_writes_metal_s_code_1 = 1,
a_lowering_bias_bounded_by_the_fragment_s_depth_writes_metal_s_code_2 = 2,
a_lowering_bias_bounded_by_the_fragment_s_depth_writes_metal_s_code_3 = 3,
);
/// The sides `metal::state::depth16_bias_side` gives: a bias of units above 0 and a slope factor
/// not below 0 raises the depth, one of units below 0 and a slope factor not above 0 lowers it, a
/// clamp short of the units on their side leaves it unknown, and so do opposite signs and no bias.
#[test]
fn a_bias_has_a_side_only_where_every_triangle_s_depth_takes_it() {
use crate::metal::state::depth16_bias_side as side;
let unit = 1.0 / 65535.0;
assert_eq!(side(0.0, 0.0, 0.0), None);
assert_eq!(side(2.0, 0.0, 0.0), Some(true));
assert_eq!(side(0.0, 1.0, 0.0), Some(true));
assert_eq!(side(0.0, -0.0, 0.0), None);
assert_eq!(side(-0.0, 0.5, 0.0), Some(true));
assert_eq!(side(-2.0, 0.0, 0.0), Some(false));
assert_eq!(side(-0.5, -3.0, 0.0), Some(false));
assert_eq!(side(2.0, -1.0, 0.0), None);
assert_eq!(side(-2.0, 1.0, 0.0), None);
assert_eq!(side(0.0, -1.0, 0.0), None);
// A clamp on the bias's side keeps it only at or past the units (3 of them for 2).
assert_eq!(side(2.0, 0.0, 3.0 * unit), Some(true));
assert_eq!(side(2.0, 0.0, 2.0 * unit), None);
assert_eq!(side(2.0, 0.0, -unit), Some(true));
assert_eq!(side(-2.0, 0.0, -3.0 * unit), Some(false));
assert_eq!(side(-2.0, 0.0, -2.0 * unit), None);
assert_eq!(side(-2.0, 0.0, unit), Some(false));
// Infinite or NaN factors have none; a NaN or infinite clamp bounds nothing.
assert_eq!(side(f32::INFINITY, 0.0, 0.0), None);
assert_eq!(side(1.0, f32::NAN, 0.0), None);
assert_eq!(side(1.0, f32::INFINITY, 0.0), None);
assert_eq!(side(1.0, 0.0, f32::NAN), Some(true));
assert_eq!(side(1.0, 0.0, f32::INFINITY), Some(true));
assert_eq!(side(-1.0, 0.0, f32::NEG_INFINITY), Some(false));
}
@@ -1,248 +0,0 @@
//! Interpreter differential tests of a written `float` texel rounded to the codes Metal stores in
//! a normalized storage texture by the bound format's class (`lower::texture::norm_write`).
//! References are plain Rust: Metal's measured rule, each channel's value clamped
//! to its range (a NaN 0) times its maximum code `m` exactly, rounded to nearest with a tie away
//! from zero, a 1-bit channel 1 only above one half; the value written `c / m` correctly rounded,
//! with the clamped value's sign.
use super::*;
use crate::lower::texture::norm_write;
use crate::metal::texel_format::{texel_format, PackedTexels};
use crate::metal::PixelFormat as P;
fn v4() -> Form {
vec(float(32), 4)
}
/// The routine at the class an input holds.
fn body(fb: &mut FunctionBuilder<'_>, x: &[Value]) -> BResult<Value> {
let r = norm_write::define(fb.module())?;
norm_write::convert(fb, r, x[0], x[1])
}
/// Metal's code of `x` in a channel of maximum code `m` (signed where `signed`), as an `i64`.
fn metal_code(x: f32, m: u32, signed: bool) -> i64 {
let lo = if signed { -1.0 } else { 0.0 };
let v = if x.is_nan() { 0.0 } else { x.clamp(lo, 1.0) };
if m == 1 {
return i64::from(v > 0.5);
}
// The product of a 24-bit significand and a 16-bit integer is exact in `f64`; `round` takes a
// tie away from zero.
(f64::from(v) * f64::from(m)).round() as i64
}
/// The `f32` bits the routine writes for `x` in such a channel: Metal's code over `m`, correctly
/// rounded, with the clamped value's sign (`-0.0` for a negative value whose code is 0).
fn written(x: f32, m: u32, signed: bool) -> u64 {
let lo = if signed { -1.0 } else { 0.0 };
let v = if x.is_nan() { 0.0 } else { x.clamp(lo, 1.0) };
let c = metal_code(x, m, signed);
let q = c.unsigned_abs() as f32 / m as f32;
u64::from(if v < 0.0 { -q } else { q }.to_bits())
}
/// Each lane's maximum code and sign of `pf`'s class: an unpacked family's in every lane, a
/// packed field's own scales.
fn scales(pf: P) -> ([u32; 4], bool) {
let signed = matches!(
pf,
P::R8Snorm | P::RG8Snorm | P::RGBA8Snorm | P::R16Snorm | P::RG16Snorm | P::RGBA16Snorm
);
if let Some(s) = PackedTexels::of(pf).and_then(PackedTexels::scales) {
return (s, signed);
}
let wide = matches!(
pf,
P::R16Unorm | P::RG16Unorm | P::RGBA16Unorm | P::R16Snorm | P::RG16Snorm | P::RGBA16Snorm
);
let m = match (wide, signed) {
(false, false) => 255,
(false, true) => 127,
(true, false) => 65535,
(true, true) => 32767,
};
([m; 4], signed)
}
/// The values beside each code and each tie of a channel of maximum `m` (every `step`-th), two
/// `f32` steps either side, over its range.
fn around_codes(m: u32, signed: bool, step: usize) -> Vec<f32> {
let lo = if signed { -i64::from(m) } else { 0 };
let mut out = Vec::new();
for k in (lo..=i64::from(m)).step_by(step).chain([i64::from(m)]) {
for c in [k as f64, k as f64 + 0.5, k as f64 - 0.5] {
let x = (c / f64::from(m)) as f32;
for d in 0..=2 {
out.push(f32::from_bits(x.to_bits().wrapping_add(d)));
out.push(f32::from_bits(x.to_bits().wrapping_sub(d)));
}
}
}
out
}
fn specials() -> Vec<f32> {
vec![
0.0,
-0.0,
1.0,
-1.0,
0.5,
-0.5,
f32::from_bits(0x3f00_0001),
f32::from_bits(0x3eff_ffff),
1.5,
-1.5,
2.0,
f32::from_bits(1),
f32::from_bits(0x8000_0001),
f32::MIN_POSITIVE,
1e-10,
-1e-10,
f32::INFINITY,
f32::NEG_INFINITY,
f32::NAN,
f32::from_bits(0xFFC0_0001),
f32::from_bits(0x7F80_0001),
]
}
/// Run the routine over `values`, each in every lane, at `class`, against `reference` of each
/// lane's index and value, bit for bit.
fn run(what: &str, class: u32, values: &[f32], reference: &dyn Fn(usize, f32) -> u64) {
let cases: Vec<Case> = values
.iter()
.map(|x| vec![vec![u64::from(x.to_bits()); 4], vec![u64::from(class)]])
.collect();
check_accept(
what,
&[v4(), int(32)],
v4(),
&body,
&cases,
&|c| {
let x = f32::from_bits(c[0][0] as u32);
Some((0..4).map(|i| reference(i, x)).collect())
},
&|g, w| g == w,
);
}
/// Every normalized format's class rounds each channel to Metal's code on its own scale: the 8-
/// and 16-bit unorm and snorm families in every lane, the packed formats' 10:10:10:2, 5:6:5, 4:4:4:4
/// and 5:5:5:1 channels each on its own, a 1-bit alpha's one half to 0.
#[test]
fn a_normalized_write_rounds_each_channel_to_metals_code() {
for pf in [
P::R8Unorm,
P::RGBA8Unorm,
P::BGRA8Unorm,
P::A8Unorm,
P::RGBA8Snorm,
P::RGBA16Unorm,
P::RG16Snorm,
P::RGBA16Snorm,
P::RGB10A2Unorm,
P::BGR10A2Unorm,
P::B5G6R5Unorm,
P::A1BGR5Unorm,
P::ABGR4Unorm,
P::BGR5A1Unorm,
] {
let class = texel_format(pf).0;
let (ms, signed) = scales(pf);
let mut values = specials();
let mut seen = Vec::new();
for m in ms {
if seen.contains(&m) {
continue;
}
seen.push(m);
let step = if m > 1023 { 97 } else { 1 };
values.extend(around_codes(m, signed, step));
}
run(&format!("{pf:?}"), class, &values, &|i, x| {
written(x, ms[i], signed)
});
}
}
/// Every other class writes the texel as computed, a NaN's payload included: the float,
/// half-float and small-float families, an 8-bit sRGB format's (its storage choice encodes it),
/// `ARGB8Unorm`'s field without a family (its storage choice rounds it), a YCbCr format's field
/// and `OTHER`.
#[test]
fn another_class_writes_the_texel_as_computed() {
let mut values = specials();
values.extend(around_codes(255, true, 7));
for pf in [
P::RGBA32Float,
P::RGBA16Float,
P::RG11B10Float,
P::RGBA8UnormSRGB,
P::ARGB8Unorm,
P::Invalid,
] {
let class = texel_format(pf).0;
run(&format!("{pf:?}"), class, &values, &|_, x| {
u64::from(x.to_bits())
});
}
let ycbcr = PackedTexels::YCbCr2048.class().0
| crate::metal::bicubic::BicubicTexels::UNORM
| crate::metal::bicubic::BicubicTexels::EXACT;
run("a YCbCr field", ycbcr, &values, &|_, x| {
u64::from(x.to_bits())
});
}
/// The value written, `c / m` within three `f32` ulps (a device's division is within 2.5 ulps),
/// times `m` lies within `2^-5` of `c`, so a device that rounds the product to nearest stores `c`
/// whatever it does at a tie: every code of every scale the routine takes.
#[test]
fn a_written_code_value_stores_its_code() {
for m in [1u32, 3, 15, 31, 63, 127, 255, 1023, 32767, 65535] {
for c in 0..=m {
let q = c as f32 / m as f32;
for d in -3i32..=3 {
let v = f32::from_bits(q.to_bits().wrapping_add_signed(d));
if c == 0 && d < 0 {
continue;
}
let product = f64::from(v) * f64::from(m);
assert!(
(product - f64::from(c)).abs() < 1.0 / 32.0,
"m {m} code {c}: {v:e} times m is {product}"
);
}
}
}
}
#[test]
fn the_norm_write_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()
};
let without = size(&|_, x| Ok(x[0]));
let defined = size(&|fb, x| {
norm_write::define(fb.module())?;
Ok(x[0])
}) - without;
let called = size(&body) - without - defined;
assert!(
defined as u64 <= norm_write::ROUTINE_WORDS,
"the routine is {defined} words, bound {}",
norm_write::ROUTINE_WORDS
);
assert!(
called <= norm_write::CALL_WORDS as usize,
"a call is {called} words, bound {}",
norm_write::CALL_WORDS
);
eprintln!("norm write routine: {defined} words, a call {called}");
}
-2
View File
@@ -99,7 +99,6 @@ pub const fn shape(f: PushField) -> FieldShape {
// The blend color as the encoder set it, four `f32`s' bits.
PushField::HalfBlendColor => FieldShape::UVec4Array(1),
// A draw's depth bias: its constant, slope and clamp as `f32`s' bits, and a zero word.
PushField::DepthBias => FieldShape::UVec4Array(1),
// Base vertex, base instance.
PushField::BaseVertexInstance => FieldShape::UVec2,
// The draw's vertices per primitive.
@@ -118,7 +117,6 @@ pub const fn shape(f: PushField) -> FieldShape {
PushField::Specialized(_) => FieldShape::U32,
// An in-place YCbCr texture's size, planes and conversion.
PushField::YCbCrInPlace(_) => FieldShape::UVec4Array(2),
PushField::ColorWriteRule(_) => FieldShape::U32,
// The residual is below `min{Storage,Uniform}BufferOffsetAlignment`.
PushField::SlotBindOffset(_) | PushField::VertexBufferStride(_) => FieldShape::U32,
// A texture's mipmap level count, an acceleration structure's instance count, the render
@@ -1,99 +1,94 @@
//! A fragment function's color outputs rounded to the codes Metal stores: which lanes of each
//! output round, from `LoweringInputs::color_writes`, and their emission (`arith::color_write`).
//! A fragment function's color outputs as the device converts them: which conversions each
//! output's channels take, from `LoweringInputs::color_writes`, and the rounding Metal's
//! `textureWriteRoundingMode` asks for (`arith::color_write`).
//!
//! The function records the map it compiled under for each attachment it writes
//! (`StageIo::color_writes`, which link checks against the pipeline's), and rounds each lane
//! whose channel has a rule:
//! (`StageIo::color_writes`, which link checks against the pipeline's), and writes each lane as
//! computed, the device's conversion storing it, but for a half-float channel under
//! `TextureWriteRoundingMode::NearestEven` (`color_writes::HALF_NEAREST`), which no device's
//! conversion of Metal's default does: the function rounds it to nearest even on every profile, and
//! the device's conversion of the rounded half is exact. A lane the device converts otherwise than
//! Metal may records a note:
//!
//! - a channel the device converts ([`ChannelWrite::Device`]: a blend other than one and zero,
//! alpha-to-coverage's alpha, or a format Metal was not measured with) is written as computed
//! and the module records `PrecisionNote::DeviceColorConversion`; one whose blend Metal rounds
//! to nearest even ([`ChannelWrite::BlendedNearestEven`], a half-float channel under
//! `TextureWriteRoundingMode::NearestEven`) is too, and records
//! `PrecisionNote::BlendedWriteRounding`;
//! - a `half` output (held widened) to a half-float channel is already a half: it is not
//! rounded again (to an 11- or 10-bit float channel it is), and to a packed 16-bit format's
//! channel ([`ChannelWrite::HalfUnorm`]) it rounds as a unorm channel's;
//! - a channel whose conversion the device makes where it is not measured to make Metal's (a
//! blend other than one and zero, alpha-to-coverage's alpha, a format Metal was not measured
//! with, or a unorm, snorm, sRGB or small float channel on a device that rounds it otherwise)
//! records `PrecisionNote::DeviceColorConversion`; one whose blend Metal rounds to nearest even
//! ([`ChannelWrite::BlendedNearestEven`], a half-float channel under
//! `TextureWriteRoundingMode::NearestEven`) records `PrecisionNote::BlendedWriteRounding`;
//! - a `half` output (held widened) to a half-float channel is already a half: the device's
//! conversion of it is exact;
//! - a `bfloat` output never arrives: Metal's compiler rejects one, and the stage's outputs refuse
//! it before (`legal::refuse_bfloat_color`);
//! - an integer output to a channel with a rule is Metal's pipeline error, which link refuses
//! (`ColorAttachment`): nothing rounds it;
//! (`ColorAttachment`): nothing converts it;
//! - a NaN written to a half-float channel is stored as the device's conversion encodes it
//! (`PrecisionNote::DeviceNanEncoding`) unless the device is measured to store Metal's: Metal
//! stores a `float` NaN as `0x7e00` and a `half` NaN's own bits. A `float` output's NaN (the
//! rounding writes `0x7fc00000`) is Metal's where the profile takes
//! `DriverDeviation::MetalFloatColorNans` or `MetalColorWrites`, a `half` output's (held
//! widened, its payload in the significand's top bits) where it takes `MetalHalfColorNans`,
//! and either where the function writes it through a 16-bit output (below); elsewhere the
//! module records the note (`runtime_lane::color_writes`: ANV and RADV store `0xfe00`, from a
//! 16-bit output too, lavapipe quiets or canonicalizes a `half` NaN, MoltenVK canonicalizes it
//! from a 32-bit output).
//! stores a `float` NaN as `0x7e00` and a `half` NaN's own bits. A `float` output's NaN is
//! Metal's where the profile takes `DriverDeviation::MetalColorWrites`, and a lane's the function
//! rounds to nearest even (its NaN `0x7fc00000`) where it takes `MetalFloatColorNans`; a `half`
//! output's (held widened, its payload in the significand's top bits) where it takes
//! `MetalHalfColorNans`, or where the function writes it through a 16-bit output (below);
//! elsewhere the module records the note (`runtime_lane::color_writes`: ANV and RADV store
//! `0xfe00`, from a 16-bit output too, lavapipe quiets or canonicalizes a `half` NaN, MoltenVK
//! canonicalizes it from a 32-bit output).
//!
//! On a profile that stores Metal's codes itself (`VkProperty::MetalColorWrites`) the map holds
//! only half-float channels (`pipeline::color_writes`): nothing rounds, and only the NaN note is
//! recorded, but for a channel that rounds to nearest even (`color_writes::HALF_NEAREST`, a
//! pipeline's `TextureWriteRoundingMode::NearestEven`), which no device's conversion does: the
//! function rounds it on every profile, and the device's toward-zero conversion of the rounded half
//! is exact.
//! only half-float channels (`pipeline::color_writes`): only the NaN note is recorded, and the
//! rounding to nearest even under `NearestEven`.
//!
//! Where the device is measured to convert one kind of channel as Metal does, an output variable's
//! lane to such a channel is written as computed, its NaN chosen where the device's store of it
//! would not be Metal's ([`color_write::Lane::NanAs`]), and the module requires the deviation's
//! property:
//! Where the device is measured to convert one kind of channel as Metal does, a lane of an output
//! variable to such a channel records no `DeviceColorConversion`, and the module requires the
//! deviation's property:
//! - a `float` output to a half-float or unsigned small float channel
//! (`DriverDeviation::MetalSmallFloatColorWrites`: RADV on the Radeon 780M, ANV on the Iris Xe
//! of RPL-P, NVIDIA's on the RTX 3090), its NaN written as the rounding's `0x7fc00000`, which
//! every such device stores as Metal's NaN of an unsigned channel and NVIDIA's as `0x7e00`
//! (RADV and ANV store `0xfe00` for every NaN of a half-float channel, noted as above, so
//! nothing is chosen there);
//! - an output to a 16-bit unorm or snorm channel (`DriverDeviation::MetalNorm16ColorWrites`:
//! RADV on the Radeon 780M), a blended snorm channel's NaN written as -1.0.
//! of RPL-P, NVIDIA's on the RTX 3090), which stores every value but a NaN as Metal does: the
//! NaN, as computed, is the device's (`PrecisionNote::DeviceNanEncoding`);
//! - an output to a 16-bit unorm or snorm channel but a blended snorm one, whose NaN Metal stores
//! as -1.0 (`DriverDeviation::MetalNorm16ColorWrites`: RADV on the Radeon 780M).
//!
//! An attachment no lane of which rounds is not listed as rounded: it keeps its Vulkan blend of
//! one and zero, through which the facts were measured too, and announces no shader conversion.
//! A write in the storage form, or through a 16-bit output, rounds as before: the facts are of
//! the device's conversion of an output variable. A storage write the shader blends into a 16-bit
//! float attachment gives every NaN as `0x7fc00000`, which the storage image's store converts:
//! Metal's `0x7e00` where the profile takes `DriverDeviation::MetalFloatStorageNans` (the module
//! requires its property), else the device's NaN, noted `PrecisionNote::DeviceNanEncoding` (ANV
//! stores `0xfe00`).
//! one and zero, through which the facts were measured too. A write in the storage form, or
//! through a 16-bit output, records the device's conversion: the facts are of the device's
//! conversion of an output variable. A storage write the shader blends into a 16-bit float
//! attachment gives every NaN as `0x7fc00000`, which the storage image's store converts: Metal's
//! `0x7e00` where the profile takes `DriverDeviation::MetalFloatStorageNans` (the module requires
//! its property), else the device's NaN, noted `PrecisionNote::DeviceNanEncoding` (ANV stores
//! `0xfe00`).
//!
//! Where the device does not store the output's NaN as Metal does, but is measured to store a
//! 16-bit output's bits unchanged (`DriverDeviation::HalfColorOutputBits`: MoltenVK 1.4.1 on the
//! M3 Max and the M4), its conversion to 16 bits is Metal's `half(float)`
//! (`DriverDeviation::MetalHalfConversion`), and the profile declares 16-bit outputs
//! (`storageInputOutput16`, with `shaderInt16` and `shaderFloat16`), an output to an attachment
//! whose every channel written is half-float is written as the bits of the half Metal stores,
//! through a 16-bit output variable ([`half_output`]): a `float` output rounded toward zero, a
//! `half` output as it is, each converted exactly to 16 bits by that conversion, a NaN as its own
//! payload's code by integer operations (`arith::color_write::half_bits`), so no conversion of the
//! device's chooses the NaN, the note is not recorded, and the module requires
//! `VkProperty::HalfColorOutputBits` and `VkProperty::MetalHalfConversion`. An attachment a lane of
//! which rounds is listed as rounded (`rounded_colors`), and one whose output is written so but
//! rounds nothing (a `half` output's) as written as a half's bits (`half_bit_colors`), its own
//! notice; either takes no Vulkan blend of one and zero. On a device not measured so the output
//! stays 32-bit: ANV and RADV store every NaN of a 16-bit output as `0xfe00` too, so the route
//! would change nothing there.
//! whose every channel written is half-float is written as the bits of its half, through a 16-bit
//! output variable ([`half_output`]): each lane converted to 16 bits by that conversion, a NaN as
//! its own payload's code by integer operations (`arith::color_write::half_bits`), so no
//! conversion of the device's chooses the NaN, the NaN note is not recorded, and the module
//! requires `VkProperty::HalfColorOutputBits` and `VkProperty::MetalHalfConversion`. An attachment
//! a lane of which rounds is listed as rounded (`rounded_colors`), and one whose output is written
//! so but rounds nothing as written as a half's bits (`half_bit_colors`), its own notice; either
//! takes no Vulkan blend of one and zero. On a device not measured so the output stays 32-bit: ANV
//! and RADV store every NaN of a 16-bit output as `0xfe00` too, so the route would change nothing
//! there.
use crate::air::abi::{AbiInt, OutputRole};
use crate::device::requirements::VkProperty;
use crate::error::DriverDeviation;
use crate::lower::arith::color_write;
use crate::lower::arith::srgb;
use crate::lower::arith::{FloatFmt, Form};
use crate::lower::emit::EmitCx;
use crate::lower::select::SelectCx;
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::color_writes;
use crate::pipeline::lower_inputs::ChannelWrite;
use crate::pipeline::stage_io::SelectedWrite;
use crate::pipeline::sym::{PushField, Stage};
use crate::pipeline::sym::Stage;
use crate::spirv::builder::FunctionBuilder;
use crate::spirv::error::BResult;
use crate::spirv::ids::Value;
use std::collections::BTreeSet;
/// Plan the rounding of a fragment function's output of form `f` to color attachment `color`
/// Plan the write of a fragment function's output of form `f` to color attachment `color`
/// (dual-source index 0), through an output variable or in the storage form (see the module
/// docs).
pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) {
@@ -111,7 +106,6 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) {
let metal = cx
.profile
.takes_driver_deviation(DriverDeviation::MetalColorWrites);
let metal_nans = metal_nans(cx, f);
let half = half_output(cx, color, f);
let storage = crate::lower::fragment::writes_through_storage(cx, color);
// A storage write the shader blends into a 16-bit float attachment stores the blend's `half`
@@ -124,28 +118,17 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) {
let mut lanes = [None; 4];
let mut device = false;
let mut blended = false;
let mut half_nans = false;
let mut nans = false;
let mut relied = BTreeSet::new();
let mut selected = None;
for (slot, rule) in lanes.iter_mut().zip(rules).take(usize::from(f.lanes)) {
let Some(rule) = rule else { continue };
half_nans |= !shader_blended && color_writes::half_float(rule) && !metal_nans && !half;
nans |= !shader_blended && color_writes::half_float(rule) && !nan_kept(cx, rule, f, half);
if metal && rule == color_writes::HALF {
continue;
}
*slot = match (rule, f.float_fmt()) {
(_, None | Some(FloatFmt::F64 | FloatFmt::BFloat)) => None,
// The draw selects the channel's rule: each one's lane, and what it does.
(ChannelWrite::Selected, Some(fmt)) => {
let (lane, write) = selected_lane(
cx,
(fmt, f.lanes),
(metal_nans, half || storage),
&mut relied,
);
selected = Some(write);
Some(lane)
}
match (rule, f.float_fmt()) {
(_, None | Some(FloatFmt::F64 | FloatFmt::BFloat)) => {}
// A `half` is a half already, whichever way the channel rounds.
(
ChannelWrite::FloatTowardZero {
mantissa: 10..,
@@ -156,35 +139,17 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) {
signed: true,
},
Some(FloatFmt::Half),
) => None,
(ChannelWrite::BlendedNearestEven { .. }, _) => {
blended |= !shader_blended;
None
}
(ChannelWrite::HalfUnorm { bits }, Some(fmt @ FloatFmt::Half)) => lane(
cx,
ChannelWrite::Unorm { bits },
fmt,
(metal_nans, half || storage),
&mut relied,
),
(ChannelWrite::Device, _) => {
device |= !shader_blended;
None
}
(rule, Some(fmt @ (FloatFmt::F32 | FloatFmt::Half))) => {
lane(cx, rule, fmt, (metal_nans, half || storage), &mut relied)
}
};
}
// The draw's rule word, and what each of its codes does, which link reads.
if let Some(write) = selected {
cx.push.insert(PushField::ColorWriteRule(color));
cx.families
.stage_io
.interface
.selected_colors
.insert(color, write);
) => {}
// The pipeline's rounding mode, which the function applies.
(rule @ ChannelWrite::FloatNearestEven { .. }, Some(_)) => *slot = Some(rule),
(ChannelWrite::BlendedNearestEven { .. }, _) => blended |= !shader_blended,
(ChannelWrite::Device, _) => device |= !shader_blended,
(rule, Some(fmt)) => match conversion(cx, rule, fmt, half || storage, &mut relied) {
Conversion::Metal => {}
Conversion::MetalButNan => nans |= !shader_blended,
Conversion::Device => device |= !shader_blended,
},
}
}
if device {
cx.precision.insert(PrecisionNote::DeviceColorConversion);
@@ -193,9 +158,9 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) {
cx.precision.insert(PrecisionNote::BlendedWriteRounding);
}
if sixteen_blended {
half_nans |= !storage_nan(cx, &mut relied);
nans |= !storage_nan(cx, &mut relied);
}
if half_nans {
if nans {
cx.precision.insert(PrecisionNote::DeviceNanEncoding);
}
if half {
@@ -206,23 +171,9 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) {
]);
}
cx.families.stage_io.color_properties.extend(relied);
let rounds = lanes
.iter()
.any(|l| matches!(l, Some(color_write::Lane::Rounded(_))));
// The color table, once: its buffer counts in the stage's limits.
if lanes.contains(&Some(color_write::Lane::Rounded(ChannelWrite::Srgb)))
&& cx.families.arith.color_table.is_none()
{
let class = srgb::ColorTable::of(cx.profile);
cx.families.arith.color_table = Some(class);
let d = &mut cx.descriptors;
match class {
srgb::ColorTable::Uniform => d.uniform_buffers = d.uniform_buffers.saturating_add(1),
srgb::ColorTable::Storage => d.storage_buffers = d.storage_buffers.saturating_add(1),
}
}
let rounds = lanes.iter().any(Option::is_some);
let sp = &mut cx.families.stage_io;
if lanes.iter().any(Option::is_some) {
if rounds {
sp.rounded.insert(color, lanes);
}
let listed = match (rounds, half) {
@@ -252,95 +203,81 @@ fn storage_nan(cx: &SelectCx<'_>, relied: &mut BTreeSet<VkProperty>) -> bool {
metal
}
/// The `f32` NaN the rounding writes for a small float's NaN (`0x7fc00000`), whose store each
/// driver of [`DriverDeviation::MetalSmallFloatColorWrites`] is measured by.
const QUIET_NAN: u32 = 0x7fc0_0000;
/// How the device converts a lane of an output of `fmt` (`F32` or `Half`) to a channel of rule
/// `rule` (a rule of Metal's, not the device's).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Conversion {
/// As Metal stores it.
Metal,
/// As Metal stores it but for a NaN, which the device encodes.
MetalButNan,
/// By the device's own rule, a near-equivalent (`PrecisionNote::DeviceColorConversion`).
Device,
}
/// How a fragment function writes a channel of rule `rule` (a rule the function applies, not
/// the device's) from an output of `fmt` (`F32` or `Half`) (`metal_nans`: the device stores the
/// output's NaN to a half-float channel as Metal does; `own`: the function writes the output
/// otherwise than as a value of its output variable the device converts, as a half's bits
/// through a 16-bit output, [`half_output`], or as a texel of a storage image): rounded by
/// Metal's rule, unless the device is measured to convert the channel's output as Metal does, whose
/// property the module then relies on (`relied`):
/// How the device converts a lane of an output of `fmt` to a channel of rule `rule` (`own`: the
/// function writes the output otherwise than as a value of its output variable the device
/// converts, as a half's bits through a 16-bit output, [`half_output`], or as a texel of a storage
/// image, which no fact measures): as Metal does where the profile takes the deviation measuring
/// it, whose property the module then relies on (`relied`), else the device's own:
///
/// - a `float` output to a half-float or unsigned small float channel where the profile takes
/// `DriverDeviation::MetalSmallFloatColorWrites`: as computed, a NaN as the rounding's
/// `0x7fc00000` (an unsigned channel's always, a half-float channel's where `metal_nans`;
/// elsewhere the device stores its own NaN there, noted `PrecisionNote::DeviceNanEncoding`);
/// `DriverDeviation::MetalSmallFloatColorWrites`: Metal's but for a NaN;
/// - an output to a 16-bit unorm or snorm channel where the profile takes
/// `DriverDeviation::MetalNorm16ColorWrites`: as computed, a blended snorm channel's NaN as
/// -1.0, as Metal stores it.
fn lane(
/// `DriverDeviation::MetalNorm16ColorWrites`: Metal's, but for a blended snorm channel, whose NaN
/// Metal stores as -1.0.
fn conversion(
cx: &SelectCx<'_>,
rule: ChannelWrite,
fmt: FloatFmt,
(metal_nans, own): (bool, bool),
own: bool,
relied: &mut BTreeSet<VkProperty>,
) -> Option<color_write::Lane> {
use color_write::Lane;
) -> Conversion {
let takes = |d| !own && cx.profile.takes_driver_deviation(d);
match rule {
ChannelWrite::FloatTowardZero { signed, .. }
ChannelWrite::FloatTowardZero { .. }
if fmt == FloatFmt::F32 && takes(DriverDeviation::MetalSmallFloatColorWrites) =>
{
relied.insert(VkProperty::MetalSmallFloatColorWrites);
(!signed || metal_nans).then_some(Lane::NanAs(QUIET_NAN))
Conversion::MetalButNan
}
ChannelWrite::Unorm { bits: 16 } | ChannelWrite::Snorm { bits: 16, .. }
if takes(DriverDeviation::MetalNorm16ColorWrites) =>
{
ChannelWrite::Unorm { bits: 16 }
| ChannelWrite::Snorm {
bits: 16,
blended: false,
} if takes(DriverDeviation::MetalNorm16ColorWrites) => {
relied.insert(VkProperty::MetalNorm16ColorWrites);
matches!(rule, ChannelWrite::Snorm { blended: true, .. })
.then_some(Lane::NanAs((-1.0f32).to_bits()))
Conversion::Metal
}
rule => Some(Lane::Rounded(rule)),
_ => Conversion::Device,
}
}
/// How a fragment function writes a lane of an output of `fmt` (`F32` or `Half`; `lanes` lanes)
/// whose channel's rule the draw selects (`ChannelWrite::Selected`), and what the attachment's
/// write does under each code of its rule word (`metal_nans` and `own` as [`lane`]'s, which
/// gives a half-float channel's lane, and records the properties it relies on in `relied`): a
/// lane of an 8-bit unorm channel rounds; of a half-float channel, it rounds where a `float`
/// output's lane does, a `half` output being a half already, and stores a NaN as the device
/// encodes it where the device does not store the output's NaN as Metal does (a lane the device
/// converts, or of no rule, as computed).
fn selected_lane(
cx: &SelectCx<'_>,
(fmt, lanes): (FloatFmt, u8),
(metal_nans, own): (bool, bool),
relied: &mut BTreeSet<VkProperty>,
) -> (color_write::Lane, SelectedWrite) {
use color_write::{HalfLane, Lane};
let half = match fmt {
FloatFmt::Half => HalfLane::AsComputed,
_ => match lane(cx, color_writes::HALF, fmt, (metal_nans, own), relied) {
Some(Lane::Rounded(_)) => HalfLane::Rounded,
Some(Lane::NanAs(bits)) => HalfLane::NanAs(bits),
Some(Lane::Selected { .. }) | None => HalfLane::AsComputed,
},
};
let bit = |code: u32| 1u8 << code;
let half_rounds = match half {
HalfLane::Rounded => bit(color_writes::HALF_CODE),
HalfLane::AsComputed | HalfLane::NanAs(_) => 0,
};
let write = SelectedWrite {
lanes,
rounds: bit(color_writes::UNORM8_CODE) | half_rounds,
nans: match metal_nans {
true => 0,
false => bit(color_writes::HALF_CODE),
},
};
(Lane::Selected { half }, write)
/// Whether the device stores the NaN a fragment function writes to a half-float channel of rule
/// `rule` from its output of form `f` as Metal does (the module docs; `half`: written as a half's
/// bits, [`half_output`]): a `float` output's where the profile takes
/// `DriverDeviation::MetalColorWrites`, or where the function rounds the lane
/// (`color_writes::HALF_NEAREST`), whose NaN `0x7fc00000` it then stores as Metal's `0x7e00`
/// under `MetalFloatColorNans` (the output's own NaN, unrounded, it is not measured to); a `half`
/// output's where it takes `MetalHalfColorNans`, or written as a half's bits. Another output stores
/// no NaN of its own there.
fn nan_kept(cx: &SelectCx<'_>, rule: ChannelWrite, f: Form, half: bool) -> bool {
let takes = |d| cx.profile.takes_driver_deviation(d);
match f.float_fmt() {
Some(FloatFmt::F32) => {
takes(DriverDeviation::MetalColorWrites)
|| (rule == color_writes::HALF_NEAREST
&& takes(DriverDeviation::MetalFloatColorNans))
}
Some(FloatFmt::Half) => half || takes(DriverDeviation::MetalHalfColorNans),
_ => true,
}
}
/// Whether the device stores the NaN of a fragment function's output of form `f` to a
/// half-float channel as Metal does (the module docs): a `float` output's where the profile
/// takes `DriverDeviation::MetalFloatColorNans` or `MetalColorWrites`, a `half` output's where
/// it takes `MetalHalfColorNans`. Another output stores no NaN of its own there.
/// half-float channel as Metal does, for [`half_output`]: a `float` output's where the profile
/// takes `DriverDeviation::MetalFloatColorNans` or `MetalColorWrites`, a `half` output's where it
/// takes `MetalHalfColorNans`. Another output stores no NaN of its own there.
fn metal_nans(cx: &SelectCx<'_>, f: Form) -> bool {
let takes = |d| cx.profile.takes_driver_deviation(d);
match f.float_fmt() {
@@ -400,17 +337,13 @@ pub(super) fn half_output(cx: &SelectCx<'_>, color: u32, f: Form) -> bool {
&& !crate::lower::fragment::writes_through_storage(cx, color)
}
/// The words of the planned writes, each emitted once per return.
pub(super) fn words(rounded: impl IntoIterator<Item = [Option<color_write::Lane>; 4]>) -> u64 {
rounded
.into_iter()
.map(|r| color_write::write_words(&r))
.sum()
/// The words of the planned roundings, each emitted once per return.
pub(super) fn words(rounded: impl IntoIterator<Item = [Option<ChannelWrite>; 4]>) -> u64 {
rounded.into_iter().map(|r| color_write::words(&r)).sum()
}
/// Output `x` (form `f`) to color attachment `color`, written as the plan writes each lane:
/// rounded, or its NaN chosen, or by the rule the attachment's rule word selects
/// (`PushField::ColorWriteRule`).
/// Output `x` (form `f`) to color attachment `color`, each lane the plan rounds rounded to nearest
/// even (`color_writes::HALF_NEAREST`), the others as computed.
pub(crate) fn round(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
@@ -418,16 +351,8 @@ pub(crate) fn round(
f: Form,
x: Value,
) -> BResult<Value> {
let Some(lanes) = cx.plan.families.stage_io.rounded.get(&color).copied() else {
let Some(rules) = cx.plan.families.stage_io.rounded.get(&color).copied() else {
return Ok(x);
};
let table = cx.decl.families.arith.color_table;
let selects = lanes
.iter()
.any(|l| matches!(l, Some(color_write::Lane::Selected { .. })));
let word = match selects {
true => Some(cx.push_field(fb, PushField::ColorWriteRule(color))?),
false => None,
};
color_write::write(fb, f, x, &lanes, (table, word))
color_write::round(fb, f, x, &rules)
}
@@ -1,291 +0,0 @@
//! Metal's `Depth16Unorm` codes, stored by the fragment stage (`LoweringInputs::depth16_codes`).
//!
//! Metal stores a depth `d` of `[0, 1]` in a `Depth16Unorm` attachment as the exact product
//! `65535 d` rounded to nearest, a tie up (probes on the M3 Max under macOS 26.7 and 27.0.1; the
//! one tie an `f32` of `[0, 1]` makes is 0.5's 32767.5, stored 32768). Vulkan converts the depth a
//! fragment stores by `convertFloatToUint(f × (2^b - 1), b)`, which "returns one of the two
//! unsigned binary integer values with exactly b bits which are closest to the floating-point
//! value r. Implementations should round to nearest. If r is equal to an integer, then that
//! integer value must be returned." (the Vulkan specification, "Conversion From Floating-Point to
//! Normalized Fixed-Point"). A device measured to store Metal's codes so takes
//! `DriverDeviation::MetalDepth16Stores`, and one measured to store Metal's codes of biased depths
//! too `DriverDeviation::MetalDepth16BiasedStores`, a biased draw on a device of only the first
//! running the variant that stores them here (`VariantKey::depth16_biased`); elsewhere the device's own rounding may store the code
//! next to Metal's near a midpoint (NVIDIA's 615.71.09 stored the code below up to 0.55 of a code
//! past one, lavapipe rounds the `float` product with ties to even). A stage compiled under the
//! input writes in place of each depth the `float` nearest Metal's code `c` over 65535
//! ([`code_depth`]): its product with 65535 lies within 2^-7 of `c`, so a conversion that rounds
//! to nearest, as the specification asks, stores `c`, as it stores every color channel the
//! translation rounds so (`arith::color_write`).
//!
//! - **A returned depth** (`[[depth(...)]]`) is clamped as Metal stores it (`clamp_depth`, to
//! `[0, 1]` on every profile here) and rounded to its code: Metal biases no depth a function
//! returns (probe `depthout`, the M3 Max under macOS 27.0.1: 16,020 rows of depths, constants
//! and slopes, every row but the two positive NaNs, which store nothing, Metal's code of the
//! clamped depth). Its `DepthGreater` or `DepthLess` mode is dropped, which the rounding can
//! break.
//! - **A function that returns no depth**, and a pipeline without a fragment function
//! ([`fragment_module`]), stores at entry the depth Metal stores for the fragment
//! ([`biased_depth`]): `FragCoord.z` (whose Vulkan bias the consumer records as zero) plus
//! Metal's bias, `o = s m + u` with `m = max(|dz/dx|, |dz/dy|)`, each operation rounded on its
//! own, clamped by Metal's clamp factor, added rounding toward zero, clamped to `[0, 1]`, and
//! rounded to its code (probe `depth16`, the M3 Max under macOS 27.0.1: 705 table rows and 24,000
//! random rows of constants exact, and 2,877 of 2,880 sloped rows, the other three within 0.002
//! of a code's midpoint). `u` is Metal's `c ± 1` units of 1/65535 (`metal::state::depth16_bias`)
//! and `s` and the clamp Metal's factors, from `PushField::DepthBias`. `m` is taken from the
//! quad's differences of `FragCoord.z` at entry, where the quad runs whole: Metal's slope is the
//! triangle's own, so a sloped bias can differ near a midpoint (the runtime announces it).
//!
//! A function that declares or takes early fragment tests, or runs its draw's tests itself, is not
//! compiled so (`LoweringInputs::depth16_codes`), nor is the store at entry made in one that reads
//! its position's depth: whether Metal's position takes the draw's bias is unmeasured, and with the
//! Vulkan bias recorded as zero it would not.
//!
//! A stage that writes its depth keeps a device from testing the depth before the stage runs, so
//! every fragment the depth hides runs it. Under a bias whose side is known
//! (`LoweringInputs::depth16_bias_raises`) the store at entry declares it, `DepthGreater` for a
//! bias that raises the depth and `DepthLess` for one that lowers it, which lets the device reject
//! a fragment the depth hides before the stage runs where its test compares that way
//! ([`bias_side_mode`], [`side_bounded`]): on the Iris Xe of Raptor Lake-P, 16 full-screen layers
//! drawn front to back took 1.85 ms so, against 9.42 ms without the declaration and 1.46 ms
//! through the device's own conversion (docs/FAST-PATHS.md, costs of matching Metal).
use crate::lower::arith::color_write::round_scaled_product;
use crate::lower::arith::legal::{FloatFmt, Form, Held};
use crate::lower::arith::ops::fsplat;
use crate::pipeline::interface::PushPlacement;
use crate::pipeline::sym::{PushField, Stage};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::Value as SValue;
use crate::spirv::ir::{
BinOp, ConstBits, Constant, ConvOp, DerivOp, ExecMode, ExecModel, GlslOp, IoDir, MemAccess,
Type, TypedModule,
};
use crate::spv::BuiltIn as B;
/// The words [`code_depth`] adds: the exact product's fourteen instructions, their constants and
/// nine `NoContraction` decorations, and the scale.
pub(crate) const CODE_WORDS: u64 = 30 * 6;
/// The words [`biased_depth`] adds beside [`code_depth`]'s: the field's three extracts and
/// conversions, the two derivatives and the slope, the bias and its clamp's comparisons and
/// selection, the sum's error and its step toward zero, the clamp to `[0, 1]`, their constants and
/// decorations.
pub(crate) const BIAS_WORDS: u64 = 40 * 6;
/// The words a function's synthesized depth adds at entry: its two objects' declarations and
/// interface entries, the push field's load, the `FragCoord` load and extract, the
/// [`biased_depth`] and [`code_depth`] arithmetic, and the store.
pub(crate) const STORE_WORDS: u64 = 4 * 6 + BIAS_WORDS + CODE_WORDS;
/// The scalar `f32` form.
const F32: Form = Form {
held: Held::Float(FloatFmt::F32),
lanes: 1,
};
/// `depth` (an `f32` of `[0, 1]`) as the `f32` the device stores as Metal's code `c`: `c` is the
/// exact product with 65535 rounded to nearest (`round_scaled_product`, ties to even, which
/// on `[0, 1]` meets only 0.5 and takes 32768, Metal's tie up), and the value is `c` times the
/// `f32` nearest 1/65535, within two `f32` rounding errors of `c / 65535`. A NaN passes as a NaN.
pub(crate) fn code_depth(fb: &mut FunctionBuilder<'_>, depth: SValue) -> BResult<SValue> {
let scale = fsplat(fb, F32, 65536.0)?;
let code = round_scaled_product(fb, F32, depth, scale)?;
let unit = fsplat(fb, F32, f64::from(1.0f32 / 65535.0))?;
fb.binary(BinOp::FMul, code, unit)
}
/// The depth Metal stores for a fragment at window depth `z` (`FragCoord.z`, unbiased) under the
/// draw's depth bias `bias` (`PushField::DepthBias`'s `uvec4` array), as [`code_depth`] writes it
/// (the module docs): [`offset_depth`] of Metal's slope, the larger of the depth's two screen
/// derivatives' magnitudes. The derivatives read the quad, so the caller emits this where every
/// invocation of it runs.
pub(crate) fn biased_depth(
fb: &mut FunctionBuilder<'_>,
z: SValue,
bias: SValue,
) -> BResult<SValue> {
let f32_ = fb.module().ty(Type::Float { width: 32 })?;
let word = |fb: &mut FunctionBuilder<'_>, i: u32| -> BResult<SValue> {
let bits = fb.composite_extract(bias, &[0, i])?;
fb.convert(ConvOp::Bitcast, bits, f32_)
};
let factors = [word(fb, 0)?, word(fb, 1)?, word(fb, 2)?];
let dx = fb.derivative(DerivOp::DPdx, z)?;
let dy = fb.derivative(DerivOp::DPdy, z)?;
let dx = fb.glsl(GlslOp::FAbs, &[dx])?;
let dy = fb.glsl(GlslOp::FAbs, &[dy])?;
let m = fb.glsl(GlslOp::NMax, &[dx, dy])?;
offset_depth(fb, z, m, factors)
}
/// The depth Metal stores for a fragment at window depth `z` of slope `m` under Metal's bias
/// `[units, slope, clamp]` (`metal::state::depth16_bias`), as [`code_depth`] writes it: the
/// offset `slope m + units`, bounded by a nonzero clamp from its side, added to `z` rounding toward
/// zero, clamped to `[0, 1]` (a NaN to 0). Every addition and product is decorated
/// `NoContraction`, so no device fuses the bias's product into its sum or the sum's error terms.
pub(crate) fn offset_depth(
fb: &mut FunctionBuilder<'_>,
z: SValue,
m: SValue,
[units, slope, clamp]: [SValue; 3],
) -> BResult<SValue> {
let f32_ = fb.module().ty(Type::Float { width: 32 })?;
let u32_ = fb.module().ty(Type::Int {
width: 32,
signed: false,
})?;
let sloped = fb.binary_no_contraction(BinOp::FMul, slope, m)?;
let offset = fb.binary_no_contraction(BinOp::FAdd, sloped, units)?;
// A clamp above 0 bounds the bias from above, one below 0 from below, and 0 not at all.
let zero = fsplat(fb, F32, 0.0)?;
let up = fb.binary(BinOp::FOrdGreaterThan, clamp, zero)?;
let past_up = fb.binary(BinOp::FOrdGreaterThan, offset, clamp)?;
let over = fb.binary(BinOp::LogicalAnd, up, past_up)?;
let down = fb.binary(BinOp::FOrdLessThan, clamp, zero)?;
let past_down = fb.binary(BinOp::FOrdLessThan, offset, clamp)?;
let under = fb.binary(BinOp::LogicalAnd, down, past_down)?;
let clamped = fb.binary(BinOp::LogicalOr, over, under)?;
let offset = fb.select(clamped, clamp, offset)?;
// `z + offset` rounded toward zero: the nearest sum and its exact error (TwoSum), and one step
// down where a positive sum lies above the exact one. A negative sum stores 0 whichever way it
// rounds.
let sum = fb.binary_no_contraction(BinOp::FAdd, z, offset)?;
let b = fb.binary_no_contraction(BinOp::FSub, sum, z)?;
let a = fb.binary_no_contraction(BinOp::FSub, sum, b)?;
let da = fb.binary_no_contraction(BinOp::FSub, z, a)?;
let db = fb.binary_no_contraction(BinOp::FSub, offset, b)?;
let error = fb.binary_no_contraction(BinOp::FAdd, da, db)?;
let positive = fb.binary(BinOp::FOrdGreaterThan, sum, zero)?;
let above = fb.binary(BinOp::FOrdLessThan, error, zero)?;
let step = fb.binary(BinOp::LogicalAnd, positive, above)?;
let bits = fb.convert(ConvOp::Bitcast, sum, u32_)?;
let one = fb.u32_const(1)?;
let one = fb.module().const_value(one)?;
let below = fb.binary(BinOp::ISub, bits, one)?;
let below = fb.convert(ConvOp::Bitcast, below, f32_)?;
let toward_zero = fb.select(step, below, sum)?;
let unit = fsplat(fb, F32, 1.0)?;
let depth = fb.glsl(GlslOp::NClamp, &[toward_zero, zero, unit])?;
code_depth(fb, depth)
}
/// The execution mode a stage that stores [`biased_depth`] declares under a bias of known side
/// (`LoweringInputs::depth16_bias_raises`): `DepthGreater` where it raises the depth, `DepthLess`
/// where it lowers it ([`side_bounded`] makes the declaration hold).
pub(crate) fn bias_side_mode(raises: bool) -> ExecMode {
match raises {
true => ExecMode::DepthGreater,
false => ExecMode::DepthLess,
}
}
/// The words [`side_bounded`] and [`bias_side_mode`] add: the mode's declaration and the bound.
pub(crate) const SIDE_WORDS: u64 = 3 + 6;
/// The depth a stage that declares [`bias_side_mode`] stores in place of [`biased_depth`]'s
/// `stored`: `NMax(stored, z)` where the bias raises the depth, `NMin(stored, z)` where it lowers
/// it, of the fragment's `z` (`FragCoord.z`). `DepthGreater` promises a depth no lower than
/// `FragCoord.z` and `DepthLess` one no higher, and a stage that breaks the promise is undefined
/// in Vulkan, so the bound keeps it by construction; it changes no code Metal stores.
///
/// The runtime gives a draw a side (`BindState::depth16_bias_raises`) only where Metal's units `u`
/// (`metal::state::depth16_bias`) lie above 0, the slope factor `s` is finite and not below 0, the
/// clamp `k` is not above 0 or is at least `u`, and the depth range of every Vulkan viewport of the
/// draw, and its Vulkan depth clamp range where it sets one (`VK_EXT_depth_clamp_control`), lie
/// inside `[0, 1]`; `DepthLess` mirrors each condition. Then, for raising, with
/// `q = fl(1/65535) = 2^-16 (1 + 2^-16)`, just below `1/65535`:
///
/// 1. `u >= q`: `u` is `(c + 1) / 65535` for a constant `c` of 0 or more, rounded to `float`, and
/// rounding keeps order.
/// 2. The offset `o >= q`: the quad's depths are finite, so the slope `m = max(|dz/dx|, |dz/dy|)`
/// is finite and not below 0, and so is `fl(s m)` (or `+inf`); `fl(fl(s m) + u) >= u` (a slope
/// factor of 0 adds 0). A clamp above 0 takes `min(o, k) >= min(u, k) = u`; one of 0 or below
/// bounds nothing from above. An infinite `o` saturates the depth at 1.
/// 3. For a `z` in `[0, 1]`, `stored >= z`: the sum rounded toward zero, `t`, is at least `z`, a
/// `float` not above the exact sum. Where `t >= 1` the depth clamps to 1, whose code 65535 is
/// written as `fl(65535 q) = fl(1 - 2^-32) = 1`. Below 1, `t > z + q - 2^-24`, so
/// `65535 t > 65535 z + 0.996`, Metal's code (nearest) is above `65535 z + 0.496`, and the
/// written `fl(code q)` lies within `2^-25` of `code (1 - 2^-32) / 65535`, above `z + 7.5e-6`.
/// 4. Without a Vulkan depth clamp the device clips each primitive's depth to the view volume, so
/// `z` lies in its Vulkan viewport's range, inside `[0, 1]`, and the bound is `stored`. Under
/// one (Metal's depth clamp mode, or a compensated range) `z` may leave `[0, 1]`: below 0
/// `stored >= 0 > z`, and above 1 the bound writes `z` where Metal stores 1, but the device
/// clamps the written depth to its clamp range, inside `[0, 1]`, so both store that range's top.
///
/// Lowering mirrors it: `u <= -q`, `o <= -q`, a sum at or below 0 stores 0, and below `z`
/// otherwise; a `z` below 0 under a Vulkan depth clamp stores the clamp range's bottom, as Metal's
/// 0 does.
pub(crate) fn side_bounded(
fb: &mut FunctionBuilder<'_>,
stored: SValue,
z: SValue,
raises: bool,
) -> BResult<SValue> {
let op = match raises {
true => GlslOp::NMax,
false => GlslOp::NMin,
};
fb.glsl(op, &[stored, z])
}
/// The push placement of a synthesized fragment stage ([`fragment_module`]): `PushField::DepthBias`
/// alone, at the fragment window's start.
pub(crate) fn fragment_placement() -> PushPlacement {
crate::lower::push::place(Stage::Fragment, &[PushField::DepthBias].into())
}
/// The fragment stage of a pipeline without a fragment function whose depth attachment is
/// `Depth16Unorm`, compiled where a function would be under `LoweringInputs::depth16_codes`: it
/// writes no color and stores at entry the depth Metal stores for the fragment
/// ([`biased_depth`]), reading the draw's bias from `PushField::DepthBias` at
/// [`fragment_placement`]'s offset. Under a bias of known side (`raises`) it declares the side
/// ([`bias_side_mode`]) and stores [`side_bounded`].
pub(crate) fn fragment_module(raises: Option<bool>) -> BResult<TypedModule> {
let mut mb = ModuleBuilder::new();
let f32_ = mb.ty(Type::Float { width: 32 })?;
let u32_ = mb.ty(Type::Int {
width: 32,
signed: false,
})?;
let vec4 = mb.ty(Type::Vector { elem: f32_, len: 4 })?;
let uvec4 = mb.ty(Type::Vector { elem: u32_, len: 4 })?;
let len = mb.constant(Constant::Scalar {
ty: u32_,
bits: ConstBits(1),
})?;
let field = mb.ty(Type::Array {
elem: uvec4,
len,
stride: Some(16),
})?;
let void = mb.ty(Type::Void)?;
let coord = mb.builtin(B::FragCoord, IoDir::Input, vec4)?;
let depth = mb.builtin(B::FragDepth, IoDir::Output, f32_)?;
// The one field, at the window's start ([`fragment_placement`]).
let offset = crate::lower::push::window(Stage::Fragment).0;
let member = mb.push_member(PushField::DepthBias, field, offset)?.index;
let push = mb.push_global()?;
let mut fb = mb.function(void)?;
let p = fb.module().global_value(coord)?;
let frag = fb.load(p, MemAccess::default())?;
let z = fb.composite_extract(frag, &[2])?;
let base = fb.module().global_value(push)?;
let index = fb.u32_const(member)?;
let index = fb.module().const_value(index)?;
let at = fb.access_chain(base, &[index])?;
let bias = fb.load(at, MemAccess::default())?;
let mut stored = biased_depth(&mut fb, z, bias)?;
if let Some(raises) = raises {
stored = side_bounded(&mut fb, stored, z, raises)?;
}
let out = fb.module().global_value(depth)?;
fb.store(out, stored, MemAccess::default())?;
fb.ret(None)?;
let f = fb.finish()?;
let mut modes = vec![ExecMode::OriginUpperLeft, ExecMode::DepthReplacing];
modes.extend(raises.map(bias_side_mode));
mb.entry(ExecModel::Fragment, f, modes)?;
mb.finalize()
}
+7 -49
View File
@@ -146,7 +146,6 @@
//! the function), and the interface variables and execution modes ([`declare`]).
pub(crate) mod color_write;
pub(crate) mod depth16;
pub(crate) mod extended_color;
pub mod fetch;
mod plan;
@@ -406,17 +405,16 @@ pub struct StageIoPlan {
/// interface parameter, one fetch per pulled attribute, the output stores, and the roundings of
/// color outputs.
pub words: u64,
/// How a fragment function writes the lanes of each color attachment's output it does not
/// leave to the device whole (`color_write`), through an output variable or in the storage
/// form: each rounded to the code Metal stores, or, where the device is measured to convert
/// it as Metal does, its NaN chosen.
pub rounded: BTreeMap<u32, [Option<crate::lower::arith::color_write::Lane>; 4]>,
/// The lanes of each color attachment's output a fragment function rounds itself
/// (`color_write`), through an output variable or in the storage form: each by its rule, a
/// half-float channel's under `TextureWriteRoundingMode::NearestEven`.
pub rounded: BTreeMap<u32, [Option<crate::pipeline::lower_inputs::ChannelWrite>; 4]>,
/// The color attachments whose output the function writes as the bits of the half Metal
/// stores, through a 16-bit output variable (`color_write::half_output`).
pub halves: BTreeSet<u32>,
/// The measured driver deviations, as their properties, a fragment function's color writes
/// rely on: channels written as computed because the device converts them as Metal does
/// (`color_write`). The module requires them.
/// rely on: channels that record no device conversion because the device converts them as
/// Metal does (`color_write`). The module requires them.
pub color_properties: BTreeSet<crate::device::requirements::VkProperty>,
/// The extended-range color attachments whose `float` or `half` output each return stores
/// as the raw texel Metal stores (`extended_color::encode`), with the form each is held in
@@ -430,10 +428,6 @@ pub struct StageIoPlan {
/// A fragment function's depth output, which each return gives Metal's answer
/// (`clamp_depth`).
pub depth_clamp: Option<DepthClamp>,
/// A fragment function that returns no depth, compiled under
/// `LoweringInputs::depth16_codes`: the `FragDepth` output and `FragCoord` input objects its
/// entry stores the depth Metal stores for the fragment through ([`depth16`]).
pub depth16: Option<Depth16Store>,
/// The render pipeline's private masks a fragment function applies itself
/// (`LoweringInputs::sample_mask`), which each return ANDs into the function's own
/// `[[sample_mask]]` output or stores as it.
@@ -651,21 +645,6 @@ pub struct DepthClamp {
pub object: usize,
pub clamps: bool,
pub range: bool,
/// Under `LoweringInputs::depth16_codes`, each return clamps the depth to `[0, 1]` and writes
/// it as Metal's `Depth16Unorm` code ([`depth16::code_depth`]).
pub codes: bool,
}
/// How a fragment function that returns no depth stores the depth Metal stores for the fragment
/// under `LoweringInputs::depth16_codes` ([`depth16`]): at entry, its `FragDepth` output object
/// (`depth`) takes [`depth16::biased_depth`] of its `FragCoord` input object's (`coord`) depth and
/// `PushField::DepthBias`, bounded by that depth on the bias's side where it is known (`raises`,
/// `LoweringInputs::depth16_bias_raises`, [`depth16::side_bounded`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Depth16Store {
pub depth: usize,
pub coord: usize,
pub raises: Option<bool>,
}
/// How a vertex function compiled under `LoweringInputs::viewport_compensation` stores its
@@ -1230,22 +1209,6 @@ pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<
let x = fetch::emit(cx, fb, &read)?;
cx.hold(v, x);
}
// The depth Metal stores for the fragment, in the first block, where the whole quad runs for
// the derivatives and the store dominates every return.
if let Some(d) = cx.plan.families.stage_io.depth16 {
let coord = global(cx, d.coord)?;
let coord = fb.module().global_value(coord)?;
let coord = fb.load(coord, MemAccess::default())?;
let z = fb.composite_extract(coord, &[2])?;
let bias = cx.push_field(fb, PushField::DepthBias)?;
let mut stored = depth16::biased_depth(fb, z, bias)?;
if let Some(raises) = d.raises {
stored = depth16::side_bounded(fb, stored, z, raises)?;
}
let out = global(cx, d.depth)?;
let out = fb.module().global_value(out)?;
fb.store(out, stored, MemAccess::default())?;
}
Ok(())
}
@@ -1706,12 +1669,7 @@ pub fn emit_return(
true => Some(cx.push_field(fb, PushField::DepthClampRange)?),
false => None,
};
let clamped =
clamp_depth(fb, part, kill, d.clamps || d.range || d.codes, range)?;
match d.codes {
true => depth16::code_depth(fb, clamped)?,
false => clamped,
}
clamp_depth(fb, part, kill, d.clamps || d.range, range)?
}
None => part,
};
+4 -67
View File
@@ -3104,12 +3104,9 @@ fn output(cx: &mut SelectCx<'_>, o: &OutputBinding, ty: AirTypeId) -> Result<Lin
DepthQualifier::Greater => (DepthMode::Greater, Some(ExecMode::DepthGreater)),
DepthQualifier::Less => (DepthMode::Less, Some(ExecMode::DepthLess)),
};
// A depth rounded to Metal's code can land below the fragment's own, or above it, so
// the function promises neither.
let codes = depth16_codes(cx);
let sp = &mut cx.families.stage_io;
sp.modes.push(ExecMode::DepthReplacing);
sp.modes.extend(extra.filter(|_| !codes));
sp.modes.extend(extra);
let link = out(
cx,
B::FragDepth,
@@ -3123,14 +3120,10 @@ fn output(cx: &mut SelectCx<'_>, o: &OutputBinding, ty: AirTypeId) -> Result<Lin
cx.facts.insert(RuntimeFact::DepthClampRange);
cx.push.insert(PushField::DepthClampRange);
}
if codes {
cx.facts.insert(RuntimeFact::Depth16Codes { biased: false });
}
cx.families.stage_io.depth_clamp = Some(DepthClamp {
object: link.object,
clamps: clamps_fragment_depth(cx),
range,
codes,
});
cx.families.fragment.depth_output = true;
link
@@ -3317,31 +3310,6 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
});
sp.interface.sample_mask = Some(masks);
}
// A fragment function that returns no depth under `LoweringInputs::depth16_codes` stores the
// depth Metal stores for the fragment at entry, its Vulkan bias recorded as zero: objects of
// its own, not the function's interface, which writes no depth. One that reads its position's
// depth keeps the device's conversion: whether Metal's position takes the draw's bias is
// unmeasured, and without the Vulkan bias it would not. Under a bias of known side
// (`LoweringInputs::depth16_bias_raises`) it declares the side (`depth16::bias_side_mode`).
if cx.stage == Stage::Fragment
&& depth16_codes(cx)
&& !cx.families.fragment.depth_output
&& !cx.families.stage_io.interface.position_depth
{
let raises = cx.inputs.depth16_bias_raises;
let sp = &mut cx.families.stage_io;
let depth = builtin_object(sp, B::FragDepth, IoDir::Output, Shape::F32);
let coord = builtin_object(sp, B::FragCoord, IoDir::Input, Shape::FVec(4));
sp.modes.push(ExecMode::DepthReplacing);
sp.modes.extend(raises.map(super::depth16::bias_side_mode));
sp.depth16 = Some(super::Depth16Store {
depth,
coord,
raises,
});
cx.facts.insert(RuntimeFact::Depth16Codes { biased: true });
cx.push.insert(PushField::DepthBias);
}
// Size: every object, the parameters' words, and a store per output element; a count's
// compare and select (and its constant 0) are a store's words more, and so is an
// amplification's offset added; an amplified output is a store, an add and a count's.
@@ -3376,7 +3344,7 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
// comparison and the kill.
+ 40 * u64::from(sp.alpha_test.is_some())
+ compensation_stores(sp.compensation)
+ sp.depth_clamp.map_or(0, |d| match (d.range, d.clamps || d.codes) {
+ sp.depth_clamp.map_or(0, |d| match (d.range, d.clamps) {
// The `[0, 1]` selects, the range's two clamps and the negative NaN's select.
(true, _) => 14,
(false, true) => 5,
@@ -3401,12 +3369,7 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
(sp.words_written.values())
.map(|&w| super::word_color::encode_words(w))
.fold(0u64, u64::saturating_add),
)
// A returned depth's code.
.saturating_add(match sp.depth_clamp.is_some_and(|d| d.codes) {
true => super::depth16::CODE_WORDS,
false => 0,
});
);
sp.words = (sp.objects.len() as u64)
.saturating_mul(OBJECT_WORDS)
.saturating_add(params)
@@ -3416,36 +3379,10 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
.saturating_mul(rets)
.saturating_mul(STORE_WORDS),
)
.saturating_add(rounding.saturating_mul(rets))
// The depth stored at entry.
.saturating_add(match sp.depth16 {
Some(d) if d.raises.is_some() => {
super::depth16::STORE_WORDS + super::depth16::SIDE_WORDS
}
Some(_) => super::depth16::STORE_WORDS,
None => 0,
});
.saturating_add(rounding.saturating_mul(rets));
Ok(())
}
/// Whether a fragment function stores Metal's `Depth16Unorm` codes itself
/// (`LoweringInputs::depth16_codes`): compiled under the input, it neither declares nor takes
/// early fragment tests (the storage form's, `fetch_early_tests`) nor runs its draw's tests itself,
/// where the device's tests take its depth before it runs.
fn depth16_codes(cx: &SelectCx<'_>) -> bool {
let early = matches!(
cx.entry.ep.stage,
AirStage::Fragment {
early_fragment_tests: true
}
);
cx.stage == Stage::Fragment
&& cx.inputs.depth16_codes
&& !early
&& !cx.families.fragment.fetch_early_tests
&& !cx.inputs.shader_tests
}
/// Whether AIR type `ty` of entry `e` is `half` or a vector of it: a `half` color output
/// (`PrecisionNote::HalfOutputPrecision`, or `HalfOutputFastMathBlend` under fast math).
fn half_color(e: &crate::air::Entry, ty: AirTypeId) -> bool {
+42 -173
View File
@@ -21,7 +21,7 @@ use super::slice::Slice;
use super::{
Coord, ImageDecl, ImageRef, QueryKind, QueryOp, Read, TexelClass, TexelConv, TexelForm,
};
use super::{HalfNans, NormWrite, NullArm, Prelude, Switch, TextureStrategy, Write};
use super::{HalfNans, NullArm, Prelude, Switch, TextureStrategy, Write};
use crate::memory::handles::{HANDLE_ALPHA_ONE, NEUTRAL_ELEMENT, NULL_HANDLE};
/// Emit strategy `s` of instruction `at` into the open block.
@@ -838,7 +838,7 @@ pub(crate) const SRGB_WRITE_WORDS: u32 =
/// below it; alpha's the exact product with 255 rounded to nearest: `pack_float_to_srgb_unorm4x8`
/// (`math::pack`), which a kernel's write takes too. Each code `c` is written as
/// `c` times the `f32` nearest `1 / 255`, whose product with 255 lies within `2^-7` of `c`, so
/// every device's conversion stores `c` (as `argb_codes` writes).
/// every device's conversion stores `c`.
fn srgb_codes(
fb: &mut FunctionBuilder<'_>,
table: crate::spirv::ids::GlobalId,
@@ -911,11 +911,9 @@ fn from_image(
StorageImageClass::RotateArgb => rotate_argb(fb, x, true)?,
StorageImageClass::AlphaInRed => alpha_in_red(fb, x, true)?,
// A `YCbCrWrite` slot is only written (`StorageImageClass::YCbCrWrite`).
StorageImageClass::HalfTowardZero
| StorageImageClass::HalfQuietNan
StorageImageClass::HalfQuietNan
| StorageImageClass::SmallFloatQuietNan
| StorageImageClass::YCbCrWrite
| StorageImageClass::OneBitAlpha => x,
| StorageImageClass::YCbCrWrite => x,
// A half-float texel's bits, through its unsigned integer alias: Metal's read, whole.
StorageImageClass::HalfBits => return half_bits_texel(fb, decl, form, x),
// An `RGB9E5Float` word, through its `R32_UINT` alias, decoded exactly.
@@ -1789,28 +1787,21 @@ pub fn to_image(
))
}
},
StorageImageClass::RotateArgb => {
let x = argb_codes(fb, form, x)?;
rotate_argb(fb, x, false)?
}
StorageImageClass::RotateArgb => rotate_argb(fb, x, false)?,
StorageImageClass::AlphaInRed if form.lanes == 4 => alpha_in_red(fb, x, false)?,
StorageImageClass::AlphaInRed => {
return Err(crate::spirv::error::BuildError::Type(
crate::spirv::error::TypeRule::FunctionSignature,
))
}
StorageImageClass::HalfTowardZero
| StorageImageClass::HalfQuietNan
| StorageImageClass::SmallFloatQuietNan => match form.conv {
TexelConv::F32 => half_write(fb, decl.class, form, x)?,
// A `half` texel, held widened, is a half already: the device stores it exactly.
_ => x,
},
StorageImageClass::HalfQuietNan | StorageImageClass::SmallFloatQuietNan => {
match form.conv {
TexelConv::F32 => half_write(fb, decl.class, form, x)?,
// A `half` texel, held widened, is a half already: the device stores it exactly.
_ => x,
}
}
StorageImageClass::YCbCrWrite => ycbcr_write_texel(fb, form, x)?,
StorageImageClass::OneBitAlpha => match (form.conv, form.lanes) {
(TexelConv::F32 | TexelConv::F16, 4) => one_bit_alpha(fb, x)?,
_ => x,
},
StorageImageClass::HalfBits => half_bits(fb, form, x)?,
StorageImageClass::SharedExponentBits => shared_exponent_word(fb, form, x)?,
};
@@ -1923,12 +1914,25 @@ fn half_bits_texel(
/// The `uvec` a `HalfBits` slot stores for held texel `x` (`f32` lanes of `form`): each lane's
/// half bits in its low 16 bits (`narrow::to_bits`, exact for every half, a NaN's sign and
/// payload included). A `half` texel's lanes are halves already, widened exactly; a `float`
/// texel's are first rounded toward zero to the half Metal stores ([`half_write`] under
/// `HalfTowardZero`: past 65504 to 65504, an infinity kept, every NaN [`QUIET_NAN`], whose bits
/// are Metal's `0x7e00`). An integer texel is not one a half-float slot takes.
/// texel's are first rounded to a half, which no conversion of the device's makes through the
/// alias: toward zero, as Metal stores it (`color_write::small_float`: past 65504 to 65504, an
/// infinity kept, every NaN [`QUIET_NAN`], whose bits are Metal's `0x7e00`). An integer texel is
/// not one a half-float slot takes.
fn half_bits(fb: &mut FunctionBuilder<'_>, form: TexelForm, x: SValue) -> BResult<SValue> {
use crate::lower::arith::legal::{FloatFmt, Form, Held};
let x = match form.conv {
TexelConv::F32 => half_write(fb, StorageImageClass::HalfTowardZero, form, x)?,
TexelConv::F32 => {
let f = Form {
held: Held::Float(FloatFmt::F32),
lanes: form.lanes,
};
crate::lower::arith::color_write::small_float(
fb,
f,
x,
crate::pipeline::color_writes::HALF,
)?
}
TexelConv::F16 => x,
_ => {
return Err(crate::spirv::error::BuildError::Type(
@@ -2066,9 +2070,9 @@ pub(crate) fn rgb9e5_word(fb: &mut FunctionBuilder<'_>, x: SValue) -> BResult<SV
Ok(word)
}
/// The `f32` NaN a written `float`'s NaN becomes under `HalfTowardZero` and `HalfQuietNan`
/// (`color_write::round`'s), which a device of `DriverDeviation::MetalFloatStorageNans` stores as
/// Metal's `0x7e00`.
/// The `f32` NaN a written `float`'s NaN becomes under `HalfQuietNan` and in a `HalfBits` slot's
/// rounding (`color_write::small_float`'s), which a device of
/// `DriverDeviation::MetalFloatStorageNans` stores as Metal's `0x7e00`.
const QUIET_NAN: u32 = 0x7fc0_0000;
/// The words of [`quiet_nans`]: one test and one select of the whole vector, and the constant.
@@ -2086,22 +2090,17 @@ fn quiet_nans(
fb.select(is_nan, nan, x)
}
/// The channels of written `float` texel `x` (`f32` lanes of `form`) to a half-float image by
/// class `class`: under `HalfTowardZero` the values every device stores as Metal's `half`, each
/// rounded toward zero to the `f32` that holds that `half` exactly, a finite value past 65504 to
/// 65504, an infinity kept and a NaN to [`QUIET_NAN`] (the half-float rule of `color_write::round`,
/// the fragment rule, which a kernel's write takes too, as measured; `color_write::small_float`
/// on the whole vector), so a device that rounds a conversion to nearest stores the exact `half`;
/// under `HalfQuietNan`, on a device that rounds as Metal does, the value as computed but a NaN as
/// [`QUIET_NAN`]. The NaN stores as the device's encoding of [`QUIET_NAN`] (Metal's `0x7e00` where
/// measured, `DriverDeviation::MetalFloatStorageNans`).
/// The channels of written `float` texel `x` (`f32` lanes of `form`) to a half-float or small
/// float image by class `class`: under `HalfQuietNan` and `SmallFloatQuietNan` the value as
/// computed, which the device's conversion rounds, but a NaN as [`QUIET_NAN`]. The NaN stores as
/// the device's encoding of [`QUIET_NAN`] (Metal's `0x7e00` where measured,
/// `DriverDeviation::MetalFloatStorageNans`).
fn half_write(
fb: &mut FunctionBuilder<'_>,
class: StorageImageClass,
form: TexelForm,
x: SValue,
) -> BResult<SValue> {
use crate::lower::arith::color_write;
use crate::lower::arith::legal::{FloatFmt, Form, Held};
let f = Form {
held: Held::Float(FloatFmt::F32),
@@ -2111,9 +2110,6 @@ fn half_write(
StorageImageClass::HalfQuietNan | StorageImageClass::SmallFloatQuietNan => {
quiet_nans(fb, f, x)
}
StorageImageClass::HalfTowardZero => {
color_write::small_float(fb, f, x, crate::pipeline::color_writes::HALF)
}
_ => Ok(x),
}
}
@@ -2342,25 +2338,17 @@ fn heap_halves(
fb.select(cond, written, texel)
}
/// The estimated words of a write's conversion by storage class `class` on four lanes:
/// `ARGB8Unorm`'s codes ([`argb_codes`]), an 8-bit sRGB format's ([`srgb_codes`]), a half-float
/// image's halves or NaN ([`half_write`]), or a YCbCr texel's bits and mark
/// ([`ycbcr_write_texel`]), none for the other classes' swizzles, which the write's base estimate
/// covers.
/// The estimated words of a write's conversion by storage class `class` on four lanes: an 8-bit
/// sRGB format's codes ([`srgb_codes`]), a half-float image's NaN ([`half_write`]), a half-float
/// texel's bits ([`half_bits`]), an `RGB9E5Float` word ([`shared_exponent_word`]), or a YCbCr
/// texel's bits and mark ([`ycbcr_write_texel`]), none for the other classes' swizzles, which the
/// write's base estimate covers.
pub(crate) fn class_write_words(class: StorageImageClass) -> u32 {
use crate::lower::arith::color_write;
use crate::pipeline::lower_inputs::ChannelWrite;
match class {
StorageImageClass::HalfTowardZero => {
color_write::small_float_words(crate::pipeline::color_writes::HALF, 4) as u32
}
StorageImageClass::HalfQuietNan | StorageImageClass::SmallFloatQuietNan => QUIET_NAN_WORDS,
StorageImageClass::RotateArgb => {
color_write::words(&[Some(ChannelWrite::Unorm { bits: 8 }); 4]) as u32
}
StorageImageClass::YCbCrWrite => YCBCR_WRITE_WORDS,
StorageImageClass::SrgbEncode | StorageImageClass::SrgbEncodeBgra => SRGB_WRITE_WORDS,
StorageImageClass::OneBitAlpha => ONE_BIT_ALPHA_WORDS,
StorageImageClass::SharedExponentBits => SHARED_EXPONENT_WORDS,
// A `float` texel's rounding, then four lanes' bits.
StorageImageClass::HalfBits => {
@@ -2381,118 +2369,6 @@ pub(crate) fn class_write_words(class: StorageImageClass) -> u32 {
/// (about twelve instructions each), the exponent's six, the word's placement, and the constants.
pub(crate) const SHARED_EXPONENT_WORDS: u32 = 3 * 12 * 6 + 8 * 6 + 3 * 6 + 12 * 4;
/// The words of [`one_bit_alpha`]: the extract, comparison, select and insert, and the
/// constants.
pub(crate) const ONE_BIT_ALPHA_WORDS: u32 = 40;
/// Written `float` texel `x` (four `f32` lanes, Metal's channel order) with alpha `1.0` above one
/// half and `0.0` elsewhere (a NaN 0): the code Metal stores in a 1-bit alpha
/// (`StorageImageClass::OneBitAlpha`), which every device stores exactly.
fn one_bit_alpha(fb: &mut FunctionBuilder<'_>, x: SValue) -> BResult<SValue> {
let a = fb.composite_extract(x, &[3])?;
let half = f32s(fb, 1, 0.5)?;
let above = fb.binary(BinOp::FOrdGreaterThan, a, half)?;
let one = f32s(fb, 1, 1.0)?;
let zero = f32s(fb, 1, 0.0)?;
let a = fb.select(above, one, zero)?;
fb.composite_insert(a, x, &[3])
}
/// The words [`heap_one_bit`] emits beside [`one_bit_alpha`], at most: the field's shift and mask,
/// and per 1-bit-alpha class its constant, comparison and union.
pub(crate) fn heap_one_bit_words() -> u32 {
let n = crate::metal::texel_format::heap_one_bit_indices().len() as u32;
20 + 14 * n
}
/// Written `float` texel `x` (four `f32` lanes) through heap handle `handle`, its alpha as
/// [`one_bit_alpha`] writes it where the handle's class is a 1-bit alpha's
/// (`metal::texel_format::heap_one_bit_indices`), as it is elsewhere (`NormWrite::HeapOneBit`).
fn heap_one_bit(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
handle: ValueId,
x: SValue,
) -> BResult<SValue> {
let indices = crate::metal::texel_format::heap_one_bit_indices();
let is = heap_class_among(cx, fb, handle, &indices)?;
let rounded = one_bit_alpha(fb, x)?;
fb.select(is, rounded, x)
}
/// Written `float` texel `v` (`f32` lanes of `form`, Metal's channel order) to `image`, each
/// channel rounded to the code Metal stores in the bound normalized format (`NormWrite::Class`): by
/// the module's routine and the slot's `TexelFormat` specialization, or a heap handle's class. A
/// texel of fewer than four lanes is widened by zeros and narrowed back.
fn norm_codes(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
image: &ImageRef,
form: TexelForm,
v: SValue,
) -> BResult<SValue> {
let Some(routine) = cx.decl.families.texture.norm_routine else {
return Err(cx.fail("a normalized write without its rounding routine"));
};
let class = match *image {
ImageRef::Slot(index) => {
let Some(c) = texel_format_const(cx, index) else {
return Err(cx.fail(format!("texture slot {index} has no texel format constant")));
};
fb.module().const_value(c)?
}
ImageRef::Heap { handle, .. } => {
let h = cx.operand(fb, handle)?;
super::heap_texel_class(cx, fb, h)?
}
};
let n = form.lanes;
let x = match n {
4 => v,
_ => {
let zero = f32s(fb, 1, 0.0)?;
let mut lanes = Vec::with_capacity(4);
for i in 0..4u8 {
lanes.push(match (n, i) {
(1, 0) => v,
(n, i) if i < n => fb.composite_extract(v, &[u32::from(i)])?,
_ => zero,
});
}
let f = f32_ty(fb)?;
let t = vec(fb, f, 4)?;
fb.composite_construct(t, &lanes)?
}
};
let r = super::norm_write::convert(fb, routine, x, class)?;
match n {
4 => Ok(r),
1 => fb.composite_extract(r, &[0]),
n => {
let lanes: Vec<u32> = (0..u32::from(n)).collect();
fb.vector_shuffle(r, r, &lanes)
}
}
}
/// `ARGB8Unorm`'s channels of written texel `x` (`f32` lanes of `form`) as the values every
/// device stores as Metal's codes: each the 8-bit unorm code Metal writes (the value clamped to
/// `[0, 1]`, a NaN 0, the exact product with 255 rounded to nearest) times the `f32` nearest `1 /
/// 255`, the rule (`color_write::round`). A device's conversion to the code may take either
/// neighbour of the product: the RTX 3090 stored the code below on 22 of the
/// `extended_range_planes` lane's 1,024 alpha values whose product lies just above a half, where
/// Metal and the other venues stored the nearest.
fn argb_codes(fb: &mut FunctionBuilder<'_>, form: TexelForm, x: SValue) -> BResult<SValue> {
use crate::lower::arith::color_write;
use crate::lower::arith::legal::{FloatFmt, Form, Held};
let f = Form {
held: Held::Float(FloatFmt::F32),
lanes: form.lanes,
};
let rule = Some(crate::pipeline::lower_inputs::ChannelWrite::Unorm { bits: 8 });
color_write::round(fb, f, x, &[rule; 4], None)
}
/// `a && b`, or `b` alone.
fn and(fb: &mut FunctionBuilder<'_>, a: Option<SValue>, b: SValue) -> BResult<SValue> {
match a {
@@ -3817,13 +3693,6 @@ fn write(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, w: &Write) -> BResul
}
_ => v,
};
// A normalized format's channels, rounded to the codes Metal stores, before the storage
// class converts the texel.
let v = match (w.norm, w.image) {
(NormWrite::Class, image) => norm_codes(cx, fb, &image, w.texel, v)?,
(NormWrite::HeapOneBit, ImageRef::Heap { handle, .. }) => heap_one_bit(cx, fb, handle, v)?,
_ => v,
};
// An extended-range texel's raw code, encoded as Metal writes it.
let texel = match w.extended {
Some(form) => {
+90 -163
View File
@@ -126,7 +126,6 @@ mod emit;
pub mod float_texel;
pub mod half;
pub(crate) mod heap_raw;
pub mod norm_write;
mod slice;
mod slot;
mod status;
@@ -430,14 +429,12 @@ pub struct Write {
/// The slot's variant binds a texture of this extended-range format: the write encodes the
/// raw texel ([`extended_range::encode`](crate::lower::arith::extended_range::encode)).
pub extended: Option<crate::metal::format::ExtendedRange>,
/// The slot's storage class ([`storage_class`]): a converting one rounds the write to Metal's
/// code of each channel (`RotateArgb`'s `ARGB8Unorm` codes; `HalfTowardZero`'s halves and
/// `HalfQuietNan`'s NaN).
/// The slot's storage class ([`storage_class`]): a converting one moves or encodes the
/// written channels (`RotateArgb`'s rotation, `SrgbEncode`'s codes, `HalfQuietNan`'s NaN).
pub class: StorageImageClass,
/// A `float` written through a heap handle on a device not measured to store it in a
/// half-float texture as Metal does ([`heap_write_class`]): the class (`HalfTowardZero` or
/// `HalfQuietNan`) the write takes where the handle's texel class is a half-float format's
/// (`emit::heap_halves`).
/// A `float` written through a heap handle on a device not measured to store its NaN in a
/// half-float texture as Metal does ([`heap_write_class`]): the class (`HalfQuietNan`) the
/// write takes where the handle's texel class is a half-float format's (`emit::heap_halves`).
pub heap_half: Option<StorageImageClass>,
/// A `float` written through a heap handle: its NaN lanes are quieted where the handle's
/// texel class is a small float's (`StorageImageClass::SmallFloatQuietNan`,
@@ -453,9 +450,6 @@ pub struct Write {
pub swizzle: bool,
/// How a `half` texel's NaN is written ([`half_nans`]).
pub half_nans: HalfNans,
/// How a `float` or `half` texel's channels are rounded to a normalized format's codes
/// ([`norm_storage`]).
pub norm: NormWrite,
/// The slot's variant binds a texture of another numeric class
/// (`LoweringInputs::cross_class`): `texel` is that class's own form
/// ([`native_write_form`]), into which the write first turns the declared lanes
@@ -506,35 +500,6 @@ impl IntRange {
}
}
/// How a `float` texel's write rounds its channels to the codes Metal stores in a normalized
/// format ([`norm_storage`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NormWrite {
/// As computed: no normalized format, or a device measured to store Metal's codes, or a
/// conversion the storage class makes (`StorageImageClass::OneBitAlpha`).
Device,
/// By the bound format's class (the slot's `TexelFormat` specialization, a heap handle's
/// class): the module's routine ([`norm_write`]).
Class,
/// Through a heap handle on a device measured to store Metal's codes but a 1-bit channel's:
/// alpha 1 only above one half where the handle's class is a 1-bit-alpha format's
/// (`metal::texel_format::heap_one_bit_indices`), as `StorageImageClass::OneBitAlpha` writes
/// it.
HeapOneBit,
}
impl NormWrite {
/// The words of the write's rounding: the routine's call, or the class index test, alpha's rule
/// and the select, and a heap handle's class read.
pub(crate) fn words(self, heap: bool) -> u32 {
match self {
NormWrite::Device => 0,
NormWrite::Class => norm_write::CALL_WORDS + if heap { HEAP_CLASS_WORDS } else { 0 },
NormWrite::HeapOneBit => emit::heap_one_bit_words() + emit::ONE_BIT_ALPHA_WORDS + 8,
}
}
}
/// How a `half` texel's write stores a NaN as Metal does ([`half_nans`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum HalfNans {
@@ -934,7 +899,6 @@ impl TextureStrategy {
0
}
+ w.half_nans.words()
+ w.norm.words(w.image.heap())
+ if w.cross.is_some() { 48 } else { 0 }
+ w.saturate.words()
+ if w.heap_bits {
@@ -1003,9 +967,6 @@ pub struct TexturePlan {
/// texel, which converts by the class its handle carries (`emit::heap_float_class`): the module
/// defines the `float` routine.
pub heap_float: bool,
/// Some heap texture's `float` write rounds to a normalized format's codes by the class its
/// handle carries ([`NormWrite::Class`]): the module defines the rounding routine.
pub heap_norm_write: 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`]).
@@ -1106,9 +1067,6 @@ pub struct Declared {
/// The module's routine converting one texel to a `float` result by the class
/// ([`float_texel::define`]), defined once where a slot takes it.
pub float_routine: Option<FuncId>,
/// The module's routine rounding a written `float` texel to a normalized format's codes by
/// the class ([`norm_write::define`]), defined once where a write takes it.
pub norm_routine: Option<FuncId>,
/// 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
@@ -1353,9 +1311,6 @@ pub fn declare(
if s.float_format && d.float_routine.is_none() {
d.float_routine = Some(float_texel::define(mb)?);
}
if s.norm_write && d.norm_routine.is_none() {
d.norm_routine = Some(norm_write::define(mb)?);
}
if s.swizzle {
let u32_ = mb.ty(SType::Int {
width: 32,
@@ -1452,9 +1407,6 @@ pub fn declare(
if plan.families.texture.heap_float && d.float_routine.is_none() {
d.float_routine = Some(float_texel::define(mb)?);
}
if plan.families.texture.heap_norm_write && d.norm_routine.is_none() {
d.norm_routine = Some(norm_write::define(mb)?);
}
Ok(d)
}
@@ -2495,9 +2447,6 @@ pub fn routine_words(
.then_some((half::CENSUS_NAME, half::ROUTINE_WORDS));
let float = (texture.heap_float || texture.slots.values().any(|s| s.float_format))
.then_some((float_texel::CENSUS_NAME, float_texel::ROUTINE_WORDS));
// The normalized write's rounding, once.
let norm = (texture.heap_norm_write || texture.slots.values().any(|s| s.norm_write))
.then_some((norm_write::CENSUS_NAME, norm_write::ROUTINE_WORDS));
// The heap's raw decode, once per result type.
let raw = (!texture.heap_raw.is_empty()).then(|| {
(
@@ -2510,7 +2459,6 @@ pub fn routine_words(
.chain(classes)
.chain(half)
.chain(float)
.chain(norm)
.chain(raw)
}
@@ -2521,7 +2469,7 @@ pub const HEAP_CLASS_CENSUS: &str = "sampler.heap.texel_class";
/// The class a `float` written through a heap handle takes where the handle's texel class is a
/// half-float format's (`emit::heap_halves`): the class a slot bound in such a format takes
/// (`metal::format::half_write_class`), `None` where that is `Identity` (the device stores the
/// write as Metal does).
/// write's NaN as Metal does).
pub(crate) fn heap_write_class(cx: &SelectCx<'_>) -> Option<StorageImageClass> {
match crate::metal::format::half_write_class(cx.profile) {
StorageImageClass::Identity => None,
@@ -2531,12 +2479,16 @@ pub(crate) fn heap_write_class(cx: &SelectCx<'_>) -> Option<StorageImageClass> {
/// What a `float` write to texture `image` (a slot's storage class `class`; a heap write's class
/// where its handle's is a half-float format's, `heap_half`) relies on or records where it may
/// reach a half-float image: a write the shader rounds or quiets stores the NaN `0x7fc00000`,
/// Metal's `0x7e00` where the profile takes `DriverDeviation::MetalFloatStorageNans` (the module
/// requires its property), else the device's encoding of it (`PrecisionNote::DeviceNanEncoding`); a
/// quieted write, unrounded, requires `VkProperty::MetalHalfStorageWrites`; and one left to the
/// device's conversion, a heap write's or a slot's whose choice declares a half-float format,
/// requires that and `VkProperty::MetalHalfStorageNans`.
/// reach a half-float image, whose rounding of each channel to `half` the device makes (Metal
/// rounds toward zero, a finite value past 65504 to 65504): Metal's where the profile takes
/// `DriverDeviation::MetalHalfStorageWrites` (the module requires its property), else the device's
/// (`PrecisionNote::DeviceColorConversion`), but for a half-float member a heap's unsigned integer
/// twin holds (`heap_bits`), whose bits the shader writes. A write the shader quiets stores the NaN
/// `0x7fc00000`, Metal's `0x7e00` where the profile takes `DriverDeviation::MetalFloatStorageNans`
/// (the module requires its property), else the device's encoding of it
/// (`PrecisionNote::DeviceNanEncoding`); one left to the device's conversion whole, a heap write's
/// or a slot's whose choice declares a half-float format, requires
/// `VkProperty::MetalHalfStorageNans` too.
pub(super) fn half_storage_facts(
cx: &mut SelectCx<'_>,
image: ImageRef,
@@ -2549,11 +2501,21 @@ pub(super) fn half_storage_facts(
ImageRef::Slot(_) => class,
};
let mut relied = Vec::new();
match applied {
StorageImageClass::HalfTowardZero | StorageImageClass::HalfQuietNan => {
if applied == StorageImageClass::HalfQuietNan {
relied.push(VkProperty::MetalHalfStorageWrites);
let rounded = |cx: &mut SelectCx<'_>, relied: &mut Vec<VkProperty>| {
let measured = cx
.profile
.takes_driver_deviation(DriverDeviation::MetalHalfStorageWrites);
match (heap_bits, measured) {
(true, _) => {}
(false, true) => relied.push(VkProperty::MetalHalfStorageWrites),
(false, false) => {
cx.precision.insert(PrecisionNote::DeviceColorConversion);
}
}
};
match applied {
StorageImageClass::HalfQuietNan => {
rounded(cx, &mut relied);
if cx
.profile
.takes_driver_deviation(DriverDeviation::MetalFloatStorageNans)
@@ -2568,7 +2530,7 @@ pub(super) fn half_storage_facts(
}
}
StorageImageClass::Identity if declared_half(cx, image)? => {
relied.push(VkProperty::MetalHalfStorageWrites);
rounded(cx, &mut relied);
relied.push(VkProperty::MetalHalfStorageNans);
}
_ => {}
@@ -2585,7 +2547,7 @@ pub(super) fn half_storage_facts(
/// ([`HalfNans::Kept`]), which a device of `DriverDeviation::MetalHalfTexelWrites` stores as its
/// bits, and any other float channel every NaN as `0x7fc00000` ([`HalfNans::Canonical`]), which a
/// 32-bit float channel stores as it is. The texture's format decides: a slot's declared format, or
/// the class it rounds by (`HalfTowardZero`, `HalfQuietNan`: a 16-bit float format's); a heap
/// the class it writes by (`HalfQuietNan`: a 16-bit float format's); a heap
/// element's handle class ([`HalfNans::HeapClass`]); a texture slot's word where its choice
/// declares none ([`HalfNans::SlotWord`]). A normalized format's channel stores no NaN
/// ([`HalfNans::Held`]).
@@ -2636,9 +2598,7 @@ pub(super) fn half_nans(
let slot = slot_of(cx, index)?.slot;
match cx.inputs.storage_images.get(&slot) {
Some(c) => match c.class {
StorageImageClass::HalfTowardZero | StorageImageClass::HalfQuietNan => {
(HalfNans::Kept, Stored::Device)
}
StorageImageClass::HalfQuietNan => (HalfNans::Kept, Stored::Device),
StorageImageClass::SmallFloatQuietNan => (HalfNans::Canonical, Stored::Device),
// The half's own bits, written through the unsigned integer alias.
StorageImageClass::HalfBits => (HalfNans::Kept, Stored::Exact),
@@ -2744,102 +2704,75 @@ fn heap_half_texel_writes(cx: &mut SelectCx<'_>, packed: bool) {
});
}
/// How a `float` (or `half`, held widened) texel's write in form `texel` to texture `image` of
/// shape `shape` rounds its channels where the texture's format may be a normalized one
/// (`norm_write`'s module docs: Metal stores each channel's code from its exact product). A device
/// measured to store those codes (`DriverDeviation::MetalNormStorageWrites`, whose property the
/// module then requires) takes the write as computed but for a 1-bit channel, which it rounds
/// otherwise: a slot of such a format takes `StorageImageClass::OneBitAlpha`, and a heap write
/// tests its handle's class where the device stores such a texture ([`NormWrite::HeapOneBit`]).
/// Elsewhere the write rounds by the bound format's class ([`NormWrite::Class`]): a slot's
/// `TexelFormat` specialization, a heap handle's class. A heap texture buffer carries no class, so
/// its write keeps the device's conversion (`PrecisionNote::DeviceColorConversion`) where such a
/// buffer may hold a format the device converts otherwise. A slot whose storage choice declares a
/// format that is not normalized, or converts by its class (sRGB, `ARGB8Unorm`, the half and small
/// floats, a YCbCr write, a 1-bit alpha), takes none.
pub(super) fn norm_storage(
/// What a `float` (or `half`, held widened) texel's write in form `texel` to texture `image` of
/// shape `shape` relies on or records where the texture's format may be a normalized one, whose
/// conversion the device makes: Metal stores each channel's value clamped to its range (a NaN 0)
/// times its maximum code exactly, rounded to nearest with a tie away from zero, a 1-bit channel 1
/// only above one half. A device measured to store those codes
/// (`DriverDeviation::MetalNormStorageWrites`, whose property the module then requires) stores
/// them, but for a 1-bit channel, which it rounds otherwise (RADV rounds its half up): a write of
/// four lanes that may reach a texture of a 1-bit alpha (a heap element, or a slot whose storage
/// choice declares no format, where the device stores such a texture) records
/// `PrecisionNote::DeviceColorConversion`. Elsewhere every such write records it (ANV and
/// lavapipe round the `f32` product with ties to even). A slot whose storage choice declares a
/// format that is not normalized, or encodes it by its class (sRGB, a YCbCr write, the half and
/// small floats), records nothing.
pub(super) fn norm_storage_facts(
cx: &mut SelectCx<'_>,
image: ImageRef,
shape: ImageShape,
texel: TexelForm,
) -> Result<NormWrite, Error> {
) -> Result<(), Error> {
use crate::device::requirements::VkProperty;
use crate::metal::format::{one_bit_storage, StorageUse};
use crate::vk::NumericFormat as N;
let buffer = shape.dim == ImageDim::Buffer;
let reached = match image {
ImageRef::Heap { .. } => true,
// Whether the write may reach a normalized format, and whether the bound texture decides it.
let (reached, bound) = match image {
ImageRef::Heap { .. } => (true, true),
ImageRef::Slot(index) => {
let slot = slot_of(cx, index)?.slot;
match cx.inputs.storage_images.get(&slot) {
None => true,
None => (true, true),
Some(c) => {
let normalized = c.vk_format == crate::vk::Format::UNDEFINED
let formatless = c.vk_format == crate::vk::Format::UNDEFINED;
let normalized = formatless
|| c.vk_format
.block()
.is_some_and(|b| matches!(b.color, Some(N::Unorm | N::Snorm)));
// `AlphaInRed` stores the rounded alpha in red: the routine rounds the
// texel in Metal's channels, before the class moves them.
normalized
&& matches!(
c.class,
StorageImageClass::Identity
| StorageImageClass::SwizzleBgra
| StorageImageClass::AlphaInRed
)
let converted = matches!(
c.class,
StorageImageClass::Identity
| StorageImageClass::SwizzleBgra
| StorageImageClass::AlphaInRed
| StorageImageClass::RotateArgb
);
(normalized && converted, formatless)
}
}
}
};
if !reached {
return Ok(NormWrite::Device);
return Ok(());
}
let measured = cx
if !cx
.profile
.takes_driver_deviation(DriverDeviation::MetalNormStorageWrites);
if measured {
cx.families
.texture
.storage_properties
.insert(VkProperty::MetalNormStorageWrites);
let use_ = match buffer {
true => StorageUse::texel_buffer(false, true),
false => StorageUse::texture(false, true),
};
// A heap write's alpha, where the device stores a texture of a 1-bit alpha there.
let one_bit = image.heap() && texel.lanes == 4 && one_bit_storage(use_, cx.profile);
return Ok(match (one_bit, buffer) {
(false, _) => NormWrite::Device,
(true, true) => {
cx.precision.insert(PrecisionNote::DeviceColorConversion);
NormWrite::Device
}
(true, false) => {
cx.families.access.heap_class_index = true;
NormWrite::HeapOneBit
}
});
.takes_driver_deviation(DriverDeviation::MetalNormStorageWrites)
{
cx.precision.insert(PrecisionNote::DeviceColorConversion);
return Ok(());
}
match image {
ImageRef::Heap { .. } if buffer => {
cx.precision.insert(PrecisionNote::DeviceColorConversion);
Ok(NormWrite::Device)
}
ImageRef::Heap { .. } => {
cx.families.texture.heap_norm_write = true;
cx.families.access.heap_class = true;
Ok(NormWrite::Class)
}
ImageRef::Slot(index) => {
let slot = slot_of(cx, index)?.slot;
if let Some(s) = cx.families.texture.slots.get_mut(&index) {
s.norm_write = true;
}
cx.facts
.insert(crate::pipeline::facts::RuntimeFact::TexelFormat { slot });
Ok(NormWrite::Class)
}
cx.families
.texture
.storage_properties
.insert(VkProperty::MetalNormStorageWrites);
let use_ = match shape.dim == ImageDim::Buffer {
true => StorageUse::texel_buffer(false, true),
false => StorageUse::texture(false, true),
};
if bound && texel.lanes == 4 && one_bit_storage(use_, cx.profile) {
cx.precision.insert(PrecisionNote::DeviceColorConversion);
}
Ok(())
}
/// A fragment function's write of a texel of form `texel` to texture `image` (`extended`: an
@@ -2853,7 +2786,7 @@ pub(super) fn norm_storage(
/// every mode. The write is built under the default's rule alone, so: a write that may be such
/// records the mode in `StageIo::texture_write_rounding`, for link to match against the pipeline's;
/// under `NearestEven` one whose slot's storage choice declares such a format (or rounds as a
/// half-float one: `HalfTowardZero`, `HalfQuietNan`) is refused
/// half-float one: `HalfQuietNan`) is refused
/// `NotImplemented(PrivateRenderState(TextureWriteRounding))`, and one whose bound texture
/// decides (a slot or texture buffer whose choice declares no format; a heap handle) states
/// `RuntimeFact::StorageTextureWriteRounding` or `RuntimeFact::HeapWriteRounding`, which the
@@ -2889,12 +2822,10 @@ fn mode_rounded_write(
match cx.inputs.storage_images.get(&slot) {
None => Target::Slot(slot),
Some(c) => match c.class {
StorageImageClass::HalfTowardZero | StorageImageClass::HalfQuietNan => {
Target::Declared {
half: true,
small: false,
}
}
StorageImageClass::HalfQuietNan => Target::Declared {
half: true,
small: false,
},
StorageImageClass::SmallFloatQuietNan => Target::Declared {
half: false,
small: true,
@@ -2968,9 +2899,9 @@ fn declared_half(cx: &SelectCx<'_>, image: ImageRef) -> Result<bool, Error> {
}
/// The class of texture slot `image`'s storage choice, where its variant states one, else
/// `Identity`: a write through a converting class stores Metal's code of each channel
/// (`RotateArgb`'s `ARGB8Unorm` codes; `HalfTowardZero`'s halves and `HalfQuietNan`'s NaN). A heap
/// element's is `Identity`.
/// `Identity`: a write through a converting class moves or encodes the written channels
/// (`RotateArgb`'s rotation, `SrgbEncode`'s codes, `HalfQuietNan`'s NaN). A heap element's is
/// `Identity`.
pub(crate) fn storage_class(
cx: &SelectCx<'_>,
image: ImageRef,
@@ -3787,12 +3718,9 @@ fn select_write(
false => HalfNans::Held,
};
// A `half` texel's too, held widened: Metal stores its value by the same rule.
let norm = match texel.conv {
TexelConv::F32 | TexelConv::F16 if extended.is_none() => {
norm_storage(cx, image, shape, texel)?
}
_ => NormWrite::Device,
};
if matches!(texel.conv, TexelConv::F32 | TexelConv::F16) && extended.is_none() {
norm_storage_facts(cx, image, shape, texel)?;
}
// A storage slot bound to a swizzled texture stores each channel from the lane the swizzle
// takes it to, under its variant, as plain Metal writes it. A `ulong` texel's is not measured.
let swizzle = shape.dim != ImageDim::Buffer && swizzled_storage(cx, image)?;
@@ -3821,7 +3749,6 @@ fn select_write(
heap_alpha_red,
swizzle,
half_nans,
norm,
cross,
saturate,
heap_bits,
@@ -1,167 +0,0 @@
//! A `float` or `half` texel a function writes to a normalized storage texture, rounded to the
//! code Metal stores.
//!
//! Metal stores a `float` write through `access::write`, `access::read_write`, a texture buffer or
//! an argument buffer's texture into a unorm or snorm format (not an sRGB one) as each channel's
//! value clamped to its range (a NaN 0) times its maximum code `m = 2^b - 1` (`2^(b-1) - 1`
//! signed) exactly, rounded to nearest with a tie away from zero; a packed 16-bit format's channel
//! takes the same exact product, not the `half` a color attachment rounds through first, and its
//! 1-bit channel stores 1 only above one half (an Apple M4 under macOS 27.0.1: every code's value
//! and every tie between codes with two `f32` steps either side, per channel), and a `half` write
//! as its value's (every one of the 65,536 halves, every format, both accesses), which the routine
//! takes widened. A Vulkan driver converts the `f32` it is handed by its own rounding: ANV and
//! lavapipe round the `f32` product with ties to even, NVIDIA's 615.71.09 stores the code below
//! about 40% of the values just past a tie (and RGB10A2's 2-bit alpha takes the top bits of an
//! 8-bit code), so near each tie they store another code.
//!
//! The slot's `SpecKey::TexelFormat` specialization (a heap texture's: the class its handle
//! carries) names the bound format's class (`metal::texel_format`), and one module routine,
//! [`define`]: `fn(x: vec4, flags: u32) -> vec4`, rounds each channel of `x` (Metal's channel
//! order, before any conversion of the storage choice) by it, so once a device specializes the
//! module and inlines the call, a slot's other arms fold away:
//!
//! - **The normalized families** (`BicubicTexels::EXACT` with `UNORM` or `SNORM`, without a packed
//! field): every channel on the format's maximum code, 255, 127, 65535 or 32767
//! (`BicubicTexels::WIDE16` for 16 bits).
//! - **A packed normalized class** (`TexelFormat::PACKED` with code scales, beside the family):
//! each channel on its own scale (`PackedTexels::scales`: 5, 6, 4, 10 and 2 bits, and the 1-bit
//! alpha of `A1BGR5Unorm` and `BGR5A1Unorm`, whose tie at one half rounds to even, 0, as Metal
//! stores it).
//! - **Any other class** (a float, half-float or small-float family, an 8-bit sRGB format's, whose
//! storage choice encodes it, a YCbCr field, `ARGB8Unorm`'s field, whose storage choice rounds
//! it, and `OTHER`): the texel as computed.
//!
//! Each rounded channel is `color_write`'s rule for a unorm or snorm color channel: the code `c`
//! from the exact product (`color_write::round_scaled_product`, the scale `m + 1` a power of two)
//! and the value written `c / m`, whose product with `m` lies within `2^-5` of `c`, so a device
//! that rounds the product to nearest stores `c` whatever it does at a tie.
//!
//! A device measured to store Metal's codes (`DriverDeviation::MetalNormStorageWrites`) takes no
//! routine; it rounds a 1-bit channel's half as other channels' (RADV), so a written slot of such a
//! format takes `StorageImageClass::OneBitAlpha` there.
use crate::lower::arith::color_write::round_scaled_product;
use crate::lower::arith::legal::{FloatFmt, Form, Held};
use crate::lower::arith::ops::{fsplat, splat, ty};
use crate::metal::bicubic::BicubicTexels;
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, ConvOp, GlslOp, Type as SType, UnOp};
use super::half::{packed_scales, TEXEL_LANES};
/// An upper estimate of the routine's words, counted once per module that defines it
/// (`the_norm_write_routine_words_bound_its_emission`).
pub const ROUTINE_WORDS: u64 = 1100;
/// An upper estimate of one call's words: the call and its argument, and a texel of fewer than
/// four lanes widened to four and narrowed back.
pub const CALL_WORDS: u32 = 32;
/// The census name of the routine.
pub const CENSUS_NAME: &str = "texture.norm_write";
fn fform() -> Form {
Form {
held: Held::Float(FloatFmt::F32),
lanes: 4,
}
}
fn uform(lanes: u8) -> Form {
Form {
held: Held::Int {
bits: 32,
container: 32,
},
lanes,
}
}
/// Define the routine `fn(x: vec4, flags: u32) -> vec4` in `mb` (module docs).
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.routine(vf)?;
let x = fb.param(vf)?;
let flags = fb.param(u32_)?;
let r = body(&mut fb, x, flags)?;
fb.ret(Some(r))?;
fb.finish()
}
fn body(fb: &mut FunctionBuilder<'_>, x: SValue, flags: SValue) -> BResult<SValue> {
let f = fform();
let u1 = |fb: &mut FunctionBuilder<'_>, v: u32| splat(fb, uform(1), u64::from(v));
let has = |fb: &mut FunctionBuilder<'_>, bit: u32| -> BResult<SValue> {
let m = u1(fb, bit)?;
let z = u1(fb, 0)?;
let and = fb.binary(BinOp::BitwiseAnd, flags, m)?;
fb.binary(BinOp::INotEqual, and, z)
};
let unorm = has(fb, BicubicTexels::UNORM)?;
let snorm = has(fb, BicubicTexels::SNORM)?;
let exact = has(fb, BicubicTexels::EXACT)?;
let wide = has(fb, BicubicTexels::WIDE16)?;
// The unpacked families' maximum code, in every lane.
let (m8, m8s) = (u1(fb, 255)?, u1(fb, 127)?);
let (m16, m16s) = (u1(fb, 65535)?, u1(fb, 32767)?);
let narrow = fb.select(snorm, m8s, m8)?;
let broad = fb.select(snorm, m16s, m16)?;
let m = fb.select(wide, broad, narrow)?;
let vu = ty(fb, uform(4))?;
let m = fb.composite_construct(vu, &[m; 4])?;
// A packed field's: each channel's own scale (1 in every lane of a field without scales).
let texel_lanes = u1(fb, TEXEL_LANES)?;
let (scales, coded, _) = packed_scales(fb, flags, texel_lanes)?;
let in_field = has(fb, TexelFormat::PACKED_MASK)?;
let m = fb.select(in_field, scales, m)?;
// The classes rounded: a normalized family's exact class, without a field or with one of
// scales.
let normalized = fb.binary(BinOp::LogicalOr, unorm, snorm)?;
let rounded = fb.binary(BinOp::LogicalAnd, exact, normalized)?;
let own = fb.unary(UnOp::LogicalNot, in_field)?;
let own_or_coded = fb.binary(BinOp::LogicalOr, own, coded)?;
let rounded = fb.binary(BinOp::LogicalAnd, rounded, own_or_coded)?;
// Each lane: a NaN 0, clamped to `[0, 1]` (`[-1, 1]` signed), its magnitude's code `c` on
// the scale `m` from the exact product, written as `c / m` with the value's sign.
let ft = ty(fb, f)?;
let mf = fb.convert(ConvOp::ConvertUToF, m, ft)?;
let one = fsplat(fb, f, 1.0)?;
let scale = fb.binary(BinOp::FAdd, mf, one)?;
let zero = fsplat(fb, f, 0.0)?;
let is_nan = fb.unary(UnOp::IsNan, x)?;
let v = fb.select(is_nan, zero, x)?;
let minus_one = fsplat(fb, f, -1.0)?;
let lo = fb.select(snorm, minus_one, zero)?;
let v = fb.glsl(GlslOp::NClamp, &[v, lo, one])?;
let a = fb.glsl(GlslOp::FAbs, &[v])?;
let c = round_scaled_product(fb, f, a, scale)?;
let q = fb.binary(BinOp::FDiv, c, mf)?;
let negative = fb.binary(BinOp::FOrdLessThan, v, zero)?;
let minus = fb.unary(UnOp::FNegate, q)?;
let q = fb.select(negative, minus, q)?;
fb.select(rounded, q, x)
}
/// Texel `x` (a `vec4` of `f32`, Metal's channel order) rounded by `routine` to the codes of the
/// bound format's class `flags` (a slot's `TexelFormat` specialization constant, or a heap
/// handle's class, as a value).
pub fn convert(
fb: &mut FunctionBuilder<'_>,
routine: FuncId,
x: SValue,
flags: SValue,
) -> BResult<SValue> {
// Every call of the routine returns its texel.
fb.call(routine, &[x, flags])?.ok_or(BuildError::Operand {
op: crate::spv::Op::FunctionCall,
rule: OperandRule::Callee,
})
}
@@ -87,10 +87,10 @@ pub struct Slice {
pub guard: bool,
/// The cell loads are contained.
pub contained: bool,
/// The slot's storage class (`super::storage_class`): a converting one (`RotateArgb`,
/// `HalfTowardZero`) rounds each texel to Metal's code of each channel.
/// The slot's storage class (`super::storage_class`): a converting one moves or encodes each
/// texel's channels (`RotateArgb`'s rotation, `HalfQuietNan`'s NaN).
pub class: StorageImageClass,
/// A `float` slice through a heap handle on a device not measured to store it in a
/// A `float` slice through a heap handle on a device not measured to store its NaN in a
/// half-float texture as Metal does: the class each texel takes where the handle's texel
/// class is a half-float format's (`super::Write::heap_half`).
pub heap_half: Option<StorageImageClass>,
@@ -342,6 +342,9 @@ pub(super) fn select(
if conv == TexelConv::F32 {
super::half_storage_facts(cx, image, class, (heap_half, heap_bits))?;
}
if matches!(conv, TexelConv::F32 | TexelConv::F16) {
super::norm_storage_facts(cx, image, t.image, TexelForm { conv, lanes })?;
}
let half_nans = match conv == TexelConv::F16 {
true => super::half_nans(cx, image, (false, heap_bits))?,
false => super::HalfNans::Held,
@@ -232,10 +232,6 @@ pub struct SlotPlan {
/// texel by the bound format's class (`float_texel`): the slot declares its `TexelFormat`
/// specialization and the module the `float` routine.
pub float_format: bool,
/// A `float` write to the slot rounds its channels by the bound format's class
/// (`norm_write`): the slot declares its `TexelFormat` specialization and the module the
/// rounding routine.
pub norm_write: bool,
/// A read of the slot, or an emulated linear sample of its cube's faces, takes an 8-bit sRGB
/// texel's raw code from the slot's raw view (`ResourceKind::RawTexture`), the slot being one
/// of `LoweringInputs::srgb_textures` (`RuntimeFact::SrgbTexture`).
@@ -283,7 +279,6 @@ impl SlotPlan {
half_filtered: false,
unmeasured: false,
float_format: false,
norm_write: false,
raw: false,
swizzle: false,
constant_lanes: false,
@@ -293,10 +288,10 @@ impl SlotPlan {
}
}
/// Whether the slot declares its `TexelFormat` specialization: a conversion or a rounding by
/// the bound format's class takes it.
/// 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 || self.float_format || self.norm_write
self.half_format || self.texel_format || self.float_format
}
/// Whether the slot is a storage image or storage texel buffer.
+14 -23
View File
@@ -3197,14 +3197,9 @@ pub(crate) fn fetch_view_alias(format: vk::Format, profile: &DeviceProfile) -> O
}
/// The class of a storage choice that views `pf`'s own format for `use_`: for a half-float
/// format (`R16Float`, `RG16Float`, `RGBA16Float`, `RGBX16Float`) the function writes, by what the device is
/// measured to store for a written `float` (Metal rounds each channel toward zero and stores
/// every NaN as `0x7e00`): `Identity` where it rounds and stores NaNs as Metal
/// does (`DriverDeviation::MetalHalfStorageWrites` and `MetalHalfStorageNans`), `HalfQuietNan`
/// where it rounds alone, else `HalfTowardZero`. An `RG11B10Float` texture the function writes
/// takes `SmallFloatQuietNan` on every device, and one of a 1-bit alpha ([`one_bit_alpha`])
/// `OneBitAlpha` on a device of `DriverDeviation::MetalNormStorageWrites` (elsewhere the shader
/// rounds it by its class). Otherwise `Identity`.
/// format (`R16Float`, `RG16Float`, `RGBA16Float`, `RGBX16Float`) the function writes,
/// [`half_write_class`]. An `RG11B10Float` texture the function writes takes
/// `SmallFloatQuietNan` on every device. Otherwise `Identity`: the device converts the write.
pub(crate) fn half_storage_class(
pf: PixelFormat,
use_: StorageUse,
@@ -3220,12 +3215,6 @@ pub(crate) fn half_storage_class(
match (half, pf == PixelFormat::RG11B10Float, use_.write) {
(true, _, true) => half_write_class(profile),
(_, true, true) => StorageImageClass::SmallFloatQuietNan,
(_, _, true)
if one_bit_alpha(pf)
&& profile.takes_driver_deviation(DriverDeviation::MetalNormStorageWrites) =>
{
StorageImageClass::OneBitAlpha
}
_ => StorageImageClass::Identity,
}
}
@@ -3233,14 +3222,16 @@ pub(crate) fn half_storage_class(
/// Whether `pf`'s alpha is a 1-bit unorm channel (`crate::metal::texel_format::PackedTexels::Rgb5A1`:
/// `A1BGR5Unorm`, `BGR5A1Unorm`), whose `float` write Metal stores as 1 only above one half, where
/// a device measured to store every other normalized channel as Metal does rounds the half up
/// (RADV).
/// (RADV): the device's conversion of such a write is noted (`lower::texture`'s
/// `norm_storage_facts`).
pub(crate) fn one_bit_alpha(pf: PixelFormat) -> bool {
crate::metal::texel_format::PackedTexels::of(pf)
== Some(crate::metal::texel_format::PackedTexels::Rgb5A1)
}
/// Whether `profile` stores a texture (or texture buffer) of a format with a 1-bit alpha
/// ([`one_bit_alpha`]) for `use_`: a heap write that may reach one tests its handle's class.
/// ([`one_bit_alpha`]) for `use_`: a write whose bound texture may be one notes the device's
/// conversion.
pub(crate) fn one_bit_storage(use_: StorageUse, profile: &DeviceProfile) -> bool {
PixelFormat::ALL
.iter()
@@ -3249,14 +3240,14 @@ pub(crate) fn one_bit_storage(use_: StorageUse, profile: &DeviceProfile) -> bool
}
/// The class a `float` write to a half-float storage image takes on `profile`
/// ([`half_storage_class`]).
/// ([`half_storage_class`]): the device rounds each channel to `half` (Metal's rule, toward zero,
/// where it takes `DriverDeviation::MetalHalfStorageWrites`), so `Identity` where it stores every
/// NaN as Metal does too (`MetalHalfStorageNans`), else `HalfQuietNan`, which writes a NaN as
/// `0x7fc00000`.
pub(crate) fn half_write_class(profile: &DeviceProfile) -> StorageImageClass {
let rounds = profile.takes_driver_deviation(DriverDeviation::MetalHalfStorageWrites);
let nans = profile.takes_driver_deviation(DriverDeviation::MetalHalfStorageNans);
match (rounds, nans) {
(true, true) => StorageImageClass::Identity,
(true, false) => StorageImageClass::HalfQuietNan,
(false, _) => StorageImageClass::HalfTowardZero,
match profile.takes_driver_deviation(DriverDeviation::MetalHalfStorageNans) {
true => StorageImageClass::Identity,
false => StorageImageClass::HalfQuietNan,
}
}
+6 -15
View File
@@ -1929,11 +1929,10 @@ fn storage_choices_on_committed_profiles_are_declarable() {
}
/// A half-float storage texture a function writes takes the class its `float` writes need, by
/// what the committed profile's device is measured to store (and lavapipe's
/// probes): `Identity` on MoltenVK (Metal's every value and NaN), `HalfQuietNan` where the device
/// rounds as Metal does but stores another NaN (RADV, ANV, NVIDIA's, lavapipe), `HalfTowardZero`
/// where its rounding is not measured; a read-only use, and another float format, stay `Identity`.
/// On a profile not measured to store a written `half`'s NaN as its bits
/// what the committed profile's device is measured to store for a NaN (and lavapipe's probes):
/// `Identity` on MoltenVK (Metal's every NaN), `HalfQuietNan` on every other profile, whose
/// device's own conversion rounds each value; a read-only use, and another float format, stay
/// `Identity`. On a profile not measured to store a written `half`'s NaN as its bits
/// (`DriverDeviation::MetalHalfTexelWrites`), a written use takes the unsigned integer alias
/// (`StorageImageClass::HalfBits`) wherever the alias serves it, an image of its own format alone
/// the measured class.
@@ -1944,15 +1943,7 @@ fn half_float_storage_writes_take_their_measured_class() {
let p = dev.profile();
let want = match stem.as_str() {
"moltenvk-m3" => StorageImageClass::Identity,
"amd-780m-radv"
| "amd-780m-hawkpoint-radv"
| "intel-irisxe-rplp-anv"
| "intel-uhd770-rpls-anv"
| "nvidia-rtx5080-laptop"
| "lavapipe"
| "gate-lavapipe"
| "gate-lavapipe-x86_64" => StorageImageClass::HalfQuietNan,
_ => StorageImageClass::HalfTowardZero,
_ => StorageImageClass::HalfQuietNan,
};
for pf in [
PixelFormat::R16Float,
@@ -1995,7 +1986,7 @@ fn half_float_storage_writes_take_their_measured_class() {
);
}
}
assert_eq!(seen.len(), 4, "{seen:?}");
assert_eq!(seen.len(), 3, "{seen:?}");
}
/// An `RG11B10Float` storage texture a function writes, or texture buffer, takes
-38
View File
@@ -521,44 +521,6 @@ fn depth16_units(c: f32) -> f64 {
f64::from(c) + if c >= 0.0 { 1.0 } else { -1.0 }
}
/// The depth bias a fragment stage that stores Metal's `Depth16Unorm` codes itself adds
/// (`BindState::depth_bias`, `RuntimeFact::Depth16Codes`), for the render encoder's
/// `setDepthBias:slopeScale:clamp:` factors `depth_bias` and `slope_scale` (both finite) and
/// `clamp` (finite; Metal's NaN or infinite clamp clamps nothing, as 0 does): `[u, s, k]`, `u`
/// Metal's `c ± 1` units of 1/65535 rounded once to `float` ([`depth_bias`]'s rule), `s` and `k`
/// the factors. All three are 0 where neither factor is nonzero, which biases nothing; the caller
/// passes 0 for a draw of points or lines, which Metal never biases.
pub fn depth16_bias(depth_bias: f32, slope_scale: f32, clamp: f32) -> [f32; 3] {
if depth_bias == 0.0 && slope_scale == 0.0 {
return [0.0; 3];
}
let units = (depth16_units(depth_bias) / 65535.0) as f32;
[units, slope_scale, clamp]
}
/// The side of the depth bias a fragment stage that stores Metal's `Depth16Unorm` codes itself
/// adds for the factors `depth_bias`, `slope_scale` and `clamp` ([`depth16_bias`]'s), where every
/// triangle's biased depth lies on it: `Some(true)` where Metal's units are above 0, the slope
/// factor finite and not below 0, and a clamp above 0 not below the units, so the stored depth is
/// never below the fragment's own; `Some(false)` for the mirror, never above it; `None` for any
/// other bias, whose side a triangle's slope decides, and for none. The caller also needs every
/// Vulkan depth range of the draw inside `[0, 1]` (`BindState::depth16_bias_raises`); the proof is
/// `lower::stage_io::depth16::side_bounded`'s.
pub fn depth16_bias_side(depth_bias: f32, slope_scale: f32, clamp: f32) -> Option<bool> {
let [units, slope, clamp] = depth16_bias(depth_bias, slope_scale, clamp);
if !units.is_finite() || !slope.is_finite() {
return None;
}
// A NaN or infinite clamp bounds nothing (`depth16_bias`), as the stage's comparisons find.
let raises = units > 0.0 && slope >= 0.0 && !(clamp > 0.0 && clamp < units);
let lowers = units < 0.0 && slope <= 0.0 && !(clamp < 0.0 && clamp > units);
match (raises, lowers) {
(true, _) => Some(true),
(_, true) => Some(false),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -914,21 +914,6 @@ pub fn heap_small_float_indices() -> Vec<u32> {
.collect()
}
/// The indices in [`heap_classes`] of the classes of a 1-bit alpha ([`PackedTexels::Rgb5A1`]'s
/// field: `A1BGR5Unorm`, `BGR5A1Unorm`; a swizzled texture's is `OTHER`): the classes whose
/// `float` write through a heap handle writes alpha 1 only above one half on a device measured to
/// store every other normalized channel as Metal does (`StorageImageClass::OneBitAlpha`), which a
/// write tests by its handle's index alone.
pub fn heap_one_bit_indices() -> Vec<u32> {
let one_bit = (PackedTexels::Rgb5A1 as u32) << TexelFormat::PACKED;
heap_classes()
.iter()
.enumerate()
.filter(|(_, &c)| c & TexelFormat::PACKED_MASK == one_bit)
.filter_map(|(i, _)| u32::try_from(i).ok())
.collect()
}
/// 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
@@ -246,9 +246,6 @@ mod serde_round_trips {
SampledType::Uint,
)]),
anisotropic_samplers: BTreeSet::from([slot(Stage::Fragment, SlotClass::Sampler, 1)]),
depth16_pass: Some(false),
depth16_biased: true,
depth16_bias_raises: Some(true),
color_group: 1,
});
round_trip(&SpecializationKey {
@@ -466,8 +463,6 @@ mod serde_round_trips {
anisotropic_samplers: BTreeSet::from([slot(Stage::Fragment, SlotClass::Sampler, 3)]),
uniform_varyings: BTreeSet::from([VaryingKey::user(b"user(tint)")]),
instanced_attributes: BTreeSet::from([1]),
depth16_codes: true,
depth16_bias_raises: Some(false),
color_group: Some(crate::pipeline::ColorGroup {
present: vec![0, 1, 2, 3, 5, 7],
width: 4,
@@ -675,7 +670,6 @@ mod serde_round_trips {
view: crate::pipeline::graphics::StandInView::Image,
}),
}),
color_write_rules: vec![(0, 0x3322), (2, 0x0001)],
snapshot_reads: true,
color_group: Some(crate::pipeline::ColorGroup {
present: vec![0, 5],
@@ -1022,10 +1016,6 @@ mod bind_serde_round_trips {
blend_color: [0.25, -0.5, 1.5, 0.75],
alpha_test_reference: Some(0.375),
primitive_type: Some(metal::PrimitiveType::TriangleStrip),
depth_bias: [1.5 / 65535.0, -2.0, 0.125],
depth16_pass: Some(true),
depth16_biased: true,
depth16_bias_raises: Some(true),
primitive_id_indices: Some(metal::IndexType::UInt16),
quad_primitive_ids: true,
private_list: true,
@@ -1087,9 +1077,6 @@ mod bind_serde_round_trips {
fragment_tests: crate::bind::FragmentTests::Pass,
extended_shadows: BTreeSet::from([0]),
snapshot_textures: BTreeSet::from([2]),
depth16_pass: Some(true),
depth16_biased: true,
depth16_bias_raises: Some(true),
primitive_id_indices: Some(metal::IndexType::UInt32),
quad_primitive_ids: true,
private_list: true,
+26 -22
View File
@@ -183,10 +183,10 @@ pub struct StageModule {
/// The constant data this stage reads at its `Synthetic(ConstantBlob)` binding, which the
/// binder fills from `WriteSource::ConstantBlob { stage }`. Each stage has its own.
pub constant_blob: Option<Arc<[u8]>>,
/// The color attachments whose float writes this fragment stage rounds to the codes Metal
/// stores in the shader (`StageIo::rounded_colors`), sorted: a normalized, sRGB or
/// half-float attachment on a device whose own conversion is not Metal's. Each such write
/// costs the stage's instructions per channel; empty for every other stage.
/// The color attachments whose float writes this fragment stage rounds in the shader
/// (`StageIo::rounded_colors`), sorted: a half-float attachment of a pipeline under
/// `TextureWriteRoundingMode::NearestEven`, whose rounding no device's conversion gives. Each
/// such write costs the stage's instructions per channel; empty for every other stage.
pub rounded_colors: Vec<u32>,
/// The notes of `precision_notes` that hold only under some specializations: a note whose
/// every access keeps its near-equivalent only on the arms the module selects by its
@@ -1180,25 +1180,29 @@ pub enum PrecisionNote {
/// Validation derives no tolerance and no explanation from it: a difference stays a mismatch
/// for review (no authored case binds such a view).
ViewBaseTexelOffset,
/// A fragment function writes a float to a color channel whose conversion the device makes,
/// not Metal's rule (`ChannelWrite::Device`): an attachment that blends with factors other
/// than one and zero, the alpha of attachment 0 under alpha-to-coverage, a format whose
/// conversion Metal was not measured with (the packed 16-bit unorm formats, `A8Unorm`, the
/// packed floats). (A `bfloat` output is refused, as Metal's compiler rejects one.) Near a tie
/// between two codes the device may store the other one (every Vulkan driver measured but
/// MoltenVK rounds the `f32` product with ties to even and encodes sRGB by its own
/// approximation, where Metal rounds the exact product and encodes through its twelve-bit
/// table). Every other float color write rounds to Metal's code in the shader. A 32-bit float
/// attachment that so blends stores the device's blend arithmetic (NVIDIA's 615.71.09 one `f32`
/// ulp from Metal's in some source-over sums, a NaN as `0x7fffffff` where Metal stores
/// `0x7fc00000`).
/// A fragment function writes a float to a color channel whose conversion the device makes
/// where it is not measured to make Metal's: a normalized, sRGB or small float channel the
/// attachment stores as written, on a device other than MoltenVK on an Apple GPU
/// (`VkProperty::MetalColorWrites`) not measured to convert that kind of channel as Metal does
/// (`DriverDeviation::MetalSmallFloatColorWrites`, `MetalNorm16ColorWrites`), an attachment that
/// blends with factors other than one and zero (`ChannelWrite::Device`), the alpha of
/// attachment 0 under alpha-to-coverage, a format whose conversion Metal was not measured with
/// (the packed 16-bit unorm formats, `A8Unorm`, the packed floats). (A `bfloat` output is
/// refused, as Metal's compiler rejects one.) Near a tie between two codes the device may store
/// the other one (every Vulkan driver measured but MoltenVK rounds the `f32` product with ties
/// to even, encodes sRGB by its own approximation and rounds a half to nearest, where Metal
/// rounds the exact product, encodes through its twelve-bit table and rounds a half toward
/// zero), and a NaN stores as its conversion makes it (Metal stores a normalized channel's as
/// 0, a blended snorm channel's as -1.0's code). A 32-bit float attachment that so blends
/// stores the device's blend arithmetic (NVIDIA's 615.71.09 one `f32` ulp from Metal's in some
/// source-over sums, a NaN as `0x7fffffff` where Metal stores `0x7fc00000`).
///
/// Also: a function writes a `float` texel through an argument buffer's texture buffer (a heap
/// texture buffer, which carries no texel class) that may hold a normalized format the device
/// converts otherwise than Metal, which stores each channel's exact product rounded with a tie
/// away from zero (a device without `DriverDeviation::MetalNormStorageWrites`, or with it where
/// such a buffer may hold a 1-bit alpha). Every other `float` texel write to a normalized
/// storage texture rounds to Metal's code in the shader.
/// Also: a function writes a `float` (or `half`) texel to a storage texture that may hold a
/// normalized or half-float format, or `ARGB8Unorm`, which the device converts where it is not
/// measured to store Metal's codes (`DriverDeviation::MetalNormStorageWrites`,
/// `MetalHalfStorageWrites`; a 1-bit alpha on a device measured to store every other
/// normalized channel's): Metal stores each normalized channel's exact product rounded with a
/// tie away from zero (a 1-bit channel 1 only above one half) and a half rounded toward zero.
///
/// Also: a blend into a packed 16-bit unorm attachment (`B5G6R5Unorm`, `A1BGR5Unorm`,
/// `ABGR4Unorm`, `BGR5A1Unorm`) reads what the device's attachment holds, its channels' codes,
+52 -205
View File
@@ -1,36 +1,36 @@
//! How a fragment function's float color outputs reach the attachments whose formats convert
//! them (`LoweringInputs::color_writes`).
//!
//! Metal stores a float written to a normalized attachment as the exact product with the
//! format's maximum code rounded to nearest, to an 8-bit sRGB one through its twelve-bit encode,
//! and to a half-float one rounded toward zero (`metal::format::write_conversion`, probes on an
//! Apple M3 Max and an M4). Vulkan's drivers round the `f32` product with ties to even, encode sRGB
//! by their own approximations, and round a half to nearest, so near every tie they store another
//! code (`runtime_lane::color_writes`: ANV, RADV, NVIDIA and lavapipe); only MoltenVK on Apple's
//! GPUs stores Metal's (`VkProperty::MetalColorWrites`). Everywhere else the fragment function
//! rounds each such output by Metal's rule itself and writes the `f32` nearest the code's exact
//! value, which every measured driver stores as that code. On MoltenVK the map keeps the half-float
//! channels alone, which round nothing and record the device's NaN encoding of a `half` output.
//! The device converts each output it is handed: its conversion is the contract. Metal stores a
//! float written to a normalized attachment as the exact product with the format's maximum code
//! rounded to nearest, to an 8-bit sRGB one through its twelve-bit encode, and to a half-float one
//! rounded toward zero (`metal::format::write_conversion`, probes on an Apple M3 Max and an M4).
//! Vulkan's drivers round the `f32` product with ties to even, encode sRGB by their own
//! approximations, and round a half to nearest, so near a tie they may store another code
//! (`runtime_lane::color_writes`: ANV, RADV, NVIDIA and lavapipe); only MoltenVK on Apple's GPUs
//! stores Metal's (`VkProperty::MetalColorWrites`). The map names each channel's rule so the
//! fragment function can record where the device's conversion is not measured to be Metal's
//! (`PrecisionNote::DeviceColorConversion`); it rounds none of them. On MoltenVK the map keeps the
//! half-float channels alone, which record the device's NaN encoding of a `half` output.
//!
//! Under `TextureWriteRoundingMode::NearestEven` (Apple's `textureWriteRoundingMode` 2) Metal
//! rounds a render state's half-float channels to nearest even ([`HALF_NEAREST`]), which no device
//! does for a conversion it stores after a blend or as Metal's default: the function rounds each
//! such channel itself on every profile, MoltenVK's included, where the channel stores the output
//! rounds a render state's half-float channels to nearest even ([`HALF_NEAREST`]), the mode the
//! pipeline asks for, which MoltenVK's conversion (toward zero, Metal's default) does not give: the
//! function rounds each such channel itself on every profile, where the channel stores the output
//! as written.
//!
//! The rounding is exact only where nothing after the shader changes the value: an attachment
//! that blends with factors other than one and zero keeps the device's conversion
//! ([`ChannelWrite::Device`], recorded as `PrecisionNote::DeviceColorConversion`), and so does
//! the alpha of attachment 0 under alpha-to-coverage at the default rounding mode, which the
//! coverage reads as computed. Under `NearestEven` that alpha rounds as the other channels do
//! where the attachment stores it: Metal stores the nearest-even half and reads the coverage from
//! the alpha before rounding (probe `a2c` on an Apple M3 Max, macOS 27.0.1: the coverage of 16,384
//! alphas is the same under either mode), which no device separates, so the coverage reads the
//! rounded alpha (`PrecisionNote::CoverageReadsRoundedAlpha`, [`pipeline_writes`]). An alpha its
//! write mask does not store keeps the device's conversion, which stores nothing, so the coverage
//! reads it as computed, as Metal's does. A format whose conversion
//! Metal was not measured with keeps the device's conversion too, and so does a 32-bit float
//! attachment that blends so, whose stored value is the device's blend arithmetic.
//! An attachment that blends with factors other than one and zero keeps the device's conversion
//! of the blend's result ([`ChannelWrite::Device`]), and so does the alpha of attachment 0 under
//! alpha-to-coverage at the default rounding mode, which the coverage reads as computed. Under
//! `NearestEven` that alpha rounds as the other channels do where the attachment stores it: Metal
//! stores the nearest-even half and reads the coverage from the alpha before rounding (probe
//! `a2c` on an Apple M3 Max, macOS 27.0.1: the coverage of 16,384 alphas is the same under either
//! mode), which no device separates, so the coverage reads the rounded alpha
//! (`PrecisionNote::CoverageReadsRoundedAlpha`, [`pipeline_writes`]). An alpha its write mask does
//! not store keeps the device's conversion, which stores nothing, so the coverage reads it as
//! computed, as Metal's does. A format whose conversion Metal was not measured with keeps the
//! device's conversion too, and so does a 32-bit float attachment that blends so, whose stored
//! value is the device's blend arithmetic.
//!
//! `Device::compile_render_pipeline` derives the map for a `Function` fragment stage from every
//! color attachment of the pipeline's descriptor ([`color_writes`]); the fragment function
@@ -55,49 +55,15 @@ use crate::pipeline::lower_inputs::{
ChannelWrite, ExtendedRangeColor, FactorLane, HalfOutputLane, RotatedBlendForm,
};
use crate::pipeline::rotated_blend::{rotated_blend, rotated_form, RotatedBlend};
use crate::pipeline::stage_io::{IoRole, SelectedWrite};
use crate::pipeline::stage_io::IoRole;
/// The color writes of a fragment function writing the attachments `written` (dual-source index
/// 0) of a pipeline whose color attachments are `colors` (alpha-to-coverage on where
/// `alpha_to_coverage`, its half-float channels rounding by `rounding`) on profile `p` (the
/// module docs). Where the device stores Metal's codes itself (`VkProperty::MetalColorWrites`)
/// the map keeps only the half-float channels ([`metal_stored`]), whose `half` NaN the
/// function's `float` output does not carry.
///
/// Elsewhere an attachment each of whose channels takes a selectable rule ([`code`]: none, the
/// device's conversion, an 8-bit unorm channel's, a half-float channel's), one of them a rounding
/// (an 8-bit unorm or a half-float channel's), takes [`ChannelWrite::Selected`] on every channel
/// ([`selects`]): the function computes each such rule and the draw selects one by the attachment's
/// rule word ([`rule_words`]), so the module is the same for every such format and blend.
/// [`exact_writes`] is the map before that.
/// module docs): each channel's rule. Where the device stores Metal's codes itself
/// (`VkProperty::MetalColorWrites`) the map keeps only the half-float channels
/// ([`metal_stored`]), whose `half` NaN the function's `float` output does not carry.
pub(crate) fn color_writes(
written: impl IntoIterator<Item = u32>,
colors: &[Option<ColorAttachmentDescriptor>],
rounding: (bool, TextureWriteRoundingMode),
p: &DeviceProfile,
) -> BTreeMap<u32, [Option<ChannelWrite>; 4]> {
let mut out = exact_writes(written, colors, rounding, p);
if !metal_color_writes(p) {
for rules in out.values_mut() {
if selects(rules) {
*rules = [Some(ChannelWrite::Selected); 4];
}
}
}
out
}
/// Whether profile `p`'s device stores Metal's codes itself (`VkProperty::MetalColorWrites`).
fn metal_color_writes(p: &DeviceProfile) -> bool {
p.fields()
.enabled
.properties
.contains(&VkProperty::MetalColorWrites)
}
/// The color writes [`color_writes`] derives before an attachment takes a selected rule: each
/// channel's own rule.
pub(crate) fn exact_writes(
written: impl IntoIterator<Item = u32>,
colors: &[Option<ColorAttachmentDescriptor>],
(alpha_to_coverage, rounding): (bool, TextureWriteRoundingMode),
@@ -131,105 +97,30 @@ pub(crate) fn exact_writes(
out
}
/// A rule word's code of a channel that takes no rule: the output as written.
pub(crate) const NO_RULE_CODE: u32 = 0;
/// A rule word's code of a channel the device converts ([`ChannelWrite::Device`]): the output as
/// written, recorded as `PrecisionNote::DeviceColorConversion`.
pub(crate) const DEVICE_CODE: u32 = 1;
/// A rule word's code of an 8-bit unorm channel ([`ChannelWrite::Unorm`] of 8 bits).
pub(crate) const UNORM8_CODE: u32 = 2;
/// A rule word's code of a half-float channel ([`HALF`]).
pub(crate) const HALF_CODE: u32 = 3;
/// The bits of each channel's code in an attachment's rule word: channel `i`'s code is
/// `(word >> (RULE_BITS * i)) & RULE_MASK`.
pub(crate) const RULE_BITS: u32 = 4;
/// One channel's code in a rule word, shifted down.
pub(crate) const RULE_MASK: u32 = (1 << RULE_BITS) - 1;
/// The code of a channel that takes `rule` in an attachment's rule word, or `None` where `rule`
/// is no selectable one.
fn code(rule: Option<ChannelWrite>) -> Option<u32> {
match rule {
None => Some(NO_RULE_CODE),
Some(ChannelWrite::Device) => Some(DEVICE_CODE),
Some(ChannelWrite::Unorm { bits: 8 }) => Some(UNORM8_CODE),
Some(rule) if rule == HALF => Some(HALF_CODE),
Some(_) => None,
}
}
/// The rule word of an attachment whose channels take `rules` ([`code`] of channel `i` at bits
/// `RULE_BITS * i`), or `None` where a channel takes a rule no code selects.
pub(crate) fn rule_word(rules: &[Option<ChannelWrite>; 4]) -> Option<u32> {
rules
.iter()
.zip(0u32..)
.try_fold(NO_RULE_CODE, |word, (&rule, i)| {
Some(word | code(rule)? << (RULE_BITS * i))
})
}
/// Whether an attachment whose channels take `rules` selects its rules at the draw
/// ([`color_writes`]): each channel's rule has a code ([`rule_word`]), and one of them rounds
/// (`UNORM8_CODE` or `HALF_CODE`). One that only keeps the device's conversion rounds nothing,
/// and keeps its module free of the rounding.
fn selects(rules: &[Option<ChannelWrite>; 4]) -> bool {
let rounds = |&r: &Option<ChannelWrite>| matches!(code(r), Some(UNORM8_CODE | HALF_CODE));
rule_word(rules).is_some() && rules.iter().any(rounds)
}
/// The codes the lanes `sel` writes take under rule word `word`.
fn lane_codes(sel: &SelectedWrite, word: u32) -> impl Iterator<Item = u32> {
(0..u32::from(sel.lanes.min(4))).map(move |i| (word >> (RULE_BITS * i)) & RULE_MASK)
}
/// Whether the write `sel` of an attachment of rule word `word` rounds a lane to Metal's code in
/// the shader, as an attachment the function lists in `StageIo::rounded_colors` does.
pub(crate) fn selected_rounds(sel: &SelectedWrite, word: u32) -> bool {
lane_codes(sel, word).any(|c| sel.rounds & (1 << c) != 0)
}
/// The precision notes the write `sel` of an attachment of rule word `word` keeps: the device's
/// conversion of a channel it converts (`PrecisionNote::DeviceColorConversion`), and its encoding
/// of a NaN where a lane's code stores one so (`PrecisionNote::DeviceNanEncoding`).
pub(crate) fn selected_notes(sel: &SelectedWrite, word: u32) -> BTreeSet<PrecisionNote> {
let mut notes = BTreeSet::new();
for c in lane_codes(sel, word) {
if c == DEVICE_CODE {
notes.insert(PrecisionNote::DeviceColorConversion);
}
if sel.nans & (1 << c) != 0 {
notes.insert(PrecisionNote::DeviceNanEncoding);
}
}
notes
/// Whether profile `p`'s device stores Metal's codes itself (`VkProperty::MetalColorWrites`).
fn metal_color_writes(p: &DeviceProfile) -> bool {
p.fields()
.enabled
.properties
.contains(&VkProperty::MetalColorWrites)
}
/// The precision notes and the attachments it rounds in the shader of fragment function `a` in
/// a render pipeline whose rule words are `rules` ([`rule_words`]) and whose color attachments
/// are `colors` (`GraphicsState::color_attachments`): the function's own
/// (`FunctionArtifact::precision`, `StageIo::rounded_colors`), for each attachment whose
/// rules it selects (`StageIo::selected_colors`) those its rule word selects
/// ([`selected_notes`], [`selected_rounds`]), `PrecisionNote::HalfOutputPrecision` where an
/// attachment of `StageIo::half_blend_colors` blends ([`blends_output`]), and
/// `PrecisionNote::HalfOutputFastMathBlend` where one of `StageIo::half_fast_colors` stores some
/// channel ([`stores_output`]), and `PrecisionNote::CoverageReadsRoundedAlpha` where the pipeline
/// covers by alpha (`alpha_to_coverage`, `GraphicsState::alpha_to_coverage`) and the function
/// rounds that alpha to nearest even ([`rounds_coverage_alpha`]). Each sorted, each entry once.
/// `None` where such an attachment has no rule word.
/// a render pipeline whose color attachments are `colors` (`GraphicsState::color_attachments`):
/// the function's own (`FunctionArtifact::precision`, `StageIo::rounded_colors`),
/// `PrecisionNote::HalfOutputPrecision` where an attachment of `StageIo::half_blend_colors`
/// blends ([`blends_output`]), and `PrecisionNote::HalfOutputFastMathBlend` where one of
/// `StageIo::half_fast_colors` stores some channel ([`stores_output`]), and
/// `PrecisionNote::CoverageReadsRoundedAlpha` where the pipeline covers by alpha
/// (`alpha_to_coverage`, `GraphicsState::alpha_to_coverage`) and the function rounds that alpha to
/// nearest even ([`rounds_coverage_alpha`]). Each sorted, each entry once.
pub(crate) fn pipeline_writes(
a: &FunctionArtifact,
rules: &[(u32, u32)],
colors: &[Option<ColorAttachmentState>],
alpha_to_coverage: bool,
) -> Option<(Vec<PrecisionNote>, Vec<u32>)> {
) -> (Vec<PrecisionNote>, Vec<u32>) {
let mut notes = a.precision.clone();
let mut rounded = a.interface.io.rounded_colors.clone();
let rounded = a.interface.io.rounded_colors.clone();
fn insert<T: Ord>(v: &mut Vec<T>, x: T) {
if let Err(at) = v.binary_search(&x) {
v.insert(at, x);
@@ -259,42 +150,7 @@ pub(crate) fn pipeline_writes(
if a.interface.io.half_fast_colors.iter().any(stored) {
insert(&mut notes, PrecisionNote::HalfOutputFastMathBlend);
}
for (&color, sel) in &a.interface.io.selected_colors {
let &(_, word) = rules.iter().find(|(c, _)| *c == color)?;
if selected_rounds(sel, word) {
insert(&mut rounded, color);
}
for note in selected_notes(sel, word) {
insert(&mut notes, note);
}
}
Some((notes, rounded))
}
/// The rule word of each attachment the fragment stage of interface `io` selects its rules for
/// (`StageIo::selected_colors`) in a render pipeline whose color attachments are `colors`
/// (alpha-to-coverage on where `alpha_to_coverage`, rounding by `rounding`) on `p`: its channels'
/// codes ([`rule_word`] of [`exact_writes`]), 0 where the pipeline converts nothing there. Sorted
/// by attachment. `NeedsInput(ColorWrites)` where a channel takes a rule no code selects, which
/// [`check`] refuses alike.
pub(crate) fn rule_words(
io: &crate::pipeline::stage_io::StageIo,
colors: &[Option<ColorAttachmentDescriptor>],
rounding: (bool, TextureWriteRoundingMode),
p: &DeviceProfile,
) -> Result<Vec<(u32, u32)>, Error> {
let exact = exact_writes(io.selected_colors.keys().copied(), colors, rounding, p);
io.selected_colors
.keys()
.map(|&a| {
let word = match exact.get(&a) {
Some(rules) => rule_word(rules),
None => Some(NO_RULE_CODE),
};
word.map(|w| (a, w))
.ok_or(Error::NeedsInput(RuntimeInput::ColorWrites))
})
.collect()
(notes, rounded)
}
/// Whether fragment function `a` rounds the alpha of its output to attachment 0 to nearest even in
@@ -382,8 +238,8 @@ fn metal_stored(c: &ColorAttachmentDescriptor) -> Option<[Option<ChannelWrite>;
/// Check the fragment stage `fragment` of a render pipeline whose color attachments are
/// `colors` (alpha-to-coverage on where `alpha_to_coverage`, rounding by `rounding`) on `p`: the
/// color writes it compiled under are the pipeline's for the attachments it writes, selected or
/// each channel's own ([`writes_hold`]), and so are its extended-range attachments' writes
/// color writes it compiled under are the pipeline's for the attachments it writes
/// ([`writes_hold`]), and so are its extended-range attachments' writes
/// ([`wanted_extended_range`]), and every color it stores nowhere (`StageIo::unattached_colors`)
/// has no attachment and is not color 0 under alpha to coverage, and the second outputs it writes
/// for rotated attachments are the pipeline's ([`wanted_rotated_factors`]), and so are the forms of
@@ -987,24 +843,15 @@ fn written(fragment: &FunctionArtifact) -> impl Iterator<Item = u32> + '_ {
}
/// Whether the color writes the fragment stage `fragment` compiled under
/// (`StageIo::color_writes`) are the pipeline's: each attachment's entry is the one the pipeline
/// gives it ([`wanted`]), or the entry of its channels' own rules ([`exact_writes`]), which a
/// function compiled under them (a caller's inputs, the map) takes, and the function has an entry
/// for no other attachment.
/// (`StageIo::color_writes`) are the pipeline's ([`wanted`]): the same entry for each attachment,
/// and none for another.
fn writes_hold(
fragment: &FunctionArtifact,
colors: &[Option<ColorAttachmentDescriptor>],
rounding: (bool, TextureWriteRoundingMode),
p: &DeviceProfile,
) -> bool {
let selected = wanted(fragment, colors, rounding, p);
let exact = exact_writes(written(fragment), colors, rounding, p);
let compiled = &fragment.interface.io.color_writes;
let mut attachments = selected.keys().chain(exact.keys()).chain(compiled.keys());
attachments.all(|a| {
let got = compiled.get(a);
got == selected.get(a) || got == exact.get(a)
})
wanted(fragment, colors, rounding, p) == fragment.interface.io.color_writes
}
/// How attachment `c` takes each channel of a float output; `coverage_alpha` where
@@ -136,8 +136,6 @@ pub struct FragmentPass<'a> {
pub(crate) color_attachments: &'a [Option<ColorAttachmentDescriptor>; 8],
/// The pipeline has a depth or a stencil attachment.
pub(crate) depth_or_stencil: bool,
/// The pipeline's depth attachment is `Depth16Unorm` (`LoweringInputs::depth16_codes`).
pub(crate) depth16: bool,
pub(crate) raster_sample_count: u32,
pub(crate) rasterization_enabled: bool,
pub(crate) alpha_to_coverage: bool,
@@ -165,7 +163,6 @@ impl<'a> From<&'a RenderPipelineDescriptor> for FragmentPass<'a> {
FragmentPass {
color_attachments: &d.color_attachments,
depth_or_stencil: d.depth_format.is_some() || d.stencil_format.is_some(),
depth16: d.depth_format == Some(crate::metal::PixelFormat::Depth16Unorm),
raster_sample_count: d.raster_sample_count,
rasterization_enabled: d.rasterization_enabled,
alpha_to_coverage: d.alpha_to_coverage,
@@ -188,7 +185,6 @@ impl<'a> From<&'a MeshPipelineDescriptor> for FragmentPass<'a> {
FragmentPass {
color_attachments: &d.color_attachments,
depth_or_stencil: d.depth_format.is_some() || d.stencil_format.is_some(),
depth16: d.depth_format == Some(crate::metal::PixelFormat::Depth16Unorm),
raster_sample_count: d.raster_sample_count,
rasterization_enabled: d.rasterization_enabled,
alpha_to_coverage: d.alpha_to_coverage,
@@ -2206,46 +2202,9 @@ pub(crate) fn fragment_inputs(
out.depth_compare_clamp_mask = d.depth_compare_clamp_mask;
out.half_output_lanes = crate::pipeline::color_writes::half_output_lanes(d.color_attachments);
out.texture_write_rounding = d.texture_write_rounding_mode;
out.depth16_codes = depth16_codes(d, v, p);
out.depth16_bias_raises = v.depth16_bias_raises.filter(|_| out.depth16_codes);
out
}
/// Whether a fragment stage of pass `d` under variant `v` on `p` stores Metal's `Depth16Unorm`
/// codes itself (`LoweringInputs::depth16_codes`): the depth it renders against is
/// `Depth16Unorm` (`VariantKey::depth16_pass`, else the pipeline's depth attachment), and
/// [`depth16_stage_form`] holds, for a biased draw under `VariantKey::depth16_biased`.
pub(crate) fn depth16_codes(d: FragmentPass<'_>, v: &VariantKey, p: &DeviceProfile) -> bool {
v.depth16_pass.unwrap_or(d.depth16)
&& depth16_stage_form(
d.rasterization_enabled,
d.raster_sample_count,
v.depth16_biased,
p,
)
}
/// Whether a pipeline that rasterizes (`rasterizes`) `samples` samples per pixel on `p` takes
/// Metal's codes from its fragment stage where it renders against a `Depth16Unorm` depth, for a
/// draw that biases it where `biased`: it rasterizes one sample, and the profile lacks
/// `DriverDeviation::MetalDepth16Stores`, or for a biased draw
/// `DriverDeviation::MetalDepth16BiasedStores`. At more than one sample the device's depth is
/// each sample's own, which one written depth would replace.
pub(crate) fn depth16_stage_form(
rasterizes: bool,
samples: u32,
biased: bool,
p: &DeviceProfile,
) -> bool {
use crate::error::DriverDeviation::{MetalDepth16BiasedStores, MetalDepth16Stores};
let stores = if biased {
MetalDepth16BiasedStores
} else {
MetalDepth16Stores
};
rasterizes && samples <= 1 && !p.takes_driver_deviation(stores)
}
/// The attributes the vertex function `spec` fetches in fixed function under `inputs` from
/// layouts `desc` steps per instance or at a constant step, where taking them so makes it write
/// some varying the same at every vertex of a primitive
+9 -117
View File
@@ -602,7 +602,7 @@ impl Device {
check_call_stack(c.artifact(), 1)?;
}
let artifacts: Vec<&FunctionArtifact> = compiled.iter().map(|c| c.artifact()).collect();
let mut linked = link(&artifacts, &LinkInputs::mesh(d), p)?;
let linked = link(&artifacts, &LinkInputs::mesh(d), p)?;
let mut stages = Vec::with_capacity(compiled.len());
for (i, c) in compiled.iter().enumerate() {
stages.push(stage_module(c, &linked, i)?);
@@ -642,10 +642,6 @@ impl Device {
}
let mut dependencies = dependencies(&artifacts, self);
dependencies.extend(mesh_facts);
let depth = (&mut linked, &mut stages, &mut dependencies);
if let Some(r) = depth16_stage((d.into(), v, d.fragment.is_none()), depth, p, m)? {
requirements = p.union_requirements(&requirements, &r);
}
let (graphics, requirements) = graphics_requirements(requirements, &linked, &artifacts, p)?;
let profile = self.profile_fingerprint();
Ok(RenderPipeline {
@@ -903,7 +899,7 @@ impl Device {
}
let compiled: Vec<&CompiledFunction> = std::iter::once(&vertex).chain(&fragment).collect();
let artifacts: Vec<&FunctionArtifact> = compiled.iter().map(|c| c.artifact()).collect();
let mut linked = link(
let linked = link(
&artifacts,
&LinkInputs::render_variant(d, v, group.clone()),
p,
@@ -957,10 +953,6 @@ impl Device {
mechanism: mechanism(&fact, self.profile()),
});
}
let depth = (&mut linked, &mut stages, &mut dependencies);
if let Some(r) = depth16_stage((pass(), v, d.fragment.is_none()), depth, p, m)? {
requirements = p.union_requirements(&requirements, &r);
}
let (mut graphics, requirements) =
graphics_requirements(requirements, &linked, &artifacts, p)?;
graphics.sample_mask = crate::pipeline::private_state::sample_mask(
@@ -1072,83 +1064,6 @@ impl Device {
}
}
/// State among a render pipeline's `dependencies` the depth variant `v` compiled it for
/// (`RuntimeFact::Depth16Pass` of `VariantKey::depth16_pass`, `RuntimeFact::Depth16Biased` of
/// `VariantKey::depth16_biased`, `RuntimeFact::Depth16BiasSide` of
/// `VariantKey::depth16_bias_raises`), and give one without a fragment
/// function (`fragmentless`) whose pass `pass` takes Metal's `Depth16Unorm` codes from its fragment
/// stage (`compile::depth16_codes`) the synthesized fragment stage
/// (`lower::stage_io::depth16::fragment_module`), as a fragment function would take them under
/// `LoweringInputs::depth16_codes`: its module after the `stages`, its push range and placement in
/// the `linked` layout and interface, and `RuntimeFact::Depth16Codes` among the `dependencies`.
/// It writes no color, so the pipeline's color state stays a fragment-less pipeline's. The module's
/// requirements, or `None` where the pipeline takes no such stage.
fn depth16_stage(
(pass, v, fragmentless): (FragmentPass<'_>, &VariantKey, bool),
(linked, stages, dependencies): (
&mut Linked,
&mut Vec<StageModule>,
&mut Vec<RuntimeDependency>,
),
p: &DeviceProfile,
m: &mut Meter,
) -> Result<Option<Requirements>, Error> {
use crate::lower::stage_io::depth16;
if let Some(depth16) = v.depth16_pass {
let fact = RuntimeFact::Depth16Pass { depth16 };
dependencies.push(RuntimeDependency::new(fact, mechanism(&fact, p)));
}
if v.depth16_biased {
let fact = RuntimeFact::Depth16Biased;
dependencies.push(RuntimeDependency::new(fact, mechanism(&fact, p)));
}
if let Some(raises) = v.depth16_bias_raises {
let fact = RuntimeFact::Depth16BiasSide { raises };
dependencies.push(RuntimeDependency::new(fact, mechanism(&fact, p)));
}
if !fragmentless || !crate::pipeline::compile::depth16_codes(pass, v, p) {
return Ok(None);
}
let module = depth16::fragment_module(v.depth16_bias_raises)?;
let stats = crate::spirv::verify::verify(&module, p, m)?;
let module = crate::spirv::serialize::serialize_for(module, p)?;
let words = crate::spirv::serialize::relocate(&module, &*linked)?;
stages.push(StageModule {
stage: vk::ShaderStage::FRAGMENT,
entry_point: ENTRY_NAME.to_owned(),
spirv: words.into(),
specialization: crate::pipeline::artifact::SpecializationLayout::default(),
required_subgroup_size: None,
stage_flags: vk::PipelineShaderStageCreateFlags::empty(),
reconvergence: crate::pipeline::artifact::Reconvergence::Guaranteed,
precision_notes: Vec::new(),
strategies: crate::pipeline::artifact::StrategyCensus::default(),
constant_blob: None,
rounded_colors: Vec::new(),
specialized_notes: Vec::new(),
half_bit_colors: Vec::new(),
own_pixel_textures: Vec::new(),
snapshot_textures: Vec::new(),
private_bytes: 0,
stats,
});
let placement = depth16::fragment_placement();
if let Some((offset, size)) = placement.push_range {
linked
.layout
.push_constants
.push(crate::pipeline::layout::PushConstantRange {
stages: vk::ShaderStageFlags::FRAGMENT,
offset,
size,
});
}
linked.interface.push.push(placement);
let fact = RuntimeFact::Depth16Codes { biased: true };
dependencies.push(RuntimeDependency::new(fact, mechanism(&fact, p)));
Ok(Some(module.requirements))
}
/// A render or mesh render pipeline's graphics state, and its stages' `requirements` with what
/// that state adds.
fn graphics_requirements(
@@ -1513,24 +1428,12 @@ fn compute_fields(d: &ComputePipelineDescriptor) -> String {
}
}
/// The pipeline key's fields of variant `v` past its stages' keys: the depth it was compiled for
/// (`VariantKey::depth16_pass`, `VariantKey::depth16_biased`, `VariantKey::depth16_bias_raises`),
/// which a pipeline without a fragment function keeps in no stage's key, and which every pipeline
/// states (`RuntimeFact::Depth16Pass`, `RuntimeFact::Depth16Biased`,
/// `RuntimeFact::Depth16BiasSide`), and its color group past the first (`VariantKey::color_group`),
/// whose variant of a pipeline without a fragment function has no stage of its own. Empty for
/// every other variant, so a pipeline keeps its key.
/// The pipeline key's fields of variant `v` past its stages' keys: its color group past the first
/// (`VariantKey::color_group`), whose variant of a pipeline without a fragment function has no
/// stage of its own, and its emulated mesh function's synthesized vertex stage. Empty for every
/// other variant, so a pipeline keeps its key.
fn variant_fields(v: &VariantKey) -> String {
let mut fields = match v.depth16_pass {
Some(depth16) => format!(" depth16_pass {depth16}"),
None => String::new(),
};
if v.depth16_biased {
fields.push_str(" depth16_biased");
}
if let Some(raises) = v.depth16_bias_raises {
fields.push_str(&format!(" depth16_bias_raises {raises}"));
}
let mut fields = String::new();
// The group a pipeline without a fragment function keeps in no stage's key.
if v.color_group != 0 {
fields.push_str(&format!(" color_group {}", v.color_group));
@@ -1578,12 +1481,6 @@ fn stage_module(c: &CompiledFunction, linked: &Linked, i: usize) -> Result<Stage
if a.subgroup.full_subgroups {
stage_flags |= vk::PipelineShaderStageCreateFlags::REQUIRE_FULL_SUBGROUPS;
}
// A fragment function that selects an attachment's rules rounds it, and keeps the notes of
// the rules, as the pipeline's attachment selects them.
let rules = linked
.graphics
.as_ref()
.map_or(&[][..], |g| &g.color_write_rules[..]);
// A `half` output of a module without fast math keeps its note where its attachment blends.
let colors = linked
.graphics
@@ -1594,13 +1491,8 @@ fn stage_module(c: &CompiledFunction, linked: &Linked, i: usize) -> Result<Stage
.graphics
.as_ref()
.is_some_and(|g| g.alpha_to_coverage);
let Some((precision_notes, rounded_colors)) =
crate::pipeline::color_writes::pipeline_writes(a, rules, colors, coverage)
else {
return Err(invariant(
"link gave no rule word to a selected color attachment",
));
};
let (precision_notes, rounded_colors) =
crate::pipeline::color_writes::pipeline_writes(a, colors, coverage);
Ok(StageModule {
stage: a.interface.vk_stage(),
entry_point: ENTRY_NAME.to_owned(),
@@ -480,13 +480,6 @@ pub fn function_key(
h.bytes(b"instanced-attributes")
.bytes(format!("{:?}", inputs.instanced_attributes).as_bytes());
}
// Appended only when set: a fragment function of any other pipeline or profile keeps its key.
if inputs.depth16_codes {
h.bytes(b"depth16-codes");
}
if let Some(raises) = inputs.depth16_bias_raises {
h.bytes(b"depth16-bias-raises").u64(u64::from(raises));
}
// Appended only when set, in its derived `Debug` form (integers), as `dropped_colors` is.
if let Some(group) = &inputs.color_group {
h.bytes(b"color-group")
@@ -758,8 +758,6 @@ fn the_inputs_encoding_is_the_earlier_derived_debug() {
.replace(", anisotropic_samplers: {}", "")
.replace(", uniform_varyings: {}", "")
.replace(", instanced_attributes: {}", "")
.replace(", depth16_codes: false", "")
.replace(", depth16_bias_raises: None", "")
.replace(", color_group: None", "")
.replace(", object_payload: None", "")
.replace(", tessellation: None", ""),
@@ -1991,8 +1989,8 @@ fn a_multisampled_framebuffer_fetch_reads_each_samples_own_color() {
/// color attachments 0 and 2, not 1: on `lavapipe` attachment 1 is masked and the feature required
/// (and enabled); on `vk12-floor`, without the feature, every element is identical, an absent
/// attachment 1's included, and a written attachment that blends differently is refused typed. A
/// blend of one and zero, added, of an attachment the function rounds to Metal's codes takes no
/// Vulkan blend, so it differs from no other element.
/// blend of one and zero, added, of an attachment whose channels convert by a rule other than the
/// device's (`StageIo::color_writes`) takes no Vulkan blend, so it differs from no other element.
#[test]
fn a_render_pipeline_requires_the_blend_features_its_attachments_need() {
use crate::device::requirements::VkFeature;
-27
View File
@@ -731,33 +731,6 @@ pub enum RuntimeFact {
/// no `PrecisionNote::DeviceNanEncoding` for these writes: the consumer announces it at a
/// draw or dispatch whose heap holds such a texture.
HeapHalfTexelWrites { stage: Stage, packed: bool },
/// The fragment stage writes each depth of a `Depth16Unorm` attachment as Metal's code
/// (`LoweringInputs::depth16_codes`), so the device stores Metal's codes without its own
/// conversion deciding them. Where `biased`, it stores the depth Metal stores for each fragment,
/// its depth bias included: it reads the draw's bias from `PushField::DepthBias`, which the
/// binder writes from `BindState::depth_bias`, and adds it to `FragCoord.z` itself, so the
/// consumer records the draw's Vulkan depth bias as zero. Otherwise the function returns its
/// own depth, which Metal does not bias.
Depth16Codes { biased: bool },
/// The render pipeline was compiled under `VariantKey::depth16_pass` holding `depth16`: for a
/// render pass whose depth is (`depth16`) or is not `Depth16Unorm`, where its own depth format
/// says otherwise, so its fragment stage takes Metal's 16-bit codes by the pass's depth
/// (`LoweringInputs::depth16_codes`). Its plans state the variant the shape asks for
/// (`BindShape::depth16_pass`).
Depth16Pass { depth16: bool },
/// The render pipeline was compiled under `VariantKey::depth16_biased`: for a draw that biases
/// a `Depth16Unorm` depth, on a profile whose unbiased depths the device stores as Metal's
/// codes but not its biased ones (`DriverDeviation::MetalDepth16Stores` without
/// `DriverDeviation::MetalDepth16BiasedStores`), so its fragment stage adds the bias and
/// writes Metal's code itself (`LoweringInputs::depth16_codes`). Its plans state the variant
/// the shape asks for (`BindShape::depth16_biased`).
Depth16Biased,
/// The render pipeline was compiled under `VariantKey::depth16_bias_raises` holding `raises`:
/// for a draw whose bias of a `Depth16Unorm` depth the runtime proved never lowers the depth
/// (`raises`) or never raises it, so a fragment stage that adds the bias itself declares that
/// side (`LoweringInputs::depth16_bias_raises`). Its plans state the variant the shape asks for
/// (`BindShape::depth16_bias_raises`).
Depth16BiasSide { raises: bool },
/// The render pipeline draws through synthesized geometry stages, one per topology class, of
/// which a draw runs its class's (`RenderPipeline::runs_stage`): its fragment function reads
/// `[[barycentric_coord]]` on a device without `fragmentShaderBarycentric` (`weights`), or its
+1 -9
View File
@@ -269,12 +269,6 @@ pub struct GraphicsState {
/// [`ShaderTestsUse`] for the consumer contract.
#[cfg_attr(feature = "serde", serde(default))]
pub shader_tests: Option<ShaderTestsUse>,
/// The rule word of each color attachment whose channels' rules the fragment function
/// selects at the draw (`StageIo::selected_colors`), by color index, sorted: each channel's
/// code of the rule this pipeline's attachment takes (`pipeline::color_writes::rule_word`),
/// which the binder writes to the function's `PushField::ColorWriteRule` of the attachment.
#[cfg_attr(feature = "serde", serde(default))]
pub color_write_rules: Vec<(u32, u32)>,
/// The fragment function reads textures through snapshots (`VariantKey::snapshot_textures`):
/// each draw of the pipeline is drawn twice in its subpass, the texture's attachment in
/// `VK_IMAGE_LAYOUT_ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT`, first with every color write mask 0,
@@ -287,8 +281,7 @@ pub struct GraphicsState {
/// The group of the pipeline's color attachments this variant draws
/// (`VariantKey::color_group`), where the device draws them in groups
/// ([`ColorGroup`](crate::pipeline::ColorGroup)): every color-indexed part of the state
/// (`color_attachments`, `input_attachments`, `storage_attachments`, `color_write_rules`
/// among them) indexes the group's attachments by location, Metal's attachment
/// (`color_attachments`, `input_attachments`, `storage_attachments` among them) indexes the group's attachments by location, Metal's attachment
/// `colors()[l]` at location `l`, and the fragment stage writes those alone. Each draw of the
/// pipeline is a draw of every group's variant, in a pass of that group's attachments; the
/// vertex stage is the same module in every variant, and the fragment stage's `FragDepth`,
@@ -433,7 +426,6 @@ impl GraphicsState {
color_outputs: 0,
sample_mask: None,
shader_tests: None,
color_write_rules: Vec::new(),
snapshot_reads: false,
color_group: None,
logic_op: None,
@@ -8,10 +8,11 @@
//! - **Color attachments**: the format mapping for `ColorAttachment` (plus
//! `ColorAttachmentBlend` when blending), the write mask, and the blend state; at most
//! `maxColorAttachments` of them. A blend of factors one and zero, added, for color and alpha,
//! of an attachment the fragment function rounds to Metal's codes (`StageIo::rounded_colors`), or
//! writes as a half's bits (`StageIo::half_bit_colors`), takes no Vulkan blend: the function
//! writes what Metal's blend stores, which a device's blend could still change (x86 lavapipe adds
//! the clear's `+0` to a `-0` source of an `R16Float` attachment, Metal keeps `-0`). An
//! of an attachment whose format converts the fragment function's output
//! (`StageIo::color_writes`), or that the function rounds (`StageIo::rounded_colors`) or writes
//! as a half's bits (`StageIo::half_bit_colors`), takes no Vulkan blend: Metal's blend stores the
//! output as written, as no blend does, which a device's blend could still change (x86 lavapipe
//! adds the clear's `+0` to a `-0` source of an `R16Float` attachment, Metal keeps `-0`). An
//! attachment that no first (index 0) output of the fragment function names (every attachment of
//! a pipeline without a fragment function) gets an empty write mask, so the draw leaves it
//! unmodified. That is what Metal does where measured: an unblended attachment the function reads
@@ -347,22 +348,6 @@ pub fn graphics_state(
_ => None,
})
.collect();
// The rule word of each attachment whose rules the fragment function selects at the draw.
let color_write_rules = match fs {
Some(f) => color_writes::rule_words(
&f.io,
&r.color_attachments,
(r.alpha_to_coverage, r.texture_write_rounding_mode),
p,
)?,
None => Vec::new(),
};
let selected_rounds = |index: u32| {
let word = color_write_rules.iter().find(|(a, _)| *a == index);
fs.and_then(|f| f.io.selected_colors.get(&index))
.zip(word)
.is_some_and(|(sel, (_, word))| color_writes::selected_rounds(sel, *word))
};
let mut color_attachments = Vec::with_capacity(used as usize);
for (index, a) in r.color_attachments.iter().take(used as usize).enumerate() {
color_attachments.push(match a {
@@ -400,19 +385,26 @@ pub fn graphics_state(
blend: None,
});
}
// The fragment function writes what Metal's blend of one and zero stores,
// so the attachment takes no Vulkan blend, nor the format's blend support:
// one it rounds, and one it writes as a half's bits. But not a 16-bit float
// attachment's from a module without fast math, whose blend Metal computes
// keeping the destination's product by zero: that one blends, announced
// (`color_writes::keeps_zero`).
let rounded = fs.is_some_and(|f| {
f.io.rounded_colors.contains(&(index as u32))
|| f.io.half_bit_colors.contains(&(index as u32))
}) || selected_rounds(index as u32);
// Metal's blend of one and zero stores the output as written, as no blend
// does, so an attachment whose format converts the output (its channels
// take a rule of Metal's, `StageIo::color_writes`), or one the function
// rounds or writes as a half's bits, takes no Vulkan blend there, nor the
// format's blend support. But not a 16-bit float attachment's from a module
// without fast math, whose blend Metal computes keeping the destination's
// product by zero: that one blends, announced (`color_writes::keeps_zero`).
let stored = fs.is_some_and(|f| {
let color = index as u32;
f.io.rounded_colors.contains(&color)
|| f.io.half_bit_colors.contains(&color)
|| f.io.color_writes.get(&color).is_some_and(|rules| {
rules.iter().flatten().any(|r| {
*r != crate::pipeline::lower_inputs::ChannelWrite::Device
})
})
});
let keeps_zero =
fs.is_some_and(|f| color_writes::keeps_zero(&f.io, index as u32, a));
let replaced = rounded && color_writes::replaces(a) && !keeps_zero;
let replaced = stored && color_writes::replaces(a) && !keeps_zero;
// An extended-range attachment whose blend the function computes over its
// input attachment takes no Vulkan blend, and the function's write stores
// every raw component (none where it keeps every channel).
@@ -703,7 +695,6 @@ pub fn graphics_state(
sample_mask: None,
// The fragment stage's facts decide it (`link::shader_tests`).
shader_tests: None,
color_write_rules,
snapshot_reads,
color_group: r.color_group.clone(),
// The pipeline's private logic operation, once compile decided it
@@ -27,51 +27,29 @@ fn link(
crate::pipeline::link::link(&all, inputs, p)
}
/// `fragment` with the color writes a render pipeline of `inputs` on `p` compiles it under, an
/// attachment whose rules it selects (`ChannelWrite::Selected`) recorded as a four-lane output's
/// (`StageIo::selected_colors`), which rounds an 8-bit unorm or a half-float channel where
/// `fragment` lists the attachment as rounded and nothing otherwise.
/// `fragment` with the color writes a render pipeline of `inputs` on `p` compiles it under.
fn compiled_for(
fragment: &FunctionArtifact,
inputs: &LinkInputs,
p: &DeviceProfile,
) -> FunctionArtifact {
use crate::pipeline::color_writes::{HALF_CODE, UNORM8_CODE};
use crate::pipeline::lower_inputs::ChannelWrite;
let mut out = fragment.clone();
if let (LinkInputs::Render(r), Stage::Fragment) = (inputs, fragment.interface.stage) {
let io = &mut out.interface.io;
io.color_writes = crate::pipeline::color_writes::wanted(
out.interface.io.color_writes = crate::pipeline::color_writes::wanted(
fragment,
&r.color_attachments,
(r.alpha_to_coverage, r.texture_write_rounding_mode),
p,
);
io.selected_colors = io
.color_writes
.iter()
.filter(|(_, rules)| rules.contains(&Some(ChannelWrite::Selected)))
.map(|(&a, _)| {
let rounds = fragment.interface.io.rounded_colors.contains(&a);
let write = crate::pipeline::stage_io::SelectedWrite {
lanes: 4,
rounds: match rounds {
true => 1 << UNORM8_CODE | 1 << HALF_CODE,
false => 0,
},
nans: 0,
};
(a, write)
})
.collect();
}
out
}
/// A blend of one and zero, added, of an attachment the fragment function rounds takes no Vulkan
/// blend, since the function writes what Metal's blend stores, nor the format's blend support
/// (lavapipe blends no snorm format); another blend keeps the device's, and so does a (one, zero)
/// blend of an attachment the function does not round.
/// A blend of one and zero, added, of an attachment whose format converts the fragment function's
/// output (its color writes name a rule), or that the function rounds, takes no Vulkan blend, since
/// Metal's blend stores the output as written, nor the format's blend support (lavapipe blends no
/// snorm format); another blend keeps the device's, and so does a (one, zero) blend of an
/// attachment whose format converts nothing (`RGBA32Float`) and the function does not round.
#[test]
fn a_rounded_one_zero_blend_takes_no_vulkan_blend() {
use crate::device::requirements::FormatUsage;
@@ -100,7 +78,10 @@ fn a_rounded_one_zero_blend_takes_no_vulkan_blend() {
};
assert_eq!(blend_of(&rounding, replace), None);
assert!(blend_of(&rounding, over).is_some());
assert!(blend_of(&fa, replace).is_some());
assert_eq!(blend_of(&fa, replace), None);
let mut float = ColorAttachmentDescriptor::new(PixelFormat::RGBA32Float);
float.blending_enabled = true;
assert!(blend_of(&fa, float).is_some());
let snorm = vk::Format::R8G8B8A8_SNORM;
assert!(!p.supports_format(snorm, FormatUsage::ColorAttachmentBlend));
let mut replace_snorm = ColorAttachmentDescriptor::new(PixelFormat::RGBA8Snorm);
@@ -149,13 +130,7 @@ fn a_safe_one_zero_blend_of_a_sixteen_bit_float_attachment_blends() {
.expect("links")
.graphics
.expect("graphics");
let (notes, _) = pipeline_writes(
&fragment,
&g.color_write_rules,
&g.color_attachments,
g.alpha_to_coverage,
)
.expect("the rule words");
let (notes, _) = pipeline_writes(&fragment, &g.color_attachments, g.alpha_to_coverage);
let noted = notes.contains(&crate::pipeline::PrecisionNote::HalfOutputPrecision);
(
g.color_attachments[0]
@@ -179,18 +154,13 @@ fn a_safe_one_zero_blend_of_a_sixteen_bit_float_attachment_blends() {
}
/// A fragment function links only under the color writes its pipeline gives the attachments it
/// writes. On lavapipe and RADV a `float4` output to an `RGBA8Unorm` attachment rounds by the unorm
/// writes. On lavapipe and RADV a `float4` output to an `RGBA8Unorm` attachment takes the unorm
/// rule, blended with (one, zero) too; under another blend, and for alpha-to-coverage's alpha, the
/// channel is the device's; an `RGBA32Float` attachment takes no entry. Where a channel so rounds,
/// the attachment selects its rules at the draw (`ChannelWrite::Selected`), by the rule word link
/// gives it: `0x2222` for the four unorm channels, `0x1222` with alpha-to-coverage's alpha,
/// `0x3333` for an `RGBA16Float` one's half-float channels, so a fragment compiled for one such
/// attachment links into a pipeline of another; one all of whose channels are the device's selects
/// nothing. A fragment compiled under the channels' own rules (`color_writes::exact_writes`) links
/// too, into a pipeline of those rules. A fragment compiled without the map, or for a format whose
/// rules it does not select (`RGBA16Unorm`), is `NeedsInput(ColorWrites)`. On MoltenVK, which
/// converts as Metal does, the map names only the half-float channels, blended or not, and selects
/// nothing.
/// channel is the device's; an `RGBA16Float` attachment takes the half-float rule, and an
/// `RGBA32Float` one no entry. A fragment compiled for one attachment's map links into a pipeline
/// of that map alone: compiled for another format, or without the map, it is
/// `NeedsInput(ColorWrites)`. On MoltenVK, which converts as Metal does, the map names only the
/// half-float channels, blended or not.
#[test]
fn color_writes_are_the_pipelines() {
use crate::error::RuntimeInput;
@@ -229,70 +199,43 @@ fn color_writes_are_the_pipelines() {
);
for stem in ["lavapipe", "amd-rdna3-radv"] {
let p = profile(stem);
let writes = |inputs: &LinkInputs, exact: bool| match inputs {
let writes = |inputs: &LinkInputs| match inputs {
LinkInputs::Render(r) => {
let colors = &r.color_attachments;
let rounding = (r.alpha_to_coverage, r.texture_write_rounding_mode);
match exact {
true => crate::pipeline::color_writes::exact_writes([0], colors, rounding, &p),
false => crate::pipeline::color_writes::wanted(&fa, colors, rounding, &p),
}
crate::pipeline::color_writes::wanted(&fa, colors, rounding, &p)
}
_ => unreachable!(),
};
let device = Some(C::Device);
let half = Some(crate::pipeline::color_writes::HALF);
let selected = Some([Some(C::Selected); 4]);
let coverage = render(
ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm),
true,
);
for (inputs, exact, want, word) in [
(&plain, Some([unorm8; 4]), selected, Some(0x2222)),
(
&render(replace, false),
Some([unorm8; 4]),
selected,
Some(0x2222),
),
(&render(blend, false), Some([device; 4]), None, None),
(
&coverage,
Some([unorm8, unorm8, unorm8, device]),
selected,
Some(0x1222),
),
(&half_float, Some([half; 4]), selected, Some(0x3333)),
(&float, None, None, None),
for (inputs, want) in [
(&plain, Some([unorm8; 4])),
(&render(replace, false), Some([unorm8; 4])),
(&render(blend, false), Some([device; 4])),
(&coverage, Some([unorm8, unorm8, unorm8, device])),
(&half_float, Some([half; 4])),
(&float, None),
] {
assert_eq!(writes(inputs, true).get(&0).copied(), exact, "{stem}");
let want = want.or(exact);
assert_eq!(writes(inputs, false).get(&0).copied(), want, "{stem}");
let l = link(&[&va, &fa], inputs, &p).unwrap_or_else(|e| panic!("{stem}: {e}"));
let words = &l.graphics.as_ref().expect("graphics").color_write_rules;
assert_eq!(writes(inputs).get(&0).copied(), want, "{stem}");
link(&[&va, &fa], inputs, &p).unwrap_or_else(|e| panic!("{stem}: {e}"));
}
let needs = Err(Error::NeedsInput(RuntimeInput::ColorWrites));
// Compiled for one attachment's map, linked into another's pipeline.
let for_plain = compiled_for(&fa, &plain, &p);
crate::pipeline::link::link(&[&va, &for_plain], &plain, &p)
.unwrap_or_else(|e| panic!("{stem}: {e}"));
for inputs in [&half_float, &coverage] {
assert_eq!(
words.clone(),
Vec::from_iter(word.map(|w| (0, w))),
crate::pipeline::link::link(&[&va, &for_plain], inputs, &p).map(|_| ()),
needs,
"{stem}"
);
}
// Compiled for one attachment whose rules it selects, linked into another's pipeline.
let for_plain = compiled_for(&fa, &plain, &p);
for inputs in [&half_float, &coverage] {
crate::pipeline::link::link(&[&va, &for_plain], inputs, &p)
.unwrap_or_else(|e| panic!("{stem}: {e}"));
}
// Compiled under the channels' own rules, it links into the pipeline of those rules alone.
let mut own = fa.clone();
own.interface.io.color_writes = writes(&plain, true);
crate::pipeline::link::link(&[&va, &own], &plain, &p)
.unwrap_or_else(|e| panic!("{stem}: {e}"));
assert_eq!(
crate::pipeline::link::link(&[&va, &own], &half_float, &p).map(|_| ()),
Err(Error::NeedsInput(RuntimeInput::ColorWrites)),
"{stem}"
);
let needs = Err(Error::NeedsInput(RuntimeInput::ColorWrites));
// Compiled without the map, and for another format.
assert_eq!(
crate::pipeline::link::link(&[&va, &fa], &plain, &p).map(|_| ()),
@@ -416,7 +359,7 @@ fn half_colors_round_to_nearest_even_under_mode_two() {
_ => unreachable!(),
};
// The default mode's own rule of the alpha the coverage reads: the output as written.
let unstored = crate::pipeline::color_writes::exact_writes(
let unstored = crate::pipeline::color_writes::color_writes(
[0],
&[Some(rgb)],
(true, Mode::TowardZero),
@@ -442,13 +385,7 @@ fn half_colors_round_to_nearest_even_under_mode_two() {
.graphics
.expect("graphics");
assert_eq!(g.alpha_to_coverage, coverage, "{stem} {c:?}");
let (notes, _) = pipeline_writes(
&fragment,
&g.color_write_rules,
&g.color_attachments,
g.alpha_to_coverage,
)
.expect("the rule words");
let (notes, _) = pipeline_writes(&fragment, &g.color_attachments, g.alpha_to_coverage);
assert_eq!(
notes.contains(&PrecisionNote::CoverageReadsRoundedAlpha),
coverage && want[3] == nearest,
@@ -338,18 +338,19 @@ pub struct LoweringInputs {
pub amplification_draws: Option<AmplificationDraws>,
/// How each color attachment the fragment function writes takes each channel of its float
/// output (red, green, blue, alpha; `None` for a channel the format lacks), where the
/// attachment's format converts it (a normalized, sRGB or half-float format) on a device not
/// measured to convert as Metal does (without `VkProperty::MetalColorWrites`): a
/// [`ChannelWrite`] rule where the function rounds the channel by Metal's rule and writes the
/// `f32` nearest the code's exact value, which the device stores as that code;
/// [`ChannelWrite::Device`] where the device's conversion stays (blending other than factors
/// one and zero, the alpha alpha-to-coverage reads, or a format whose conversion Metal was
/// not measured with), a near-equivalent the function records as
/// `PrecisionNote::DeviceColorConversion`. `Device::compile_render_pipeline` sets it for a
/// `Function` fragment stage from the pipeline's color attachments, blend states and
/// alpha-to-coverage, and a fragment compiled on its own for such a pipeline compiles under the
/// same map: link refuses one compiled under another as `NeedsInput(ColorWrites)`. Empty on a
/// device with the property and for any other function.
/// attachment's format converts it (a normalized, sRGB or small float format): Metal's
/// [`ChannelWrite`] rule where the attachment stores the output as written, which the device's
/// conversion stores, the function recording `PrecisionNote::DeviceColorConversion` where the
/// device is not measured to convert it as Metal does; [`ChannelWrite::Device`] where the
/// device's conversion of another value stays (blending other than factors one and zero, the
/// alpha alpha-to-coverage reads, or a format whose conversion Metal was not measured with),
/// recorded alike; and a half-float channel's rule under
/// `TextureWriteRoundingMode::NearestEven`, which the function rounds itself. On a device that
/// stores Metal's codes (`VkProperty::MetalColorWrites`) only the half-float channels.
/// `Device::compile_render_pipeline` sets it for a `Function` fragment stage from the
/// pipeline's color attachments, blend states and alpha-to-coverage, and a fragment compiled
/// on its own for such a pipeline compiles under the same map: link refuses one compiled under
/// another as `NeedsInput(ColorWrites)`. Empty for any other function.
#[cfg_attr(feature = "serde", serde(default))]
pub color_writes: BTreeMap<u32, [Option<ChannelWrite>; 4]>,
/// The varyings the fragment function's mesh render pipeline's mesh function writes per
@@ -787,36 +788,6 @@ pub struct LoweringInputs {
/// projection). Empty for any other function.
#[cfg_attr(feature = "serde", serde(default))]
pub instanced_attributes: BTreeSet<u32>,
/// The fragment function stores Metal's `Depth16Unorm` codes itself
/// (`lower::stage_io::depth16`): the depth its draws render against is `Depth16Unorm` (its
/// pipeline's depth attachment, or the pass's, `VariantKey::depth16_pass`) and its pipeline
/// rasterizes one sample, on a profile without `DriverDeviation::MetalDepth16Stores`, or,
/// under `VariantKey::depth16_biased` (a draw that biases the depth), without
/// `DriverDeviation::MetalDepth16BiasedStores`, so the device's own conversion of a depth may
/// store another code near a code's midpoint. Each
/// depth it writes is the `float` nearest Metal's code over 65535, which every conversion that
/// rounds to nearest stores as that code: the depth it returns, clamped as Metal stores it
/// (no `DepthGreater` or `DepthLess` mode, which the rounding can break), and, for a function
/// that returns none, the depth Metal stores for the fragment under the draw's depth bias
/// (`PushField::DepthBias`, `RuntimeFact::Depth16Codes`), whose hardware bias the consumer
/// records as zero. A function that declares or takes early fragment tests, or runs its
/// draw's tests itself (`shader_tests`), compiles as without it: the device's tests take its
/// depth before it runs; so does one that returns no depth and reads its position's depth,
/// which the draw's bias may reach on Metal (unmeasured). `Device::compile_render_pipeline`
/// sets it for a `Function` fragment stage from the descriptor, the variant and the profile;
/// any other function compiles as without it.
#[cfg_attr(feature = "serde", serde(default))]
pub depth16_codes: bool,
/// Under `depth16_codes`, the side of the draw's bias where the runtime proved it
/// (`VariantKey::depth16_bias_raises`): `Some(true)` where Metal's biased depth is never below
/// the fragment's own, `Some(false)` where it is never above. A function that stores the
/// depth at entry declares it (`DepthGreater`, `DepthLess`) and bounds the depth it writes by
/// `FragCoord.z` on that side, so the device may test the depth before the stage runs where its
/// test compares that way (`lower::stage_io::depth16::side_bounded`, whose docs prove the bound
/// changes no code). `None` elsewhere, and for a function that returns its depth or stores
/// none at entry.
#[cfg_attr(feature = "serde", serde(default))]
pub depth16_bias_raises: Option<bool>,
/// The group of its render pipeline's color attachments a fragment function writes
/// ([`ColorGroup`]), where the pipeline has more color attachments than the device draws to at
/// once, or one at an index at or past that count: the function writes the group's colors at
@@ -1149,15 +1120,6 @@ pub enum ChannelWrite {
/// The channel's bits.
bits: u8,
},
/// One of the selectable rules (none, the device's conversion, an 8-bit unorm channel's, a
/// half-float channel's), chosen at each draw by the attachment's `PushField::ColorWriteRule`
/// word, which the pipeline's attachment decides (`GraphicsState::color_write_rules`): the
/// function computes each rule's value and selects one, so one module serves every
/// attachment whose channels take such rules, whatever its format or blend. Where the device
/// does not store Metal's codes itself, an attachment whose channels each take such a rule, one
/// of them a rounding (`Unorm { bits: 8 }` or a half's `FloatTowardZero`), takes `Selected` on
/// every channel of its entry.
Selected,
}
/// What a vertex function compiled for draws of one amplification each writes beyond its own
@@ -1455,7 +1417,8 @@ pub enum StorageImageClass {
/// [`SwizzleBgra`]: StorageImageClass::SwizzleBgra
SrgbEncodeBgra,
/// An `ARGB8Unorm` image (alpha in byte 0, then red, green, and blue) viewed as
/// `R8G8B8A8_UNORM`: the shader rotates the channels.
/// `R8G8B8A8_UNORM`: the shader rotates the channels, and the device converts a written
/// value.
RotateArgb,
/// An `A8Unorm` texture held in `R8_UNORM` (`metal::format::FormatEmulation::AlphaInRed`):
/// a read is the byte as alpha, `(0, 0, 0, r)`, and a write stores the texel's alpha, as
@@ -1463,14 +1426,9 @@ pub enum StorageImageClass {
/// texels and `read_write` access).
AlphaInRed,
/// A half-float image (`R16Float`, `RG16Float`, `RGBA16Float`) written by a device not
/// measured to round a `float` texel as Metal does: the shader rounds each written `float`
/// channel toward zero to the `half` Metal stores (a finite value past 65504 to 65504, an
/// infinity kept, a NaN to `0x7fc00000`), which the device then stores exactly. A `half`
/// texel is written as it is, and reads are `Identity`'s.
HalfTowardZero,
/// A half-float image written by a device measured to round a `float` texel as Metal does
/// but not to store every NaN as Metal's `0x7e00`: the shader writes a `float` channel's NaN
/// as `0x7fc00000`, every other value as computed. Reads are `Identity`'s.
/// measured to store every NaN as Metal's `0x7e00`: the shader writes a `float` channel's NaN
/// as `0x7fc00000`, every other value as computed, which the device's conversion rounds. A
/// `half` texel is written as it is, and reads are `Identity`'s.
HalfQuietNan,
/// A 4:4:4 two-plane YCbCr texture a slot only writes, through an `R32G32B32A32_UINT` image
/// of the texture's own (the consumer's write shadow): the shader writes each texel as the
@@ -1484,13 +1442,6 @@ pub enum StorageImageClass {
/// as Metal does; RADV and NVIDIA keep another NaN's payload bits. A `half` texel is written
/// as it is, and reads are `Identity`'s.
SmallFloatQuietNan,
/// A unorm image with a 1-bit alpha (`A1BGR5Unorm`, `BGR5A1Unorm`) written on a device
/// measured to store every other normalized channel as Metal does
/// (`DriverDeviation::MetalNormStorageWrites`) but to round a 1-bit channel's half up: the
/// shader writes a `float` or `half` texel's alpha as `1.0` above one half and `0.0`
/// elsewhere (a NaN 0), the code Metal stores, every other channel as computed. Reads are
/// `Identity`'s.
OneBitAlpha,
/// A half-float image (`R16Float`, `RG16Float`, `RGBA16Float`) a slot writes, and may read,
/// on a device not measured to store a written `half`'s NaN as its bits
/// (`DriverDeviation::MetalHalfTexelWrites`), viewed through its unsigned integer alias of
+4 -27
View File
@@ -196,9 +196,10 @@ pub struct StageIo {
/// pipeline's (`NeedsInput(ColorWrites)`).
#[cfg_attr(feature = "serde", serde(default))]
pub color_writes: BTreeMap<u32, [Option<ChannelWrite>; 4]>,
/// The attachments among `color_writes` whose float writes the function rounds to Metal's
/// codes in the shader, sorted: those with a channel it rounds by Metal's rule rather than
/// leaving to the device (`StageModule::rounded_colors`).
/// The attachments among `color_writes` whose float writes the function rounds in the shader,
/// sorted: those with a half-float channel under `TextureWriteRoundingMode::NearestEven`
/// (`color_writes::HALF_NEAREST`), which no device's conversion gives
/// (`StageModule::rounded_colors`).
#[cfg_attr(feature = "serde", serde(default))]
pub rounded_colors: Vec<u32>,
/// The attachments among `color_writes` whose output the function writes as the bits of the
@@ -345,13 +346,6 @@ pub struct StageIo {
/// (`InvalidDescriptor(VertexAttribute)`). Empty for every other function.
#[cfg_attr(feature = "serde", serde(default))]
pub instanced_attributes: Vec<u32>,
/// The attachments among `color_writes` whose rules the draw selects
/// (`ChannelWrite::Selected`), by color index, with what the function's write does under each
/// code of the attachment's rule word (`PushField::ColorWriteRule`): link derives the word
/// from the pipeline's attachment (`GraphicsState::color_write_rules`), and from it whether
/// the write rounds in the shader and the notes it keeps.
#[cfg_attr(feature = "serde", serde(default))]
pub selected_colors: BTreeMap<u32, SelectedWrite>,
/// The attachments a `half` color output of a module compiled without fast math
/// (`air.compile.fast_math_disable`, safe or relaxed math) reaches, by color index, sorted.
/// Metal stores there the `half` the function returns, blended into a 16-bit float format with
@@ -405,23 +399,6 @@ pub struct StageIo {
pub color_group: Option<crate::pipeline::lower_inputs::ColorGroup>,
}
/// What a fragment function's write of a color attachment whose rules the draw selects does
/// under each code of the attachment's rule word (`StageIo::selected_colors`): bit `c` of a mask
/// is code `c` (`pipeline::color_writes`'s codes: no rule, the device's conversion, an 8-bit
/// unorm channel's, a half-float channel's).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SelectedWrite {
/// The lanes of the output the rules take, the first `lanes` channels' codes.
pub lanes: u8,
/// A lane of code `c` rounds the output to Metal's code in the shader.
pub rounds: u8,
/// A lane of code `c` stores a NaN as the device encodes it
/// (`PrecisionNote::DeviceNanEncoding`).
pub nans: u8,
}
/// The samplers a fragment function makes depth comparisons through ([`StageIo::depth_compares`]),
/// as bits of Metal's `fragmentDepthCompareClampMask`: bit `s` for `[[sampler(s)]]` (`s` below
/// 16, Metal's sampler slots), bit 31 for a constexpr sampler, and bit 30
-20
View File
@@ -374,12 +374,6 @@ pub enum SyntheticBinding {
/// the post-tessellation vertex function reads (`lower::tessellation::work`). Declared with
/// the vertex stage's symbols.
TessellationRecords,
/// A fragment function's sRGB color table: a read-only uniform or storage buffer (as the
/// binding's descriptor type says) holding
/// [`color_write_table`](crate::bind::color_write_table)'s bytes, from which a function that
/// writes a float to an sRGB color attachment reads the linear value of the byte Metal
/// stores.
ColorWriteTable,
/// The stand-in of the render pass's depth attachment a fragment function that runs the
/// draw's depth test itself tests and writes (`GraphicsState::shader_tests`): a coherent
/// `R32f` storage image holding pixel `(x, y)`'s depth at texel `(x, y)` (its samples as the
@@ -1144,25 +1138,11 @@ pub enum PushField {
/// signedness, as Metal stores it (`RuntimeFact::StorageTextureIntegerChannels`, a slot whose
/// storage choice declares no format).
TextureIntegerChannels(SlotRef),
/// The rule word of the color attachment of this index for a fragment function that selects
/// its channels' rules at the draw (`ChannelWrite::Selected`, `StageIo::selected_colors`): one
/// `u32` holding each channel's code (`pipeline::color_writes::rule_word`: none, the device's
/// conversion, an 8-bit unorm channel's, a half-float channel's), which the pipeline's
/// attachment decides (`GraphicsState::color_write_rules`), so every attachment format and
/// blend whose channels take those rules shares one module.
ColorWriteRule(u32),
/// The render encoder's blend color (`setBlendColorRed:green:blue:alpha:`) for a fragment
/// function that blends a 16-bit float attachment in the shader under a blend that reads it
/// (a fetched attachment's blend): one `uvec4` holding the four `f32`s' bits as the encoder
/// set them (`BindState::blend_color`), which the function rounds to `half`.
HalfBlendColor,
/// The draw's depth bias for a fragment stage that stores Metal's `Depth16Unorm` codes itself
/// (`RuntimeFact::Depth16Codes`): one `uvec4` holding the bits of three `f32`s and a zero
/// word, `[constant, slope, clamp, 0]` (`BindState::depth_bias`). The constant is Metal's
/// units of 1/65535 as a depth (`metal::state::depth16_bias`), the slope and clamp factors
/// Metal's; all three are 0 for a draw its bias does not touch (points, lines, a bias the
/// draw's viewports take).
DepthBias,
/// The render encoder's alpha test reference (`setAlphaTestReferenceValue:`) for a fragment
/// function compiled under `LoweringInputs::alpha_test`: one `u32`, the reference's 8-bit
/// unorm code as Metal's alpha test compares it (`bind::alpha_test_code` of
@@ -250,11 +250,6 @@ fn states() -> Vec<BindState> {
s.extended_shadows.insert(0);
}),
with(|s| s.fragment_tests = FragmentTests::Pass),
with(|s| s.depth16_pass = Some(false)),
with(|s| s.depth16_pass = Some(true)),
with(|s| s.depth16_biased = true),
with(|s| s.depth16_bias_raises = Some(true)),
with(|s| s.depth16_bias_raises = Some(false)),
with(|s| s.quad_primitive_ids = true),
with(|s| s.private_list = true),
]
@@ -1,572 +0,0 @@
//! A `Depth16Unorm` depth stored as Metal's code by the fragment stage
//! (`LoweringInputs::depth16_codes`, `lower::stage_io::depth16`), over the owned fixtures
//! `engine/rt6_render_state` (`rt6_full`, and `rt6_white`, which returns no depth) and
//! `engine/rfb_viewports` (`rfb_full`; `rfb_depth` returns a depth, `rfb_position` reads its
//! position's depth and returns none):
//!
//! - On a committed profile without `DriverDeviation::MetalDepth16Stores`, a single-sampled
//! pipeline whose depth attachment is `Depth16Unorm` states `RuntimeFact::Depth16Codes`: biased
//! where its fragment function returns no depth (it reads `PushField::DepthBias`), unbiased where
//! it returns one; a pipeline without a fragment function gets a fragment stage of its own. A
//! profile that takes the deviation, a pipeline of another depth format, a multisampled one and
//! a function that reads its position's depth and returns none state nothing. Every module
//! passes L3.
//! - The render pass's depth decides it, whatever the pipeline names: a draw against another
//! depth than the pipeline's (`BindState::depth16_pass`) runs the variant of the pass's
//! (`VariantKey::depth16_pass`), which states it (`RuntimeFact::Depth16Pass`) and plans itself,
//! and pushes the draw's bias (`BindState::depth_bias`) where it writes the codes.
//! - A draw that biases the depth (`BindState::depth16_biased`) on a profile that takes the
//! deviation but not `DriverDeviation::MetalDepth16BiasedStores` runs the variant whose fragment
//! stage adds the bias (`VariantKey::depth16_biased`), which states it
//! (`RuntimeFact::Depth16Biased`) and plans itself; a function that returns its depth or reads
//! its position's, a multisampled pipeline and a profile of either other form run as compiled.
//! - A biased draw whose bias's side the consumer proved (`BindState::depth16_bias_raises`), where
//! the fragment stage adds the bias itself (under that variant, or on a profile without the
//! deviation), runs the variant whose stage declares the side (`VariantKey::depth16_bias_raises`,
//! `RuntimeFact::Depth16BiasSide`): `DepthGreater` with `NMax` for a raising bias, `DepthLess`
//! with `NMin` for a lowering one. A profile that stores biased depths as Metal's, and a function
//! that returns its depth, run as compiled.
//!
//! What the device stores is the runtime lane's (`runtime_lane::unorm_depth_bias`, Metal probes).
//! `llvm-as` assembles the fixture; a missing tool skips visibly. No GPU is used.
use std::path::Path;
use crate::bind::{BindState, DrawCall};
use crate::budget::Budget;
use crate::device::{Device, DeviceDescription, DevicePolicy};
use crate::error::{BindError, DriverDeviation};
use crate::library::Library;
use crate::metal::PixelFormat;
use crate::pipeline::artifact::RenderPipeline;
use crate::pipeline::descriptor::{
ColorAttachmentDescriptor, FunctionDescriptor, RenderPipelineDescriptor, StageSource,
};
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::interface::PushLoc;
use crate::pipeline::sym::{PushField, Stage};
use crate::pipeline::testing::{engine_dir, llvm_assemble, AssembleError};
use crate::spirv::testing::check_words_valid;
use crate::vk;
/// The library of `engine/<name>.ll`, or `None` (printed) where `llvm-as` is missing.
fn fixture(name: &str) -> Option<Library> {
match llvm_assemble(&engine_dir().join(format!("{name}.ll"))) {
Ok(b) => Some(Library::from_air(&b).expect("library")),
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
None
}
Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}.ll: {why}"),
}
}
/// The two fixtures' libraries, or `None` (printed) where `llvm-as` is missing.
fn fixtures() -> Option<Fixtures> {
Some(Fixtures {
rt6: fixture("rt6_render_state")?,
rfb: fixture("rfb_viewports")?,
})
}
/// The libraries of `engine/rt6_render_state` and `engine/rfb_viewports`.
struct Fixtures {
rt6: Library,
rfb: Library,
}
/// A fragment stage of the test's pipelines.
#[derive(Clone, Copy, Debug)]
enum Fragment {
/// `rt6_white` after `rt6_full`: returns no depth.
White,
/// `rfb_depth` after `rfb_full`: returns a depth.
Depth,
/// `rfb_position` after `rfb_full`: reads its position's depth and returns none.
Position,
/// `rt6_full` alone: no fragment function.
Absent,
}
/// The device of the committed description `stem`, under the default policy.
fn device(stem: &str) -> Device {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/profiles")
.join(format!("{stem}.json"));
let text = std::fs::read_to_string(path).expect("profile");
let desc = DeviceDescription::from_khronos_json(&text, None).expect("description");
Device::new(desc, DevicePolicy::default()).expect("device")
}
/// The profiles this test compiles on: two that take the deviation, two that do not.
const STEMS: [&str; 4] = [
"amd-780m-radv",
"moltenvk-m3",
"nvidia-rtx50-linux",
"lavapipe",
];
/// A pipeline of `fragment` and its vertex function with one `RGBA32Float` color, a depth
/// attachment of `depth` and `samples` raster samples.
fn descriptor(
libs: &Fixtures,
fragment: Fragment,
depth: PixelFormat,
samples: u32,
) -> RenderPipelineDescriptor {
let function = |lib: &Library, name| {
StageSource::Function(FunctionDescriptor::new(lib.function(name).expect(name)))
};
let (vertex, fragment) = match fragment {
Fragment::White => (
function(&libs.rt6, "rt6_full"),
Some((&libs.rt6, "rt6_white")),
),
Fragment::Depth => (
function(&libs.rfb, "rfb_full"),
Some((&libs.rfb, "rfb_depth")),
),
Fragment::Position => (
function(&libs.rfb, "rfb_full"),
Some((&libs.rfb, "rfb_position")),
),
Fragment::Absent => (function(&libs.rt6, "rt6_full"), None),
};
let mut d = RenderPipelineDescriptor::new(vertex);
d.fragment = fragment.map(|(lib, name)| function(lib, name));
d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Float));
d.depth_format = Some(depth);
d.raster_sample_count = samples;
d
}
/// Every stage of `p` passes L3 on `dev`.
fn validate(p: &RenderPipeline, dev: &Device, what: &str) {
for m in &p.stages {
check_words_valid(&m.spirv, &p.requirements, dev.profile())
.unwrap_or_else(|e| panic!("{what} {:?}: L3: {e}", m.stage));
}
}
/// How `p` stores a `Depth16Unorm` depth: its `RuntimeFact::Depth16Codes`, `Some(biased)`.
fn codes(p: &RenderPipeline) -> Option<bool> {
p.dependencies.iter().find_map(|d| match d.fact {
RuntimeFact::Depth16Codes { biased } => Some(biased),
_ => None,
})
}
/// The push offset of `p`'s fragment `PushField::DepthBias`, `None` without it.
fn bias_offset(p: &RenderPipeline, what: &str) -> Option<usize> {
p.interface
.push
.iter()
.filter(|pl| pl.stage == Stage::Fragment)
.flat_map(|pl| pl.fields.iter())
.find(|f| f.field == PushField::DepthBias)
.map(|f| match f.loc {
PushLoc::Push { offset } => {
assert_eq!(f.size, 16, "{what}");
offset as usize
}
other => panic!("{what}: {other:?}"),
})
}
#[test]
fn a_depth16_pipeline_s_fragment_stage_writes_metal_s_codes_where_the_device_does_not() {
let Some(libs) = fixtures() else {
return;
};
let budget = Budget::standard();
let d16 = PixelFormat::Depth16Unorm;
let mut forms = [0usize; 2];
for stem in STEMS {
let dev = device(stem);
let stores = dev
.profile()
.takes_driver_deviation(DriverDeviation::MetalDepth16Stores);
forms[usize::from(stores)] += 1;
let cases = [
(Fragment::White, d16, 1, Some(true)),
(Fragment::Depth, d16, 1, Some(false)),
(Fragment::Absent, d16, 1, Some(true)),
(Fragment::Position, d16, 1, None),
(Fragment::White, PixelFormat::Depth32Float, 1, None),
(Fragment::White, d16, 4, None),
(Fragment::Absent, d16, 4, None),
];
for (fragment, depth, samples, shader) in cases {
let what = format!("{stem} {fragment:?} {depth:?} x{samples}");
let d = descriptor(&libs, fragment, depth, samples);
let p = dev
.compile_render_pipeline(&d, &budget)
.unwrap_or_else(|e| panic!("{what}: {e}"));
validate(&p, &dev, &what);
let want = shader.filter(|_| !stores);
assert_eq!(codes(&p), want, "{what}");
assert_eq!(
bias_offset(&p, &what).is_some(),
want == Some(true),
"{what}"
);
let fragments = p
.stages
.iter()
.filter(|m| m.stage == vk::ShaderStage::FRAGMENT)
.count();
let fragmentless = matches!(fragment, Fragment::Absent);
let synthesized = fragmentless && want.is_some();
assert_eq!(
fragments,
usize::from(!fragmentless || synthesized),
"{what}"
);
}
}
assert_eq!(forms, [2, 2], "the profiles of each form");
}
/// A draw against another depth than its pipeline names runs the pass's variant: a pipeline
/// naming `Depth16Unorm` drawn against a `float` depth writes no codes, one naming `Depth32Float`
/// (or none, with no fragment function) drawn against a `Depth16Unorm` depth writes them and
/// pushes the draw's bias; each variant states its pass and plans itself, and a draw against the
/// named depth, or against none, runs the pipeline as compiled.
#[test]
fn a_draw_against_another_depth_runs_the_variant_of_the_pass_s_depth() {
let Some(libs) = fixtures() else {
return;
};
let budget = Budget::standard();
let triangle = DrawCall::Primitives {
vertex_start: 0,
vertex_count: 3,
instance_count: 1,
base_instance: 0,
};
let bias = [3.0f32 / 65535.0, 0.5, -0.25];
let against = |pass: Option<bool>| BindState {
depth16_pass: pass,
depth_bias: bias,
..Default::default()
};
for stem in ["lavapipe", "nvidia-rtx50-linux"] {
let dev = device(stem);
assert!(
!dev.profile()
.takes_driver_deviation(DriverDeviation::MetalDepth16Stores),
"{stem}"
);
let cases = [
(Fragment::White, PixelFormat::Depth16Unorm, false),
(Fragment::White, PixelFormat::Depth32Float, true),
(Fragment::Absent, PixelFormat::Depth32Float, true),
];
for (fragment, named, pass) in cases {
let what = format!("{stem} {fragment:?} {named:?} against {pass}");
let d = descriptor(&libs, fragment, named, 1);
let base = dev
.compile_render_pipeline(&d, &budget)
.unwrap_or_else(|e| panic!("{what}: {e}"));
// Against the named depth, or none, as compiled.
for same in [Some(!pass), None] {
let state = against(same);
let plan = base
.plan(&dev, &state.shape())
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert_eq!(plan.variant.depth16_pass, None, "{what} {same:?}");
plan.instantiate_draw(&state, &triangle)
.unwrap_or_else(|e| panic!("{what} {same:?}: {e:?}"));
}
let state = against(Some(pass));
let plan = base
.plan(&dev, &state.shape())
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert_eq!(plan.variant.depth16_pass, Some(pass), "{what}");
assert_eq!(
plan.instantiate_draw(&state, &triangle),
Err(BindError::NeedsVariant {
variant: Box::new(plan.variant.clone())
}),
"{what}"
);
let key = plan.variant.clone();
let v = dev
.compile_render_variant(&d, &key, &budget)
.unwrap_or_else(|e| panic!("{what}: {e}"));
validate(&v, &dev, &what);
assert_ne!(v.key, base.key, "{what}");
assert!(
v.dependencies
.iter()
.any(|x| x.fact == RuntimeFact::Depth16Pass { depth16: pass }),
"{what}"
);
assert_eq!(codes(&v), pass.then_some(true), "{what}");
let plan = v
.plan(&dev, &state.shape())
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert_eq!(plan.variant, key, "{what}");
let commands = plan
.instantiate_draw(&state, &triangle)
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
let Some(offset) = bias_offset(&v, &what) else {
assert!(!pass, "{what}: no bias field");
continue;
};
let mut pushed = vec![None; 256];
for w in &commands.push_constants {
for (i, b) in w.bytes.iter().enumerate() {
if let Some(slot) = pushed.get_mut(w.offset as usize + i) {
*slot = Some(*b);
}
}
}
let bytes: Vec<Option<u8>> = bias
.iter()
.chain(&[0.0])
.flat_map(|v| v.to_le_bytes())
.map(Some)
.collect();
assert_eq!(pushed.get(offset..offset + 16), Some(&bytes[..]), "{what}");
}
}
}
/// A draw biasing a `Depth16Unorm` depth on the Iris Xe RPL-P's profile, which takes
/// `DriverDeviation::MetalDepth16Stores` but not `DriverDeviation::MetalDepth16BiasedStores`,
/// runs the variant whose fragment stage adds the bias: it states `RuntimeFact::Depth16Biased`,
/// writes the codes biased, pushes the draw's bias, and plans itself, where an unbiased draw runs
/// the pipeline as compiled. A function that returns its depth (which Metal does not bias) or
/// reads its position's, a multisampled pipeline, and the profiles that take both deviations (the
/// 780M's) or neither (the RTX 50's) run a biased draw as compiled.
#[test]
fn a_biased_draw_runs_the_biased_variant_where_the_device_stores_only_unbiased_codes() {
let Some(libs) = fixtures() else {
return;
};
let budget = Budget::standard();
let d16 = PixelFormat::Depth16Unorm;
let triangle = DrawCall::Primitives {
vertex_start: 0,
vertex_count: 3,
instance_count: 1,
base_instance: 0,
};
let bias = [3.0f32 / 65535.0, 0.5, -0.25];
let drawn = |biased: bool| BindState {
depth16_pass: Some(true),
depth16_biased: biased,
depth_bias: bias,
..Default::default()
};
let stem = "intel-irisxe-rplp-anv";
let dev = device(stem);
let profile = dev.profile();
assert!(
profile.takes_driver_deviation(DriverDeviation::MetalDepth16Stores)
&& !profile.takes_driver_deviation(DriverDeviation::MetalDepth16BiasedStores),
"{stem}"
);
for fragment in [Fragment::White, Fragment::Absent] {
let what = format!("{stem} {fragment:?}");
let d = descriptor(&libs, fragment, d16, 1);
let base = dev
.compile_render_pipeline(&d, &budget)
.unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(codes(&base), None, "{what}");
let unbiased = drawn(false);
let plan = base
.plan(&dev, &unbiased.shape())
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert!(!plan.variant.depth16_biased, "{what} unbiased");
plan.instantiate_draw(&unbiased, &triangle)
.unwrap_or_else(|e| panic!("{what} unbiased: {e:?}"));
let state = drawn(true);
let plan = base
.plan(&dev, &state.shape())
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert!(plan.variant.depth16_biased, "{what}");
assert_eq!(plan.variant.depth16_pass, None, "{what}");
assert_eq!(
plan.instantiate_draw(&state, &triangle),
Err(BindError::NeedsVariant {
variant: Box::new(plan.variant.clone())
}),
"{what}"
);
let key = plan.variant.clone();
let v = dev
.compile_render_variant(&d, &key, &budget)
.unwrap_or_else(|e| panic!("{what}: {e}"));
validate(&v, &dev, &what);
assert_ne!(v.key, base.key, "{what}");
assert!(
v.dependencies
.iter()
.any(|x| x.fact == RuntimeFact::Depth16Biased),
"{what}"
);
assert_eq!(codes(&v), Some(true), "{what}");
assert!(bias_offset(&v, &what).is_some(), "{what}");
let plan = v
.plan(&dev, &state.shape())
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert_eq!(plan.variant, key, "{what}");
plan.instantiate_draw(&state, &triangle)
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
}
let compiled = [
(stem, Fragment::Depth, 1),
(stem, Fragment::Position, 1),
(stem, Fragment::White, 4),
("amd-780m-radv", Fragment::White, 1),
("nvidia-rtx50-linux", Fragment::White, 1),
];
for (stem, fragment, samples) in compiled {
let what = format!("{stem} {fragment:?} x{samples}");
let dev = device(stem);
let d = descriptor(&libs, fragment, d16, samples);
let base = dev
.compile_render_pipeline(&d, &budget)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let plan = base
.plan(&dev, &drawn(true).shape())
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert!(!plan.variant.depth16_biased, "{what}");
}
}
/// The execution modes the module `words` declares, and the `GLSL.std.450` instructions it uses.
fn modes_and_glsl(words: &[u32]) -> (Vec<u32>, Vec<u32>) {
const HEADER_WORDS: usize = 5;
let (mut modes, mut glsl) = (Vec::new(), Vec::new());
let mut at = HEADER_WORDS;
while at < words.len() {
let length = (words[at] >> 16) as usize;
assert!(length > 0, "an instruction of zero words at {at}");
match words[at] & 0xffff {
op if op == crate::spv::Op::ExecutionMode as u32 => modes.push(words[at + 2]),
op if op == crate::spv::Op::ExtInst as u32 => glsl.push(words[at + 4]),
_ => {}
}
at += length;
}
(modes, glsl)
}
/// A biased draw of proven side runs the variant whose fragment stage declares it, where the stage
/// adds the bias itself: the Iris Xe RPL-P under `VariantKey::depth16_biased`, and the RTX 50
/// (no `DriverDeviation::MetalDepth16Stores`) for every draw. Each side's variant states
/// `RuntimeFact::Depth16BiasSide`, declares `DepthGreater` (raising) or `DepthLess` (lowering)
/// beside `DepthReplacing`, bounds the depth with `NMax` or `NMin`, passes L3 and plans itself; a
/// draw of unknown side keeps the stage that declares neither. The 780M, which stores biased
/// depths as Metal's, and a function that returns its depth do not plan it.
#[test]
fn a_biased_draw_of_proven_side_declares_it() {
use crate::spv::{ExecutionMode as M, GlslStd450Op as G};
let Some(libs) = fixtures() else {
return;
};
let budget = Budget::standard();
let d16 = PixelFormat::Depth16Unorm;
let triangle = DrawCall::Primitives {
vertex_start: 0,
vertex_count: 3,
instance_count: 1,
base_instance: 0,
};
let drawn = |raises: Option<bool>| BindState {
depth16_pass: Some(true),
depth16_biased: true,
depth16_bias_raises: raises,
depth_bias: crate::metal::state::depth16_bias(2.0, 0.0, 0.0),
..Default::default()
};
for stem in ["intel-irisxe-rplp-anv", "nvidia-rtx50-linux"] {
let dev = device(stem);
for fragment in [Fragment::White, Fragment::Absent] {
let what = format!("{stem} {fragment:?}");
let d = descriptor(&libs, fragment, d16, 1);
let base = dev
.compile_render_pipeline(&d, &budget)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let plan = base
.plan(&dev, &drawn(None).shape())
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert_eq!(
plan.variant.depth16_bias_raises, None,
"{what} unknown side"
);
let unsided = dev
.compile_render_variant(&d, &plan.variant, &budget)
.unwrap_or_else(|e| panic!("{what}: {e}"));
for raises in [true, false] {
let what = format!("{what} raises {raises}");
let state = drawn(Some(raises));
let plan = base
.plan(&dev, &state.shape())
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert_eq!(plan.variant.depth16_bias_raises, Some(raises), "{what}");
let key = plan.variant.clone();
let v = dev
.compile_render_variant(&d, &key, &budget)
.unwrap_or_else(|e| panic!("{what}: {e}"));
validate(&v, &dev, &what);
assert_ne!(v.key, unsided.key, "{what}");
assert!(
v.dependencies
.iter()
.any(|x| x.fact == RuntimeFact::Depth16BiasSide { raises }),
"{what}"
);
assert_eq!(codes(&v), Some(true), "{what}");
let fragment_words = |p: &RenderPipeline| {
let m = p
.stages
.iter()
.find(|m| m.stage == vk::ShaderStage::FRAGMENT)
.unwrap_or_else(|| panic!("{what}: no fragment stage"));
modes_and_glsl(&m.spirv)
};
let (mode, op, other_mode) = match raises {
true => (M::DepthGreater, G::NMax, M::DepthLess),
false => (M::DepthLess, G::NMin, M::DepthGreater),
};
let (modes, glsl) = fragment_words(&v);
assert!(modes.contains(&(M::DepthReplacing as u32)), "{what}");
assert!(modes.contains(&(mode as u32)), "{what}: {modes:?}");
assert!(!modes.contains(&(other_mode as u32)), "{what}: {modes:?}");
assert!(glsl.contains(&(op as u32)), "{what}: {glsl:?}");
let (unsided_modes, unsided_glsl) = fragment_words(&unsided);
for m in [M::DepthGreater, M::DepthLess] {
assert!(!unsided_modes.contains(&(m as u32)), "{what} unsided");
}
let bounds = |g: &[u32]| g.iter().filter(|&&x| x == op as u32).count();
assert_eq!(bounds(&glsl), bounds(&unsided_glsl) + 1, "{what}");
let plan = v
.plan(&dev, &state.shape())
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert_eq!(plan.variant, key, "{what}");
plan.instantiate_draw(&state, &triangle)
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
}
}
}
let compiled = [
("intel-irisxe-rplp-anv", Fragment::Depth),
("amd-780m-radv", Fragment::White),
];
for (stem, fragment) in compiled {
let what = format!("{stem} {fragment:?}");
let dev = device(stem);
let d = descriptor(&libs, fragment, d16, 1);
let base = dev
.compile_render_pipeline(&d, &budget)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let plan = base
.plan(&dev, &drawn(Some(true)).shape())
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert_eq!(plan.variant.depth16_bias_raises, None, "{what}");
}
}
@@ -10,8 +10,8 @@
//! - A read outside the texture is Metal's zero texel, alpha the format's (measured), on a profile
//! whose device robustness would return the raw zero.
//! - `ARGB8Unorm`'s storage slot rotates its bytes in the shader (`RotateArgb`), and a half-float
//! storage slot of `HalfTowardZero` rounds each written `float` toward zero, one of
//! `HalfQuietNan` its NaN alone.
//! storage slot of `HalfQuietNan` quiets a written `float`'s NaN alone, the device rounding
//! every other value.
//! - The binder joins a slot bound in an extended-range format to the plan's variant, the
//! variant's plan states the same key, and it views the image in the raw format.
//! - Samples of such a texture are Metal's (`samples`), at Metal's level and through a linear
@@ -625,10 +625,8 @@ fn bfloat_reads_and_writes_are_metals() {
}
/// `ARGB8Unorm`'s storage slot holds its bytes in an `R8G8B8A8_UNORM` image, alpha in red: a
/// read rotates them into Metal's channels, and a write back stores each channel's code as Metal
/// writes it (the value clamped to `[0, 1]`, the exact product with 255 rounded to nearest, ties
/// to even) as that code times the `f32` nearest `1 / 255`, which every device stores as the code.
/// The held lanes run from below 0 to above 1.
/// read rotates them into Metal's channels, and a write back rotates them into the image's lanes
/// as computed, which the device's conversion stores. The held lanes run from below 0 to above 1.
#[test]
fn argb8_storage_slots_rotate_their_bytes() {
let Some(bc) = assemble("argb8", &kernel(Source::ReadWrite, false, 0)) else {
@@ -644,11 +642,6 @@ fn argb8_storage_slots_rotate_their_bytes() {
// The image's lanes as the view reads them (the interpreter holds `f32` bits).
let value = |k: u32| k as f32 / 3600.0 - 0.1;
let held = |n: u32| -> [u32; 4] { [0, 1, 2, 3].map(|c| value(4 * n + c).to_bits()) };
// The lanes a write of `held(n)` stores.
let code = |bits: u32| -> u32 {
let product = f64::from(f32::from_bits(bits).clamp(0.0, 1.0)) * 255.0;
(product.round_ties_even() as f32 * (1.0f32 / 255.0)).to_bits()
};
for (stem, p) in profiles() {
let (plan, m) =
typed_module_with(&bc, "k", &p, &i).unwrap_or_else(|e| panic!("{stem}: {e}"));
@@ -664,23 +657,22 @@ fn argb8_storage_slots_rotate_their_bytes() {
let at = layout
.index(0, 0, 0, [n % SIDE, n / SIDE, 0])
.expect("texel");
assert_eq!(target[at], held(n).map(code), "{stem}: texel {n} written");
assert_eq!(target[at], held(n), "{stem}: texel {n} written");
}
}
}
/// A half-float storage slot of `HalfTowardZero` (formatless, and declared `Rgba16f`) writes each
/// `float` channel rounded toward zero to the `half` Metal stores, as the `f32` that holds it: a
/// finite value past 65504 as 65504, an infinity kept, a NaN as `0x7fc00000`;
/// one of `HalfQuietNan` (a device's that rounds as Metal does: MoltenVK's here) writes it as
/// computed but a NaN as `0x7fc00000`. The held lanes cover
/// every tie between neighbouring halves and its neighbours, past the largest, the infinities
/// and NaNs. The NaN is Metal's where the profile takes `DriverDeviation::MetalFloatStorageNans`
/// (MoltenVK's and lavapipe's: the module requires its property, and `HalfQuietNan`'s also
/// `MetalHalfStorageWrites`), else the device's (ANV's on the Iris Xe of RPL-P:
/// `PrecisionNote::DeviceNanEncoding`).
/// A half-float storage slot of `HalfQuietNan` (formatless, and declared `Rgba16f`) writes each
/// `float` channel as computed but a NaN as `0x7fc00000`, the device's conversion rounding the
/// value: Metal's rounding toward zero where the profile takes
/// `DriverDeviation::MetalHalfStorageWrites` (the module requires its property), else the
/// device's own (`PrecisionNote::DeviceColorConversion`). The held lanes cover every tie between
/// neighbouring halves and its neighbours, past the largest, the infinities and NaNs. The NaN is
/// Metal's where the profile takes `DriverDeviation::MetalFloatStorageNans` (MoltenVK's and
/// lavapipe's: the module requires its property), else the device's (ANV's on the Iris Xe of
/// RPL-P: `PrecisionNote::DeviceNanEncoding`).
#[test]
fn half_float_storage_slots_round_toward_zero() {
fn half_float_storage_slots_quiet_their_nans() {
use crate::device::requirements::VkProperty;
use crate::pipeline::artifact::PrecisionNote;
let Some(bc) = assemble("halves", &kernel(Source::ReadWrite, false, 0)) else {
@@ -713,10 +705,8 @@ fn half_float_storage_slots_round_toward_zero() {
}
};
let held = move |n: u32| -> [u32; 4] { [0, 1, 2, 3].map(|c| value(n, c)) };
for class in [
StorageImageClass::HalfTowardZero,
StorageImageClass::HalfQuietNan,
] {
{
let class = StorageImageClass::HalfQuietNan;
for choice in [
StorageImageChoice {
numeric: Some(crate::pipeline::sym::SampledType::Float),
@@ -729,12 +719,8 @@ fn half_float_storage_slots_round_toward_zero() {
let anv = "intel-irisxe-rplp-anv";
let anv = (anv, profile(anv, DevicePolicy::default()).expect("profile"));
for (stem, p) in profiles().into_iter().chain([anv]) {
// `HalfQuietNan` is the class of a device measured to round as Metal does.
let rounds =
p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfStorageWrites);
if class == StorageImageClass::HalfQuietNan && !rounds {
continue;
}
// The kernel reads both textures: without formatless reads, the target's choice
// declares its format and the source's `RGBA32Float`'s.
let mut i = i.clone();
@@ -760,9 +746,6 @@ fn half_float_storage_slots_round_toward_zero() {
.expect("texel");
let want = held(n).map(|x| match f32::from_bits(x) {
v if v.is_nan() => 0x7fc0_0000,
v if class == StorageImageClass::HalfTowardZero => {
half_value(half_toward_zero(v)).to_bits()
}
_ => x,
});
assert_eq!(target[at], want, "{what}: texel {n}");
@@ -788,9 +771,15 @@ fn half_float_storage_slots_round_toward_zero() {
);
assert_eq!(
relied.contains(&VkProperty::MetalHalfStorageWrites),
class == StorageImageClass::HalfQuietNan,
rounds,
"{what}"
);
assert_eq!(
a.precision.contains(&PrecisionNote::DeviceColorConversion),
!rounds,
"{what}: {:?}",
a.precision
);
assert!(
!relied.contains(&VkProperty::MetalHalfStorageNans),
"{what}"
@@ -189,68 +189,6 @@ fn render_state(scale_offset: u64) -> BindState {
s
}
/// A fragment function that writes a float to an sRGB attachment reads the color table at a
/// fragment binding of its own, which the plan writes as `WriteSource::ColorWriteTable`: a uniform
/// buffer on ANV (`DriverWorkaround::UniformReadsOutpaceStorageReads`), a storage buffer on RADV,
/// NVIDIA and lavapipe. MoltenVK, whose conversion is Metal's, rounds nothing and has none, and an
/// `RGBA8Unorm` attachment has none anywhere.
#[test]
fn an_srgb_color_write_binds_the_color_table() {
use crate::pipeline::sym::SyntheticBinding;
let Some(bc) = fixture("stage_io") else {
return;
};
let (uniform, storage) = (
Some(vk::DescriptorType::UNIFORM_BUFFER),
Some(vk::DescriptorType::STORAGE_BUFFER),
);
let table = BindingSource::Synthetic {
stage: Stage::Fragment,
binding: SyntheticBinding::ColorWriteTable,
};
for (stem, ty) in [
("intel-irisxe-rplp-anv", uniform),
("intel-uhd770-rpls-anv", uniform),
("amd-780m-radv", storage),
("nvidia-rtx5080-laptop", storage),
("lavapipe", storage),
("moltenvk-m3", None),
] {
let dev = device(stem);
for (pf, want) in [
(PixelFormat::RGBA8UnormSRGB, ty),
(PixelFormat::RGBA8Unorm, None),
] {
let what = format!("{stem} {pf:?}");
let mut d = render_descriptor(&bc);
d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(pf));
let p = dev
.compile_render_pipeline(&d, &Budget::standard())
.unwrap_or_else(|e| panic!("{what}: {e}"));
let bound = p
.layout
.sets
.iter()
.flat_map(|s| &s.bindings)
.find(|b| b.source == table)
.map(|b| (b.ty, b.stages, b.count));
assert_eq!(
bound,
want.map(|t| (t, vk::ShaderStageFlags::FRAGMENT, 1)),
"{what}"
);
let plan = p.plan(&dev, &render_state(16).shape()).expect("plan");
let written: Vec<vk::DescriptorType> = plan
.descriptors
.iter()
.filter(|w| w.source == WriteSource::ColorWriteTable)
.map(|w| w.ty)
.collect();
assert_eq!(written, want.into_iter().collect::<Vec<_>>(), "{what}");
}
}
}
/// `Device::compile_render_pipeline` compiles a `Function` fragment stage with no output at a color
/// it writes that the pipeline has no attachment for, whose write Metal discards: the fixture's
/// fragment, writing colors 0 and 2, states color 0 alone among its color outputs in a pipeline of
@@ -1080,86 +1018,6 @@ fn stage_push(
u32::from_le_bytes(w.bytes[at..at + 4].try_into().expect("four bytes"))
}
/// Where the device does not store Metal's color writes, `stage_io_fragment`'s `float4` output to a
/// `BGRA8Unorm`, an `RGBA8Unorm` or an `RGBA16Float` attachment 0 compiles to one fragment module
/// (one key, the same words), which reads the attachment's rule word at each draw
/// (`PushField::ColorWriteRule`): the plan writes `0x2222` for the four 8-bit unorm channels and
/// `0x3333` for the half-float ones. Each pipeline lists the attachment as rounded in the shader
/// (its stage module's `rounded_colors`) where its rules round: the unorm channels always, the
/// half-float ones where the device does not convert a `float` to a half as Metal does
/// (`DriverDeviation::MetalSmallFloatColorWrites`). On MoltenVK, which stores Metal's codes, no
/// fragment reads a word.
#[test]
fn a_draw_writes_its_attachments_color_write_rule() {
use crate::error::DriverDeviation;
let Some(bc) = fixture("stage_io") else {
return;
};
for stem in [
"moltenvk-m3",
"lavapipe",
"amd-rdna3-radv",
"intel-irisxe-rplp-anv",
"nvidia-rtx5080-laptop",
] {
let dev = device(stem);
let takes = |d| dev.profile().takes_driver_deviation(d);
let metal = takes(DriverDeviation::MetalColorWrites);
let small = takes(DriverDeviation::MetalSmallFloatColorWrites);
let mut modules = BTreeSet::new();
let mut keys = Vec::new();
for (pf, word, rounds) in [
(PixelFormat::BGRA8Unorm, 0x2222, true),
(PixelFormat::RGBA8Unorm, 0x2222, true),
(PixelFormat::RGBA16Float, 0x3333, !small),
] {
let what = format!("{stem} {pf:?}");
let mut d = render_descriptor(&bc);
d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(pf));
keys.push(
dev.render_pipeline_key(&d, &Budget::standard())
.unwrap_or_else(|e| panic!("{what}: {e}"))
.fragment,
);
let p = dev
.compile_render_pipeline(&d, &Budget::standard())
.unwrap_or_else(|e| panic!("{what}: {e}"));
let fragment = p
.stages
.iter()
.find(|m| m.stage == vk::ShaderStage::FRAGMENT)
.expect("a fragment stage");
modules.insert(fragment.spirv.clone());
let reads = p.interface.push.iter().any(|pl| {
pl.fields
.iter()
.any(|f| f.field == PushField::ColorWriteRule(0))
});
assert_eq!(reads, !metal, "{what}");
if metal {
continue;
}
assert_eq!(fragment.rounded_colors.contains(&0), rounds, "{what}");
let state = render_state(16);
let plan = p.plan(&dev, &state.shape()).expect("plan");
let draw = DrawCall::Primitives {
vertex_start: 0,
vertex_count: 3,
instance_count: 1,
base_instance: 0,
};
let cmds = plan.instantiate_draw(&state, &draw).expect("draw");
let fragment_stage = (Stage::Fragment, vk::ShaderStageFlags::FRAGMENT);
let got = stage_push(&plan, &cmds, fragment_stage, PushField::ColorWriteRule(0));
assert_eq!(got, word, "{what}");
}
if !metal {
assert!(keys.windows(2).all(|k| k[0] == k[1]), "{stem}: {keys:?}");
assert_eq!(modules.len(), 1, "{stem}");
}
}
}
/// Pulled attributes (signed formats into the `uint` attributes) from layout 1, the `scale`
/// argument's index, with a static stride, and from layout 2 with a per-bind stride. Buffer 1 is
/// one binding (the argument's slot, widened to a `Whole` storage view); the static stride fills
+18 -23
View File
@@ -1651,20 +1651,28 @@ declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32)
// words) and its read of the table's length are emitted once. The module was
// about 3,500 words with a search per load; it is 1,520 with `u64` ids and 2,202
// with word ids.
// On a profile not measured to store Metal's normalized codes, the write rounds
// by the handle's class through the module's routine: a third function, called
// once.
// The write's normalized channels are the device's conversion: noted where the
// profile is not measured to store Metal's codes, or where it stores a texture
// of a 1-bit alpha, which it rounds otherwise.
let measured =
p.takes_driver_deviation(crate::error::DriverDeviation::MetalNormStorageWrites);
let routine = usize::from(!measured);
assert_eq!(count(&a, OP_FUNCTION), 2 + routine, "{stem}");
assert_eq!(count(&a, OP_FUNCTION_CALL), 2 + routine, "{stem}");
let one_bit = crate::metal::format::one_bit_storage(
crate::metal::format::StorageUse::texture(false, true),
&p,
);
assert_eq!(
a.precision
.contains(&crate::pipeline::PrecisionNote::DeviceColorConversion),
!measured || one_bit,
"{stem}"
);
assert_eq!(count(&a, OP_FUNCTION), 2, "{stem}");
assert_eq!(count(&a, OP_FUNCTION_CALL), 2, "{stem}");
assert_eq!(count(&a, OP_ULESS_THAN_EQUAL), 16, "{stem}");
assert_eq!(count(&a, OP_ARRAY_LENGTH), 1, "{stem}");
// A heap write on a profile whose half-float storage class converts also tests
// the handle's class index and writes that class's half, Metal's measured half
// write: 1,652 words with `HalfQuietNan`, 1,901 with `HalfTowardZero` (2,588 with
// word ids).
// the handle's class index and quiets the write's NaN: 1,652 words with
// `HalfQuietNan` (2,588 with word ids).
let half = match crate::metal::format::half_write_class(&p) {
crate::pipeline::lower_inputs::StorageImageClass::Identity => 0,
class => crate::lower::texture::heap_half_write_words(class) as usize,
@@ -1674,26 +1682,13 @@ declare i32 @air.get_width_texture_2d(ptr addrspace(1), i32)
let small = crate::lower::texture::heap_half_write_words(
crate::pipeline::lower_inputs::StorageImageClass::SmallFloatQuietNan,
) as usize;
// And the normalized write's rounding: the routine, its call and the class
// table where unmeasured, else a 1-bit alpha's class test where the profile
// stores one.
use crate::lower::texture::{norm_write, NormWrite};
let norm = match measured {
false => {
norm_write::ROUTINE_WORDS as usize
+ crate::lower::texture::heap_classes_words() as usize
+ NormWrite::Class.words(true) as usize
}
true => NormWrite::HeapOneBit.words(true) as usize,
};
// And a half-float member's bits through the unsigned integer twin, where the
// profile takes it.
let bits = match crate::metal::format::heap_half_bits(&p) {
true => crate::lower::texture::heap_bits_write_words() as usize,
false => 0,
};
let bound =
half + small + norm + bits + if p.fields().leaf.int64 { 1_600 } else { 2_300 };
let bound = half + small + bits + if p.fields().leaf.int64 { 1_600 } else { 2_300 };
assert!(
a.module.words.len() <= bound,
"{stem}: {}",
+54 -96
View File
@@ -610,11 +610,10 @@ fn the_projection_of_the_fixture_is_fixed_function() {
/// A fragment function's write to a half-float channel records the device's NaN encoding
/// (`PrecisionNote::DeviceNanEncoding`) only where the profile's driver is not measured to store
/// Metal's NaN: a `float` output's everywhere but MoltenVK, lavapipe and NVIDIA's measured GPUs, a
/// Metal's NaN: a `float` output's everywhere but MoltenVK, whose conversion is Metal's (the
/// output's own NaN reaches the device's conversion, which no other driver is measured with), a
/// `half` output's everywhere but NVIDIA's measured GPUs and MoltenVK, which writes it through a
/// 16-bit output. A write to an `RGBA8Unorm` attachment records none. Where the function selects
/// the attachment's rules at the draw, the pipeline keeps the note its rule word selects
/// (`color_writes::pipeline_writes`).
/// 16-bit output. A write to an `RGBA8Unorm` attachment records none.
#[test]
fn half_float_writes_note_the_nan_encoding_where_the_device_rewrites_it() {
use crate::pipeline::artifact::PrecisionNote;
@@ -623,12 +622,12 @@ fn half_float_writes_note_the_nan_encoding_where_the_device_rewrites_it() {
};
let note = PrecisionNote::DeviceNanEncoding;
for (stem, float_note, half_note) in [
("lavapipe", false, true),
("gate-lavapipe-x86_64", false, true),
("lavapipe", true, true),
("gate-lavapipe-x86_64", true, true),
("amd-rdna3-radv", true, true),
("intel-irisxe-rplp-anv", true, true),
("nvidia-rtx50-linux", true, true),
("nvidia-rtx5080-laptop", false, false),
("nvidia-rtx5080-laptop", true, false),
("moltenvk-m3", false, false),
] {
let p = prof(stem);
@@ -650,11 +649,9 @@ fn half_float_writes_note_the_nan_encoding_where_the_device_rewrites_it() {
let g = l.graphics.as_ref().expect("graphics");
let (notes, _) = crate::pipeline::color_writes::pipeline_writes(
&f,
&g.color_write_rules,
&g.color_attachments,
g.alpha_to_coverage,
)
.unwrap_or_else(|| panic!("{what}: no rule word"));
);
assert_eq!(notes.contains(&note), want, "{what}: {notes:?}");
}
}
@@ -797,11 +794,9 @@ fn half_attachments_round_to_nearest_even_under_mode_two() {
let g = l.graphics.as_ref().expect("graphics");
let (notes, _) = crate::pipeline::color_writes::pipeline_writes(
&f,
&g.color_write_rules,
&g.color_attachments,
g.alpha_to_coverage,
)
.unwrap_or_else(|| panic!("{what}: no rule word"));
);
assert_eq!(
notes.contains(&PrecisionNote::CoverageReadsRoundedAlpha),
float && r.alpha_to_coverage,
@@ -902,14 +897,6 @@ fn mode_two_refuses_fragment_texture_writes_it_would_round() {
),
Goes::Declared,
),
(
"tob_write",
choice(
vk::Format::R16G16B16A16_SFLOAT,
StorageImageClass::HalfTowardZero,
),
Goes::Declared,
),
(
"tob_write",
choice(vk::Format::B10G11R11_UFLOAT_PACK32, identity),
@@ -972,21 +959,23 @@ fn mode_two_refuses_fragment_texture_writes_it_would_round() {
}
}
/// Where the profile's driver is measured to convert a `float` output to a half-float or unsigned
/// small float channel as Metal does (`MetalSmallFloatColorWrites`: RADV on the Radeon 780M, ANV on
/// the Iris Xe of RPL-P, NVIDIA's on the RTX 3090), or an output to a 16-bit unorm or snorm channel
/// (`MetalNorm16ColorWrites`: the 780M), the fragment function writes it as computed: the
/// attachment is not listed as rounded (its blend of one and zero kept), the module requires the
/// property, and it links valid. Only a NaN is chosen, as `0x7fc00000` where the device stores that
/// as Metal's NaN and its own NaN would not be (an unsigned small float, and a half-float channel
/// on the 3090), and as -1.0 for a blended snorm channel, so `OpIsNan` appears exactly there.
/// Elsewhere (the UHD 770 of RPL-S, the RTX 5080 Laptop GPU, lavapipe; a `half` output to
/// `RG11B10Float`) the output rounds, listed, requiring neither. Each holds of the channels' own
/// rules (`color_writes::exact_writes`), and where the function selects the attachment's rules at
/// the draw the pipeline lists the attachment, keeps its blend and requires the property alike.
/// A fragment function's output to a normalized or small float attachment is written as computed
/// on every profile, its conversion the device's: nothing rounds (no `OpIsNan` of a rounding), the
/// attachment is not listed as rounded, and its blend of one and zero takes no Vulkan blend, as
/// Metal's stores the output as written. Where the profile's
/// driver is measured to convert a `float` output to a half-float or unsigned small float channel
/// as Metal does (`MetalSmallFloatColorWrites`: RADV on the Radeon 780M, ANV on the Iris Xe of
/// RPL-P and the UHD 770 of RPL-S, NVIDIA's on the RTX 3090), or an output to a 16-bit unorm or
/// snorm channel (`MetalNorm16ColorWrites`: the 780M; a blended snorm channel's NaN aside), the
/// module requires the property and records no `PrecisionNote::DeviceColorConversion` (a small
/// float's NaN, as computed, is the device's: `PrecisionNote::DeviceNanEncoding`); elsewhere (the
/// RTX 5080 Laptop GPU, lavapipe; a `half` output to `RG11B10Float`) it records the conversion and
/// requires neither, but for a `half` output to a half-float channel, a half already, which records
/// none.
#[test]
fn measured_color_conversions_are_left_to_the_device() {
use crate::device::requirements::VkProperty;
use crate::pipeline::artifact::PrecisionNote;
let Some(bc) = assemble("rt6_samples.ll") else {
return;
};
@@ -1004,53 +993,40 @@ fn measured_color_conversions_are_left_to_the_device() {
.profile()
.clone()
};
for (stem, p, small_taken, norm16_taken, nan_selected) in [
("amd-780m-radv", prof("amd-780m-radv"), true, true, false),
for (stem, p, small_taken, norm16_taken) in [
("amd-780m-radv", prof("amd-780m-radv"), true, true),
(
"intel-irisxe-rplp-anv",
prof("intel-irisxe-rplp-anv"),
true,
false,
false,
),
("rtx-3090", rtx_3090, true, false, true),
("rtx-3090", rtx_3090, true, false),
(
"intel-uhd770-rpls-anv",
prof("intel-uhd770-rpls-anv"),
true,
false,
false,
),
(
"nvidia-rtx5080-laptop",
prof("nvidia-rtx5080-laptop"),
false,
false,
false,
),
("lavapipe", prof("lavapipe"), false, false, false),
("lavapipe", prof("lavapipe"), false, false),
] {
let v = compile(&bc, "rt6_fill_vertex", &p).expect("vertex");
for (entry, float) in [
("rt6_fill_rgba32float", true),
("rt6_fill_rgba16float", false),
] {
for (pf, property, taken, nan) in [
(
PixelFormat::RGBA16Float,
small,
small_taken && float,
nan_selected,
),
(
PixelFormat::R16Float,
small,
small_taken && float,
nan_selected,
),
(PixelFormat::RG11B10Float, small, small_taken && float, true),
(PixelFormat::RGBA16Unorm, norm16, norm16_taken, false),
(PixelFormat::RG16Snorm, norm16, norm16_taken, false),
for (pf, property, taken) in [
(PixelFormat::RGBA16Float, small, small_taken && float),
(PixelFormat::R16Float, small, small_taken && float),
(PixelFormat::RG11B10Float, small, small_taken && float),
(PixelFormat::RGBA16Unorm, norm16, norm16_taken),
(PixelFormat::RG16Snorm, norm16, norm16_taken),
] {
for blended in [false, true] {
let what = format!("{stem} {entry} {pf:?} blended {blended}");
@@ -1058,61 +1034,43 @@ fn measured_color_conversions_are_left_to_the_device() {
let mut a = ColorAttachmentDescriptor::new(pf);
a.blending_enabled = blended;
r.color_attachments[0] = Some(a);
let mut exact = fragment_inputs(&r, &p);
exact.color_writes = crate::pipeline::color_writes::exact_writes(
[0],
&r.color_attachments,
(r.alpha_to_coverage, r.texture_write_rounding_mode),
&p,
);
let f = compile_with(&bc, entry, &p, &exact)
let f = compile_with(&bc, entry, &p, &fragment_inputs(&r, &p))
.unwrap_or_else(|e| panic!("{what}: {e}"));
let l =
link(&[&v, &f], &render(&r), &p).unwrap_or_else(|e| panic!("{what}: {e}"));
let words = validate_all(&l, &[&v, &f], &p);
let text = spirv_dis(&words[1]);
// A `half` output to a half-float channel is a half already: nothing rounds.
let held =
!float && matches!(pf, PixelFormat::RGBA16Float | PixelFormat::R16Float);
let listed = f.interface.io.rounded_colors.contains(&0);
assert_eq!(listed, !taken && !held, "{what}");
assert!(!text.contains("OpIsNan"), "{what}\n{text}");
assert!(!f.interface.io.rounded_colors.contains(&0), "{what}");
// A blended snorm channel's NaN is Metal's -1.0, which no device stores.
let taken = taken && !(blended && pf == PixelFormat::RG16Snorm);
assert_eq!(
f.requirements.properties.contains(&property),
taken,
"{what}"
);
// A `half` output to a half-float channel is a half already.
let held =
!float && matches!(pf, PixelFormat::RGBA16Float | PixelFormat::R16Float);
assert_eq!(
f.precision.contains(&PrecisionNote::DeviceColorConversion),
!taken && !held,
"{what}: {:?}",
f.precision
);
if taken && property == small {
assert!(
f.precision.contains(&PrecisionNote::DeviceNanEncoding),
"{what}: {:?}",
f.precision
);
}
let blend = l.graphics.as_ref().expect("graphics").color_attachments[0]
.as_ref()
.expect("attachment")
.blend
.is_some();
assert_eq!(blend, blended && !listed, "{what}");
if taken {
let snorm = blended && pf == PixelFormat::RG16Snorm;
assert_eq!(text.contains("OpIsNan"), nan || snorm, "{what}\n{text}");
}
// The pipeline's map, whose attachment may select its rules at the draw.
let s = compile_with(&bc, entry, &p, &fragment_inputs(&r, &p))
.unwrap_or_else(|e| panic!("{what}: {e}"));
let l =
link(&[&v, &s], &render(&r), &p).unwrap_or_else(|e| panic!("{what}: {e}"));
validate_all(&l, &[&v, &s], &p);
let g = l.graphics.as_ref().expect("graphics");
let (_, rounded) = crate::pipeline::color_writes::pipeline_writes(
&s,
&g.color_write_rules,
&g.color_attachments,
g.alpha_to_coverage,
)
.unwrap_or_else(|| panic!("{what}: no rule word"));
assert_eq!(rounded.contains(&0), listed, "{what} selected");
assert_eq!(
s.requirements.properties.contains(&property),
taken,
"{what} selected"
);
let attachment = g.color_attachments[0].as_ref().expect("attachment");
assert_eq!(attachment.blend.is_some(), blend, "{what} selected");
assert!(!blend, "{what}");
}
}
}
@@ -5,7 +5,7 @@
//!
//! On the CPU interpreter, each kernel runs under the choice without the conversion and with it,
//! on the same image and values, for `float`, `half`, `uint` and `int` texels and the classes a
//! held RGBA twin takes (`Identity`; a half-float twin's `HalfTowardZero`): a `read_write` read
//! held RGBA twin takes (`Identity`; a half-float twin's `HalfQuietNan`): a `read_write` read
//! is the plain read with alpha 1, in bounds and past the texture (whose alpha Metal reads 1
//! too); a write, `access::write` or `read_write`, stores the plain write's texel with its fourth
//! lane the green lane's bits, after the class's conversion. An sRGB twin's `SrgbEncode`, and an
@@ -79,7 +79,7 @@ impl Texel {
(vk::Format::R8G8B8A8_UNORM, StorageImageClass::Identity),
(
vk::Format::R16G16B16A16_SFLOAT,
StorageImageClass::HalfTowardZero,
StorageImageClass::HalfQuietNan,
),
(vk::Format::R32G32B32A32_SFLOAT, StorageImageClass::Identity),
],
@@ -956,10 +956,8 @@ fn a_half_color_output_records_its_precision() {
/// device blends in its own arithmetic).
#[test]
fn a_half_output_without_fast_math_is_noted_where_its_attachment_blends() {
use crate::metal::{PixelFormat, TextureWriteRoundingMode};
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::color_writes::{pipeline_writes, rule_words};
use crate::pipeline::descriptor::ColorAttachmentDescriptor;
use crate::pipeline::color_writes::pipeline_writes;
use crate::pipeline::graphics::{BlendState, ColorAttachmentState};
use crate::vk::{BlendFactor as F, BlendOp as O, ColorComponentFlags, Format};
let Some(disabled) = math_mode_edited(Some("air.compile.fast_math_disable")) else {
@@ -1000,22 +998,17 @@ fn a_half_output_without_fast_math_is_noted_where_its_attachment_blends() {
let f = compile(&disabled, "stage_io_fragment_point", &p).expect("half");
assert_eq!(f.interface.io.half_blend_colors, [0], "{stem}");
assert!(!f.precision.contains(&note), "{stem}");
let descriptors = [Some(ColorAttachmentDescriptor::new(
PixelFormat::RGBA16Float,
))];
let rounding = (false, TextureWriteRoundingMode::TowardZero);
let rules = rule_words(&f.interface.io, &descriptors, rounding, &p).expect("rules");
for (what, mask, b, want) in cases {
let colors = [Some(ColorAttachmentState::new(
Format::R16G16B16A16_SFLOAT,
mask,
b,
))];
let (notes, _) = pipeline_writes(&f, &rules, &colors, false).expect(what);
let (notes, _) = pipeline_writes(&f, &colors, false);
assert_eq!(notes.contains(&note), want, "{stem}: {what}: {notes:?}");
}
// A pipeline without the attachment's state (none listed) records none.
let (notes, _) = pipeline_writes(&f, &rules, &[], false).expect("no attachments");
let (notes, _) = pipeline_writes(&f, &[], false);
assert!(!notes.contains(&note), "{stem}: no attachments");
}
}
@@ -1030,10 +1023,8 @@ fn a_half_output_without_fast_math_is_noted_where_its_attachment_blends() {
/// window-server pass's colors of mask none beside its fetched one).
#[test]
fn a_half_output_with_fast_math_is_noted_where_its_attachment_stores() {
use crate::metal::{PixelFormat, TextureWriteRoundingMode};
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::color_writes::{pipeline_writes, rule_words};
use crate::pipeline::descriptor::ColorAttachmentDescriptor;
use crate::pipeline::color_writes::pipeline_writes;
use crate::pipeline::graphics::{BlendState, ColorAttachmentState};
use crate::vk::{BlendFactor as F, BlendOp as O, ColorComponentFlags, Format};
let Some(bc) = fixture() else { return };
@@ -1060,18 +1051,13 @@ fn a_half_output_with_fast_math_is_noted_where_its_attachment_stores() {
let f = compile(&bc, "stage_io_fragment_point", &p).expect("half");
assert_eq!(f.interface.io.half_fast_colors, [0], "{stem}");
assert!(!f.precision.contains(&note), "{stem}");
let descriptors = [Some(ColorAttachmentDescriptor::new(
PixelFormat::RGBA16Float,
))];
let rounding = (false, TextureWriteRoundingMode::TowardZero);
let rules = rule_words(&f.interface.io, &descriptors, rounding, &p).expect("rules");
for (what, mask, b, want) in cases {
let colors = [Some(ColorAttachmentState::new(
Format::R16G16B16A16_SFLOAT,
mask,
b,
))];
let (notes, _) = pipeline_writes(&f, &rules, &colors, false).expect(what);
let (notes, _) = pipeline_writes(&f, &colors, false);
assert_eq!(notes.contains(&note), want, "{stem}: {what}: {notes:?}");
}
// A one-channel format under a mask of blue alone stores nothing; under red it stores.
@@ -1084,7 +1070,7 @@ fn a_half_output_with_fast_math_is_noted_where_its_attachment_stores() {
mask,
over,
))];
let (notes, _) = pipeline_writes(&f, &rules, &colors, false).expect("R16");
let (notes, _) = pipeline_writes(&f, &colors, false);
assert_eq!(
notes.contains(&note),
want,
@@ -1092,7 +1078,7 @@ fn a_half_output_with_fast_math_is_noted_where_its_attachment_stores() {
);
}
// A pipeline without the attachment's state (none listed) records none.
let (notes, _) = pipeline_writes(&f, &rules, &[], false).expect("no attachments");
let (notes, _) = pipeline_writes(&f, &[], false);
assert!(!notes.contains(&note), "{stem}: no attachments");
}
}
@@ -253,8 +253,8 @@ fn bgra8_and_rgba8_storage_textures_compile_to_distinct_modules() {
srgb += 1;
assert!(!s.precision.contains(&PrecisionNote::DeviceTranscendentals));
assert_ne!(s.key, rgba.key, "{stem}");
// instructions' count: an rgba8 write rounds to Metal's codes in the shader too
// where the device is not measured to store them.
// The encode's table, which an rgba8 write, left to the device's conversion,
// takes none of.
assert!(table(s) && !table(&rgba), "{stem}");
}
}
-1
View File
@@ -36,7 +36,6 @@ mod engine_coverage_loop;
mod engine_cross_class;
mod engine_cube_gather;
mod engine_declared_varyings;
mod engine_depth16_codes;
mod engine_depth_range;
mod engine_device_level;
mod engine_device_replay;
@@ -2571,7 +2571,6 @@ field metal2vulkan-runtime::WorkCounts.creation_pipelines_made pub creation_pipe
field metal2vulkan-runtime::WorkCounts.creation_render_pipelines_drawn pub creation_render_pipelines_drawn: u64
field metal2vulkan-runtime::WorkCounts.creation_render_pipelines_made pub creation_render_pipelines_made: u64
field metal2vulkan-runtime::WorkCounts.dedicated_memory_blocks_live pub dedicated_memory_blocks_live: u64
field metal2vulkan-runtime::WorkCounts.depth16_sided_draws pub depth16_sided_draws: u64
field metal2vulkan-runtime::WorkCounts.depth_attachments_moved pub depth_attachments_moved: u64
field metal2vulkan-runtime::WorkCounts.depth_instances_held pub depth_instances_held: u64
field metal2vulkan-runtime::WorkCounts.descriptor_keys_built pub descriptor_keys_built: u64
@@ -2998,9 +2997,6 @@ field metal2vulkan::bind::AstcDecode.height pub height: u32
field metal2vulkan::bind::AstcDecode.srgb pub srgb: bool
field metal2vulkan::bind::AstcDecode.width pub width: u32
field metal2vulkan::bind::BindShape.argument_samplers pub argument_samplers: ArgumentSamplersShape
field metal2vulkan::bind::BindShape.depth16_bias_raises pub depth16_bias_raises: Option<bool>
field metal2vulkan::bind::BindShape.depth16_biased pub depth16_biased: bool
field metal2vulkan::bind::BindShape.depth16_pass pub depth16_pass: Option<bool>
field metal2vulkan::bind::BindShape.depth_clamp_range pub depth_clamp_range: bool
field metal2vulkan::bind::BindShape.dropped_colors pub dropped_colors: BTreeSet<u32>
field metal2vulkan::bind::BindShape.extended_shadows pub extended_shadows: BTreeSet<u32>
@@ -3027,10 +3023,6 @@ field metal2vulkan::bind::BindShape.zeroed_colors pub zeroed_colors: BTreeMap<u3
field metal2vulkan::bind::BindState.alpha_test_reference pub alpha_test_reference: Option<f32>
field metal2vulkan::bind::BindState.argument_samplers pub argument_samplers: Vec<ArgumentSampler>
field metal2vulkan::bind::BindState.blend_color pub blend_color: [f32; 4]
field metal2vulkan::bind::BindState.depth16_bias_raises pub depth16_bias_raises: Option<bool>
field metal2vulkan::bind::BindState.depth16_biased pub depth16_biased: bool
field metal2vulkan::bind::BindState.depth16_pass pub depth16_pass: Option<bool>
field metal2vulkan::bind::BindState.depth_bias pub depth_bias: [f32; 3]
field metal2vulkan::bind::BindState.depth_clamp_range pub depth_clamp_range: Option<[f32; 2]>
field metal2vulkan::bind::BindState.depth_clip_mode_clamp pub depth_clip_mode_clamp: bool
field metal2vulkan::bind::BindState.depth_range pub depth_range: [f32; 2]
@@ -3643,9 +3635,6 @@ field metal2vulkan::cache::VariantKey.captured_positions pub captured_positions:
field metal2vulkan::cache::VariantKey.color_group pub color_group: u32
field metal2vulkan::cache::VariantKey.cross_class pub cross_class: BTreeMap<SlotRef, crate::pipeline::sym::SampledType>
field metal2vulkan::cache::VariantKey.cubic_samplers pub cubic_samplers: BTreeMap<SlotRef, u32>
field metal2vulkan::cache::VariantKey.depth16_bias_raises pub depth16_bias_raises: Option<bool>
field metal2vulkan::cache::VariantKey.depth16_biased pub depth16_biased: bool
field metal2vulkan::cache::VariantKey.depth16_pass pub depth16_pass: Option<bool>
field metal2vulkan::cache::VariantKey.depth_clamp_range pub depth_clamp_range: bool
field metal2vulkan::cache::VariantKey.dropped_colors pub dropped_colors: BTreeSet<u32>
field metal2vulkan::cache::VariantKey.dropped_vertex_layer pub dropped_vertex_layer: bool
@@ -4153,7 +4142,6 @@ field metal2vulkan::pipeline::GraphicsState.clip_distances pub clip_distances: u
field metal2vulkan::pipeline::GraphicsState.color_attachments pub color_attachments: Vec<Option<ColorAttachmentState>>
field metal2vulkan::pipeline::GraphicsState.color_group pub color_group: Option<crate::pipeline::lower_inputs::ColorGroup>
field metal2vulkan::pipeline::GraphicsState.color_outputs pub color_outputs: u32
field metal2vulkan::pipeline::GraphicsState.color_write_rules pub color_write_rules: Vec<(u32, u32)>
field metal2vulkan::pipeline::GraphicsState.declares_layer pub declares_layer: bool
field metal2vulkan::pipeline::GraphicsState.depth_format pub depth_format: Option<vk::Format>
field metal2vulkan::pipeline::GraphicsState.dynamic_states pub dynamic_states: Vec<vk::DynamicState>
@@ -4214,8 +4202,6 @@ field metal2vulkan::pipeline::LoweringInputs.color_group pub color_group: Option
field metal2vulkan::pipeline::LoweringInputs.color_writes pub color_writes: BTreeMap<u32, [Option<ChannelWrite>; 4]>
field metal2vulkan::pipeline::LoweringInputs.cross_class pub cross_class: BTreeMap<SlotRef, SampledType>
field metal2vulkan::pipeline::LoweringInputs.cubic_samplers pub cubic_samplers: BTreeMap<SlotRef, u32>
field metal2vulkan::pipeline::LoweringInputs.depth16_bias_raises pub depth16_bias_raises: Option<bool>
field metal2vulkan::pipeline::LoweringInputs.depth16_codes pub depth16_codes: bool
field metal2vulkan::pipeline::LoweringInputs.depth_clamp_range pub depth_clamp_range: bool
field metal2vulkan::pipeline::LoweringInputs.depth_compare_clamp_mask pub depth_compare_clamp_mask: u32
field metal2vulkan::pipeline::LoweringInputs.dropped_colors pub dropped_colors: BTreeSet<u32>
@@ -4598,7 +4584,6 @@ fn metal2vulkan::bind::capture_assembly_module pub fn capture_assembly_module(de
fn metal2vulkan::bind::capture_settle_module pub fn capture_settle_module(device: &Device) -> Result<CaptureSettleModule, Error>
fn metal2vulkan::bind::chroma_decode_module pub fn chroma_decode_module(device: &Device, decode: ChromaDecode) -> Result<BlockDecodeModule, Error>
fn metal2vulkan::bind::color_resolve_modules pub fn color_resolve_modules(device: &Device, format: ColorResolveFormat, samples: u32, source: ResolveSource, feature: Feature) -> Result<ColorResolveModules, Error>
fn metal2vulkan::bind::color_write_table pub fn color_write_table() -> &'static [u8]
fn metal2vulkan::bind::compressed_blit_module pub fn compressed_blit_module(device: &Device, rule: CompressedBlit) -> Result<CompressedBlitModule, Error>
fn metal2vulkan::bind::depth_split_module pub fn depth_split_module(device: &Device, form: DepthStandInForm, feature: Feature) -> Result<DepthSplitModule, Error>
fn metal2vulkan::bind::depth_stencil_copy_modules pub fn depth_stencil_copy_modules(device: &Device, copy: DepthStencilCopy, feature: Feature) -> Result<DepthStencilCopyModules, Error>
@@ -4723,8 +4708,6 @@ fn metal2vulkan::metal::state::blend_factor pub fn blend_factor(f: BlendFactor,
fn metal2vulkan::metal::state::blend_op pub fn blend_op(op: BlendOperation) -> Result<vk::BlendOp, Error>
fn metal2vulkan::metal::state::blend_state pub fn blend_state(attachment: &ColorAttachmentDescriptor, profile: &DeviceProfile) -> Result<Option<BlendState>, Error>
fn metal2vulkan::metal::state::color_write_mask pub fn color_write_mask(mask: ColorWriteMask) -> Result<vk::ColorComponentFlags, Error>
fn metal2vulkan::metal::state::depth16_bias pub fn depth16_bias(depth_bias: f32, slope_scale: f32, clamp: f32) -> [f32; 3]
fn metal2vulkan::metal::state::depth16_bias_side pub fn depth16_bias_side(depth_bias: f32, slope_scale: f32, clamp: f32) -> Option<bool>
fn metal2vulkan::metal::state::depth_bias pub fn depth_bias(topology: vk::PrimitiveTopology, depth_bias: f32, slope_scale: f32, clamp: f32, depth_format: Option<PixelFormat>, profile: &DeviceProfile) -> Result<DepthBias, Error>
fn metal2vulkan::metal::state::depth_clamp_enable pub fn depth_clamp_enable(mode: DepthClipMode, profile: &DeviceProfile) -> Result<bool, Error>
fn metal2vulkan::metal::state::depth_stencil_state pub fn depth_stencil_state(desc: &DepthStencilDescriptor) -> DepthStencilState
@@ -5142,7 +5125,6 @@ macro-member metal2vulkan-runtime::Degradation::ShaderHalfColorBits ShaderHalfCo
macro-member metal2vulkan-runtime::Degradation::ShaderResolve ShaderResolve = "shader-resolve", Performance,
macro-member metal2vulkan-runtime::Degradation::ShaderSideDepthTest ShaderSideDepthTest = "shader-side-depth-test", Performance,
macro-member metal2vulkan-runtime::Degradation::ShaderSideStencil ShaderSideStencil = "shader-side-stencil", Performance,
macro-member metal2vulkan-runtime::Degradation::ShaderUnormDepth ShaderUnormDepth = "shader-unorm-depth", Performance,
macro-member metal2vulkan-runtime::Degradation::ShadowMerge ShadowMerge = "shadow-merge", Performance,
macro-member metal2vulkan-runtime::Degradation::ShadowedTexture ShadowedTexture = "shadowed-texture", Performance,
macro-member metal2vulkan-runtime::Degradation::ShadowedTextureView ShadowedTextureView = "shadowed-texture-view", Performance,
@@ -5185,7 +5167,6 @@ macro-member metal2vulkan-runtime::Degradation::UnnamedTexturesPastCapacity Unna
macro-member metal2vulkan-runtime::Degradation::UnorderedDrawBytes UnorderedDrawBytes = "unordered-draw-bytes", Performance,
macro-member metal2vulkan-runtime::Degradation::UnormDepthBias UnormDepthBias = "unorm-depth-bias", Precision,
macro-member metal2vulkan-runtime::Degradation::UnormDepthRounding UnormDepthRounding = "unorm-depth-rounding", Precision,
macro-member metal2vulkan-runtime::Degradation::UnormDepthSlope UnormDepthSlope = "unorm-depth-slope", Precision,
macro-member metal2vulkan-runtime::Degradation::UnpackedFillColor UnpackedFillColor = "unpacked-fill-color", Precision,
macro-member metal2vulkan-runtime::Degradation::UnreachedTilesRewritten UnreachedTilesRewritten = "unreached-tiles-rewritten", Precision,
macro-member metal2vulkan-runtime::Degradation::UnreadableHandleTexture UnreadableHandleTexture = "unreadable-handle-texture", Precision,
@@ -12324,7 +12305,6 @@ variant metal2vulkan::bind::WriteSource::ArgumentSampler ArgumentSampler { index
variant metal2vulkan::bind::WriteSource::ArgumentTable ArgumentTable { stage: Stage, bytes_len: u32 }
variant metal2vulkan::bind::WriteSource::Attachment Attachment { color_index: u32 }
variant metal2vulkan::bind::WriteSource::Buffer Buffer { slot: SlotRef }
variant metal2vulkan::bind::WriteSource::ColorWriteTable ColorWriteTable
variant metal2vulkan::bind::WriteSource::CombinedImageSampler CombinedImageSampler { image: ImageSource, sampler: SamplerSource }
variant metal2vulkan::bind::WriteSource::ConstantBlob ConstantBlob { stage: Stage }
variant metal2vulkan::bind::WriteSource::ControlPointIndices ControlPointIndices
@@ -13518,7 +13498,6 @@ variant metal2vulkan::pipeline::ChannelWrite::Device Device
variant metal2vulkan::pipeline::ChannelWrite::FloatNearestEven FloatNearestEven { mantissa: u8, signed: bool }
variant metal2vulkan::pipeline::ChannelWrite::FloatTowardZero FloatTowardZero { mantissa: u8, signed: bool }
variant metal2vulkan::pipeline::ChannelWrite::HalfUnorm HalfUnorm { bits: u8 }
variant metal2vulkan::pipeline::ChannelWrite::Selected Selected
variant metal2vulkan::pipeline::ChannelWrite::Snorm Snorm { bits: u8, blended: bool }
variant metal2vulkan::pipeline::ChannelWrite::Srgb Srgb
variant metal2vulkan::pipeline::ChannelWrite::Unorm Unorm { bits: u8 }
@@ -13652,10 +13631,8 @@ variant metal2vulkan::pipeline::PushField::BlendColor BlendColor
variant metal2vulkan::pipeline::PushField::CaptureAddress CaptureAddress
variant metal2vulkan::pipeline::PushField::CaptureIndexAddress CaptureIndexAddress
variant metal2vulkan::pipeline::PushField::CaptureLayout CaptureLayout
variant metal2vulkan::pipeline::PushField::ColorWriteRule ColorWriteRule(u32)
variant metal2vulkan::pipeline::PushField::CommandRecordsAddress CommandRecordsAddress
variant metal2vulkan::pipeline::PushField::ControlPointIndexOffset ControlPointIndexOffset
variant metal2vulkan::pipeline::PushField::DepthBias DepthBias
variant metal2vulkan::pipeline::PushField::DepthClampRange DepthClampRange
variant metal2vulkan::pipeline::PushField::DispatchRegion DispatchRegion
variant metal2vulkan::pipeline::PushField::ExecutionStatusAddress ExecutionStatusAddress
@@ -13738,10 +13715,6 @@ variant metal2vulkan::pipeline::RuntimeFact::ConstexprSampled ConstexprSampled {
variant metal2vulkan::pipeline::RuntimeFact::CrossClassReads CrossClassReads { slot: SlotRef }
variant metal2vulkan::pipeline::RuntimeFact::CubicArgumentSampler CubicArgumentSampler { stage: Stage }
variant metal2vulkan::pipeline::RuntimeFact::CubicSampler CubicSampler { slot: SlotRef }
variant metal2vulkan::pipeline::RuntimeFact::Depth16BiasSide Depth16BiasSide { raises: bool }
variant metal2vulkan::pipeline::RuntimeFact::Depth16Biased Depth16Biased
variant metal2vulkan::pipeline::RuntimeFact::Depth16Codes Depth16Codes { biased: bool }
variant metal2vulkan::pipeline::RuntimeFact::Depth16Pass Depth16Pass { depth16: bool }
variant metal2vulkan::pipeline::RuntimeFact::DepthClampRange DepthClampRange
variant metal2vulkan::pipeline::RuntimeFact::DeviceAddresses DeviceAddresses { slot: SlotRef }
variant metal2vulkan::pipeline::RuntimeFact::DispatchGrid DispatchGrid
@@ -13893,9 +13866,7 @@ variant metal2vulkan::pipeline::StorageFormatClass::Unknown Unknown
variant metal2vulkan::pipeline::StorageImageClass::AlphaInRed AlphaInRed
variant metal2vulkan::pipeline::StorageImageClass::HalfBits HalfBits
variant metal2vulkan::pipeline::StorageImageClass::HalfQuietNan HalfQuietNan
variant metal2vulkan::pipeline::StorageImageClass::HalfTowardZero HalfTowardZero
variant metal2vulkan::pipeline::StorageImageClass::Identity Identity
variant metal2vulkan::pipeline::StorageImageClass::OneBitAlpha OneBitAlpha
variant metal2vulkan::pipeline::StorageImageClass::RotateArgb RotateArgb
variant metal2vulkan::pipeline::StorageImageClass::SharedExponentBits SharedExponentBits
variant metal2vulkan::pipeline::StorageImageClass::SmallFloatQuietNan SmallFloatQuietNan
@@ -13909,7 +13880,6 @@ variant metal2vulkan::pipeline::Symbol::DescriptorSet DescriptorSet(ResourceSlot
variant metal2vulkan::pipeline::Symbol::Location Location(VaryingKey)
variant metal2vulkan::pipeline::Symbol::SpecId SpecId(SpecKey)
variant metal2vulkan::pipeline::SyntheticBinding::ArgumentTable ArgumentTable
variant metal2vulkan::pipeline::SyntheticBinding::ColorWriteTable ColorWriteTable
variant metal2vulkan::pipeline::SyntheticBinding::ConstantBlob ConstantBlob
variant metal2vulkan::pipeline::SyntheticBinding::ControlPointIndices ControlPointIndices
variant metal2vulkan::pipeline::SyntheticBinding::DepthStandIn DepthStandIn
Can't render this file because it is too large.
+2 -17
View File
@@ -759,7 +759,6 @@ surface! {
enum ResolveSource N;
const SRGB_RESOLVE_LINEAR;
const SRGB_RESOLVE_THRESHOLDS;
fn color_write_table;
fn depth_stencil_copy_modules;
fn stencil_split_module;
fn depth_split_module;
@@ -974,8 +973,6 @@ surface! {
struct DepthBias N;
enum DepthBiasUnit N;
fn depth_bias;
fn depth16_bias;
fn depth16_bias_side;
}
"metal::vertex" => metal2vulkan::metal::vertex {
fn vk_vertex_format;
@@ -1065,10 +1062,8 @@ use metal2vulkan::pipeline::{
use metal2vulkan::Budget;
/// `inputs` with the color writes `writes` (attachment, its channels' rules), the half-float
/// channels alone where `dev`'s driver converts a fragment's float writes as Metal does, and
/// elsewhere each attachment whose rules are each none, the device's, an 8-bit unorm channel's or a
/// half-float channel's, one of them a rounding, selected at the draw (`ChannelWrite::Selected`):
/// the inputs a fragment of a pipeline with those attachments compiles under.
/// channels alone where `dev`'s driver converts a fragment's float writes as Metal does: the
/// inputs a fragment of a pipeline with those attachments compiles under.
fn with_color_writes(
dev: &Device,
mut inputs: LoweringInputs,
@@ -1081,20 +1076,10 @@ fn with_color_writes(
signed: true,
};
let metal = dev.profile().takes_driver_deviation(metal);
// Whether a channel's rule rounds, or `None` where no code selects it.
let rounds = |r: Option<ChannelWrite>| match r {
None | Some(ChannelWrite::Device) => Some(false),
Some(r) => (r == ChannelWrite::Unorm { bits: 8 } || r == half).then_some(true),
};
let selects = |rules: &[Option<ChannelWrite>; 4]| {
let each: Option<Vec<bool>> = rules.iter().map(|&r| rounds(r)).collect();
each.is_some_and(|each| each.contains(&true))
};
inputs.color_writes = writes
.iter()
.map(|&(a, rules)| match metal {
true => (a, rules.map(|r| r.filter(|&r| r == half))),
false if selects(&rules) => (a, [Some(ChannelWrite::Selected); 4]),
false => (a, rules),
})
.filter(|(_, rules)| rules.iter().any(Option::is_some))
+19 -38
View File
@@ -1307,38 +1307,14 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
- `metal2vulkan-degrade-unorm-depth-bias` (precision). `UnormDepthBias`: A draw biases a
`Depth16Unorm` depth by a constant, or by a slope alone, which brings Metal's constant unit, on a
device whose driver is not measured to store Metal's codes so
(`DriverDeviation::MetalDepth16BiasedStores`), through a pipeline whose fragment stage does not
add the bias itself (more than one sample, early fragment tests, the draw's tests run in the
shader, a function that returns its depth or reads its position's depth). Elsewhere such a draw
runs the variant whose fragment stage adds the bias. Cost: a biased depth can store a code next
to Metal's: the device rounds the biased sum its own way, and without depthBiasExact counts the
bias in its own unit.
(`DriverDeviation::MetalDepth16BiasedStores`): the device biases and converts the depth. Cost: a
biased depth can store a code next to Metal's: the device rounds the biased sum its own way, and
without depthBiasExact counts the bias in its own unit.
- `metal2vulkan-degrade-unorm-depth-rounding` (precision). `UnormDepthRounding`: A draw tests or
writes a `Depth16Unorm` depth on a device whose driver is not measured to convert a depth to
Metal's code (`DriverDeviation::MetalDepth16Stores`), through a pipeline whose fragment stage
cannot write the code itself (more than one sample, early fragment tests, the draw's tests run
in the shader, a function that reads its position's depth and returns none), or through one
that does, in depth clamp mode through a viewport depth range an end of which lies inside
`(0, 1)`, where the device clamps the depth to that end. Cost: a depth
near a code's midpoint can store the code below Metal's: the device converts the depth to the
16-bit code its own way, where Metal rounds to nearest, a tie up.
- `metal2vulkan-degrade-shader-unorm-depth` (performance). `ShaderUnormDepth`: A draw tests or
writes a `Depth16Unorm` depth on a device whose driver is not measured to convert a depth to
Metal's code (`DriverDeviation::MetalDepth16Stores`, or for a biased draw
`DriverDeviation::MetalDepth16BiasedStores`), through a single-sampled pipeline whose fragment
stage writes each depth as Metal's code, its depth bias added in the shader (a pipeline without
a fragment function draws through a fragment stage of its own). The render pass's depth decides
it, whatever depth format the pipeline names. Cost: the fragment stage writes each depth as
Metal's code, about 50 more instructions per fragment, which keeps the device from testing the
depth before the stage runs. A biased draw whose bias has a known side
(`metal::state::depth16_bias_side`, every Vulkan depth range of the draw inside `[0, 1]`) runs a
stage that declares it (`DepthGreater` or `DepthLess`, counted by
`WorkCounts::depth16_sided_draws`), so the device may still test first where its test compares
that way (docs/FAST-PATHS.md's costs of matching Metal).
- `metal2vulkan-degrade-unorm-depth-slope` (precision). `UnormDepthSlope`: A draw biases a
`Depth16Unorm` depth by a slope through a fragment stage that adds Metal's bias itself. Cost:
the fragment stage takes the depth's slope from the depths of its 2x2 quad, where Metal takes
the triangle's own: a biased depth near a code's midpoint can store the code next to Metal's.
Metal's code (`DriverDeviation::MetalDepth16Stores`): the device converts the depth. Cost: a
depth near a code's midpoint can store the code below Metal's: the device converts the depth to
the 16-bit code its own way, where Metal rounds to nearest, a tie up.
- `metal2vulkan-degrade-point-guard-band` (precision). `PointGuardBand`: A draw of points keeps
Vulkan's clipping of points, where Metal's guard band cannot be emulated: in a rate-mapped pass,
on a device without `shaderClipDistance` or with too few clip distances beside the vertex
@@ -1494,10 +1470,10 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
the attachment's image takes no input attachment usage, a copy of its samples over the render
area into a scratch image first.
- `metal2vulkan-degrade-shader-color-conversion` (performance). `ShaderColorConversion`: A fragment
function writes a float to a normalized, sRGB or half-float color attachment on a device whose own
conversion is not Metal's (`StageModule::rounded_colors`). Cost: the fragment function rounds each
such channel to the code Metal stores before it writes it: about 35 more instructions per
normalized or half-float channel, and about 70 and one read of a 4 KiB table per sRGB channel.
function writes a float to a half-float color attachment of a pipeline under
`TextureWriteRoundingMode::NearestEven`, whose rounding no device's conversion gives
(`StageModule::rounded_colors`). Cost: the fragment function rounds each such channel to nearest
even before it writes it: about 35 more instructions per channel.
- `metal2vulkan-degrade-shader-half-color-bits` (performance). `ShaderHalfColorBits`: A fragment
function writes a `half` to a half-float color attachment as the bits of the half Metal stores,
through a 16-bit output, on a device that does not store a 32-bit output's NaN as Metal does
@@ -2821,10 +2797,15 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
raw sample (`heap_raw`).
- `metal2vulkan-degrade-device-color-conversion` (precision).
`PrecisionNote::DeviceColorConversion`: A fragment function writes a float to a color channel
whose conversion the device makes, not Metal's rule (`ChannelWrite::Device`): an attachment that
blends with factors other than one and zero, the alpha of attachment 0 under alpha-to-coverage, a
format whose conversion Metal was not measured with (the packed 16-bit unorm formats, `A8Unorm`,
the packed floats).
whose conversion the device makes where it is not measured to make Metal's: a normalized, sRGB or
small float channel on a device other than MoltenVK on an Apple GPU not measured to convert that
kind as Metal does, an attachment that blends with factors other than one and zero
(`ChannelWrite::Device`), the alpha of attachment 0 under alpha-to-coverage, a format whose
conversion Metal was not measured with (the packed 16-bit unorm formats, `A8Unorm`, the packed
floats). Near a tie between two codes the device may store the other one. Also a `float` texel a
function writes to a storage texture that may hold a normalized or half-float format, or
`ARGB8Unorm`, on a device not measured to store Metal's codes (or a 1-bit alpha, on one measured
to store every other normalized channel's).
- `metal2vulkan-degrade-device-interpolation` (precision). `PrecisionNote::DeviceInterpolation`: A
fragment function reads a varying the device interpolates (`center_perspective`, `centroid`,
`sample` or `no_perspective`, not `flat`) on a device not measured to interpolate as Metal does