rt: a render encoder sets the alpha test reference, and alpha-test states are made

A gap against the old runtime. rt refused every render state whose fragment
runs the private alpha test (PrivateRenderState::alpha_test_enabled with a
compare function other than Never or Always): the translator pushes
PushField::AlphaTestReference there, and render.rs draws() mapped no value for
it, so new_render_pipeline_state answered Gap::RenderPipeline { DrawInput }.
Nothing drew against an unfilled push word; Never and Always states, which read
no reference, were made and drew right.

Now RenderCommandEncoder::set_alpha_test_reference_value(f32) (Apple's
setAlphaTestReferenceValue: SPI) keeps the reference's 8-bit unorm code in the
encoder's state, Metal's 1 until set, not kept across encoders (the old
runtime's rule, from probes on an Apple M3 Max, macOS 27.0.1); draws() maps the
field to FieldValue::AlphaTestReference, and a draw pushes the code. A change of
code refills the push bytes; an equal one records nothing new. The code is the
translator's: bind::alpha_test_code, now public (api_surface row, docs/API.md
line), so rt and the binder compare as Metal does through one function.

Test: tests::alpha_test draws green at alpha 0.6 (code 153) under Greater, one
quadrant a draw through scissor rectangles: the default reference and 0.75
keep the clear, 0.25 (held across draws) draws, and a second encoder starts at
1 again (its whole-target draw changes nothing) until 0 draws. README and the
API signature table updated.

Verified: build and device legs follow.
This commit is contained in:
Anees Iqbal committed 2026-11-19 03:32:27 -08:00
1 parent e74d7ab714
commit f6032c796c
12 files changed
+187 -12

No files matched your search

+7
View File
@@ -1990,6 +1990,13 @@ or does not check is rebuilt from the generations' names, with young counted ful
references, the depth bias and the blend color, Metal's defaults where it set none. A vertex buffer slot serves
the vertex function's buffer argument of its index and the vertex descriptor's layout of its
index alike, a `set_vertex_bytes` copy too, read through the parameter ring's buffer.
- An encoder also holds the alpha test reference of OpenGL on Metal
(`set_alpha_test_reference_value`, Apple's `setAlphaTestReferenceValue:` SPI): 1 until the
encoder sets it, a reference set in an earlier encoder not kept, as an Apple M3 Max under macOS
27.0.1 keeps it. A state with the private alpha test (`PrivateRenderState::alpha_test_enabled`,
a compare function other than `Never` or `Always`) reads it at each draw, pushed as Metal's
8-bit unorm code (`metal2vulkan::bind::alpha_test_code`), and its fragment function compares its
color 0's alpha's code with it; a fragment that fails writes nothing.
- `draw_primitives` and `draw_indexed_primitives` are one `vkCmdDraw` or `vkCmdDrawIndexed` each.
A draw pushes its functions' fields in the one push range (the addresses of their buffer slots
plus offsets, the resource IDs of their textures and sampler states, the state's constexpr
+4 -2
View File
@@ -1328,8 +1328,10 @@ impl Parameters {
bytes[at..at + 32].copy_from_slice(stage_in);
}
}
// A compute content has neither (`pipeline::interface`).
FieldValue::Word(_) | FieldValue::TessellationFactors => {}
// A compute content has none of these (`pipeline::interface`).
FieldValue::Word(_)
| FieldValue::TessellationFactors
| FieldValue::AlphaTestReference => {}
}
}
self.block_address = (interface.block_len > 0).then_some(interface.block_address);
+4
View File
@@ -583,6 +583,10 @@ pub(crate) enum FieldValue {
/// (`setTessellationFactorBuffer:offset:instanceStride:`), which a post-tessellation vertex
/// function's control stage reads each patch's factors from.
TessellationFactors,
/// A `u32`: the render encoder's alpha test reference (`setAlphaTestReferenceValue:`) as the
/// 8-bit unorm code a fragment function under the private alpha test compares its color 0's
/// alpha with (`metal2vulkan::bind::alpha_test_code`), Metal's 1 until the encoder sets it.
AlphaTestReference,
}
/// A `VkPipeline`'s specialization: the threadgroup size, the threadgroup memory lengths in the
+3
View File
@@ -463,6 +463,9 @@ fn draws(
}
}
PushField::TessellationFactorAddress => FieldValue::TessellationFactors,
// The encoder's reference, which a fragment function under the private alpha test
// compares its color 0's alpha with.
PushField::AlphaTestReference => FieldValue::AlphaTestReference,
_ => return Err(draw_input()),
};
fields.push((offset, at, value));
+26 -2
View File
@@ -91,6 +91,7 @@ use crate::sampler::SamplerState;
use crate::shadow::{self, Area, Held};
use crate::texture::Texture;
use ash::vk;
use metal2vulkan::bind::alpha_test_code;
use metal2vulkan::metal::format::integer_channels_word;
use metal2vulkan::metal::state::{input_assembly, DepthStencilDescriptor};
use metal2vulkan::metal::{
@@ -459,6 +460,9 @@ pub struct RenderCommandEncoder {
/// The front and back stencil references, saturated to 8 bits.
stencil_reference: [u32; 2],
blend_color: [f32; 4],
/// The alpha test reference's 8-bit unorm code (`metal2vulkan::bind::alpha_test_code`),
/// Metal's 1 until set.
alpha_test: u32,
/// The depth bias's constant and slope scale, Metal's `depthBias` and `slopeScale`.
depth_bias: [f32; 2],
/// Whether the last draw recorded the depth bias enabled.
@@ -542,6 +546,7 @@ impl CommandBuffer {
winding: Winding::Clockwise,
stencil_reference: [0; 2],
blend_color: [0.0; 4],
alpha_test: alpha_test_code(1.0),
depth_bias: [0.0; 2],
biased: false,
recorded: None,
@@ -1051,6 +1056,22 @@ impl RenderCommandEncoder {
self.dirty |= BLEND;
}
/// `setAlphaTestReferenceValue:` (Apple SPI, of OpenGL on Metal): the reference a state with
/// the private alpha test (`PrivateRenderState::alpha_test_enabled` with a compare function
/// other than `Never` or `Always`) compares each fragment's color 0 alpha with, both as
/// Metal's 8-bit unorm codes (`metal2vulkan::bind::alpha_test_code`: a NaN taken as 0, the
/// value clamped to `[0, 1]`, the exact product with 255 rounded to nearest). It holds for the
/// encoder's later draws; each encoder starts at Metal's 1, and a reference set in an earlier
/// encoder is not kept (probes on an Apple M3 Max, macOS 27.0.1). Every value is accepted, as
/// on Metal. A draw of a state the test reads it in pushes its code; any other reads none.
pub fn set_alpha_test_reference_value(&mut self, value: f32) {
let code = alpha_test_code(value);
if code != self.alpha_test {
self.alpha_test = code;
self.push_filled = false;
}
}
/// The static precision note of a draw of triangles under a depth bias
/// ([`set_depth_bias`](Self::set_depth_bias)).
pub const DEPTH_BIAS_NOTE: PrecisionNote = PrecisionNote::DeviceDepthBias;
@@ -1737,7 +1758,7 @@ impl RenderCommandEncoder {
});
fill_push(
&mut self.push,
(&self.tables, self.facts.nil, factors),
(&self.tables, self.facts.nil, factors, self.alpha_test),
&self.moved,
&self.shadow_slots,
state,
@@ -2273,7 +2294,7 @@ fn primitives(primitive_type: PrimitiveType) -> Result<(vk::PrimitiveTopology, b
fn fill_push(
push: &mut Vec<u8>,
(tables, nil, factors): (&[Tables; 2], u64, u64),
(tables, nil, factors, alpha_test): (&[Tables; 2], u64, u64, u32),
moved: &[Moved],
shadow_slots: &[(usize, u32)],
state: &RenderPipelineState,
@@ -2322,6 +2343,9 @@ fn fill_push(
FieldValue::TessellationFactors => {
push[at..at + 8].copy_from_slice(&factors.to_le_bytes());
}
FieldValue::AlphaTestReference => {
push[at..at + 4].copy_from_slice(&alpha_test.to_le_bytes());
}
// A render content has no dispatch or stage-in region (`render::draws`).
FieldValue::DispatchRegion | FieldValue::StageInRegion => {}
}
@@ -0,0 +1,122 @@
//! The private alpha test of OpenGL on Metal (`PrivateRenderState::alpha_test_enabled` and
//! `alpha_test_function`), with the encoder's reference
//! (`RenderCommandEncoder::set_alpha_test_reference_value`), under a device cfg on every device of
//! the cfg's kind. The expected texels are Metal's rule as probed on an Apple M3 Max under macOS
//! 27.0.1 (the old runtime lane's `alpha_tests`, 413 rows): color 0's alpha and the reference are
//! each compared as 8-bit unorm codes, and an encoder compares against 1 until it sets the
//! reference, a reference set in an earlier encoder not kept.
//!
//! The fragment writes green at alpha 0.6, code 153, under `Greater`: the default reference (code
//! 255) and 0.75 (code 191) kill it, 0.25 (code 64) and 0 (code 0) keep it. One draw a quadrant,
//! through scissor rectangles, in two encoders.
//!
//! `llvm-as` assembles the functions; without it the test skips visibly.
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod on_device {
use crate::tests::command::on_device::each_device;
use crate::tests::draw::on_device::{
descriptor, examples, floats, pass, read, run, state, target, Buffers, SIDE,
};
use crate::{LoadAction, PixelFormat, PrimitiveType, ScissorRect, TextureUsage};
/// `MTLCompareFunctionGreater`.
const GREATER: u64 = 4;
/// The fragment's color: green at alpha 0.6, code 153 (the exact product with 255).
const COLOR: [f32; 4] = [0.0, 1.0, 0.0, 0.6];
/// The drawn texel, and the clear's.
const DRAWN: [u8; 4] = [0, 255, 0, 153];
const CLEAR: [u8; 4] = [0, 0, 0, 255];
/// The scissor rectangle of the quadrant at `[x, y]`, each 0 or 1, y down.
fn quadrant([x, y]: [u64; 2]) -> ScissorRect {
let half = u64::from(SIDE / 2);
ScissorRect {
x: x * half,
y: y * half,
width: half,
height: half,
}
}
/// A state with the alpha test on reads the encoder's reference, which holds for the encoder's
/// later draws and starts at 1 in each encoder: of four quadrants drawn in one encoder, the
/// one drawn before any reference and the one under 0.75 keep the clear, and the two under
/// 0.25 are drawn; a second encoder's draw of the whole target before it sets a reference
/// changes nothing, and its draw under 0 fills the quadrant the first encoder's 0.75 kept.
#[test]
fn every_device_alpha_tests_against_the_encoder_s_reference() {
let Some(library) = examples() else {
return;
};
let mut d = descriptor(&library, "colored_fragment", PixelFormat::RGBA8Unorm);
d.private.alpha_test_enabled = true;
d.private.alpha_test_function = GREATER;
each_device("alpha_test", |name, _, device| {
let state = state(name, &device, &d);
let mut buffers = Buffers::new(&device);
let positions = buffers.of(&device, &floats(&[-1.0, -1.0, 3.0, -1.0, -1.0, 3.0]));
let colors = buffers.of(&device, &floats(&[COLOR, COLOR, COLOR].concat()));
let color = target(
&device,
PixelFormat::RGBA8Unorm,
TextureUsage::RENDER_TARGET,
);
let queue = device.new_command_queue(4).expect("a queue");
let command_buffer = queue.command_buffer().expect("a command buffer");
let ok = |result: Result<(), crate::Error>| {
result.unwrap_or_else(|error| panic!("{name}: {error}"))
};
let mut loads = pass(&color, None);
loads.color_attachments[0].load_action = LoadAction::Load;
for (at, passed) in [pass(&color, None), loads].iter().enumerate() {
let mut encoder = (command_buffer.render_command_encoder(passed))
.unwrap_or_else(|error| panic!("{name}: {error}"));
ok(encoder.set_render_pipeline_state(&state));
ok(encoder.set_vertex_buffer(Some(&positions), 0, 0));
ok(encoder.set_vertex_buffer(Some(&colors), 0, 1));
// Each step: the reference set first where one is given, then a draw through the
// quadrant's rectangle, or the whole target's.
let steps: &[(Option<f32>, Option<[u64; 2]>)] = match at {
0 => &[
(None, Some([0, 0])),
(Some(0.75), Some([1, 0])),
(Some(0.25), Some([0, 1])),
(None, Some([1, 1])),
],
_ => &[(None, None), (Some(0.0), Some([1, 0]))],
};
for &(reference, rect) in steps {
if let Some(reference) = reference {
encoder.set_alpha_test_reference_value(reference);
}
encoder.set_scissor_rect(rect.map_or(
ScissorRect {
x: 0,
y: 0,
width: u64::from(SIDE),
height: u64::from(SIDE),
},
quadrant,
));
ok(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0));
}
encoder.end_encoding();
}
run(name, &command_buffer);
let half = SIDE / 2;
let want: Vec<u8> = (0..SIDE)
.flat_map(|y| (0..SIDE).map(move |x| (x, y)))
.flat_map(|(x, y)| match x < half && y < half {
true => CLEAR,
false => DRAWN,
})
.collect();
assert_eq!(read(&color, 4), want, "{name}: the texels");
println!(
"alpha_test: {name}: the default and 0.75 kept the clear, 0.25 and 0 drew, a second \
encoder started at 1"
);
});
}
}
+1
View File
@@ -1,3 +1,4 @@
mod alpha_test;
mod arrays;
mod blit;
mod cache;
+7 -5
View File
@@ -2804,11 +2804,13 @@ fn shadow_stencil_words(t: &ShadowTemplate, state: &BindState) -> Result<FieldBy
/// The `PushField::ShaderTestsState` words of a draw under encoder state `state`: the depth compare
/// function, write enable and clip mode, and viewport 0's depth range.
/// The 8-bit unorm code Metal's private alpha test compares the reference `reference` as
/// (`PushField::AlphaTestReference`, probes on an Apple M3 Max): NaN is 0, the value is clamped
/// to `[0, 1]`, and the code is the exact product with 255 rounded to nearest, as the fragment
/// function converts its alpha (`lower::arith::color_write::unorm8_code`). The product of an
/// `f32` and 255 is exact as an `f64`, and its only tie, at 0.5, rounds to 128 either way.
pub(crate) fn alpha_test_code(reference: f32) -> u32 {
/// (`setAlphaTestReferenceValue:`, Apple SPI; `PushField::AlphaTestReference`, probes on an Apple
/// M3 Max): NaN is 0, the value is clamped to `[0, 1]`, and the code is the exact product with
/// 255 rounded to nearest, as the fragment function converts its alpha
/// (`lower::arith::color_write::unorm8_code`). The product of an `f32` and 255 is exact as an
/// `f64`, and its only tie, at 0.5, rounds to 128 either way. A runtime fills the push field with
/// it.
pub fn alpha_test_code(reference: f32) -> u32 {
let clamped = match reference.is_nan() {
true => 0.0,
false => f64::from(reference.clamp(0.0, 1.0)),
+2 -2
View File
@@ -233,8 +233,8 @@ pub use extended_canonical::{
};
pub use extended_shadow::{extended_shadow_module, ExtendedShadowModule};
pub use graphics::{
DrawCall, DrawCommands, IndexOverrun, MeshDispatch, MeshGroups, MeshRecordsRegion, SlotRebinds,
TessellationDispatch, TessellationRecords,
alpha_test_code, DrawCall, DrawCommands, IndexOverrun, MeshDispatch, MeshGroups,
MeshRecordsRegion, SlotRebinds, TessellationDispatch, TessellationRecords,
};
pub use heap::{
handle_entry, handle_entry_flags, heap_classes, heap_element, heap_raw_form, HeapElement,
@@ -6103,6 +6103,7 @@ fn metal2vulkan-runtime::process_exiting pub fn process_exiting() -> bool
fn metal2vulkan-runtime::program_instance_made pub fn program_instance_made()
fn metal2vulkan-runtime::sampler_border_color pub fn sampler_border_color(raw: u64) -> SamplerBorderColor
fn metal2vulkan::ash_interop::sampler_create_info pub fn sampler_create_info<'a>(desc: &vk::SamplerDesc, reduction: &'a mut ash::vk::SamplerReductionModeCreateInfo<'static>, border: &'a mut ash::vk::SamplerBorderColorComponentMappingCreateInfoEXT<'static>) -> ash::vk::SamplerCreateInfo<'a>
fn metal2vulkan::bind::alpha_test_code pub fn alpha_test_code(reference: f32) -> u32
fn metal2vulkan::bind::astc_decode_module pub fn astc_decode_module(device: &Device, decode: AstcDecode, texels: AstcTexels) -> Result<BlockDecodeModule, Error>
fn metal2vulkan::bind::check_draw_modules pub fn check_draw_modules(device: &Device) -> Result<CheckDrawModules, Error>
fn metal2vulkan::bind::chroma_convert_module pub fn chroma_convert_module(device: &Device, decode: ChromaDecode) -> Result<ChromaConvertModule, Error>
@@ -9687,6 +9688,7 @@ method metal2vulkan-rt::RenderCommandEncoder::draw_patches pub fn draw_patches(&
method metal2vulkan-rt::RenderCommandEncoder::draw_primitives pub fn draw_primitives(&mut self, primitive_type: PrimitiveType, vertex_start: u32, vertex_count: u32, instance_count: u32, base_instance: u32) -> Result<(), Error>
method metal2vulkan-rt::RenderCommandEncoder::end_encoding pub fn end_encoding(mut self)
method metal2vulkan-rt::RenderCommandEncoder::memory_barrier pub fn memory_barrier(&mut self) -> Result<(), Error>
method metal2vulkan-rt::RenderCommandEncoder::set_alpha_test_reference_value pub fn set_alpha_test_reference_value(&mut self, value: f32)
method metal2vulkan-rt::RenderCommandEncoder::set_blend_color pub fn set_blend_color(&mut self, red: f32, green: f32, blue: f32, alpha: f32)
method metal2vulkan-rt::RenderCommandEncoder::set_color_store_action pub fn set_color_store_action(&mut self, action: StoreAction, index: usize) -> Result<(), Error>
method metal2vulkan-rt::RenderCommandEncoder::set_cull_mode pub fn set_cull_mode(&mut self, mode: CullMode)
Can't render this file because it is too large.
+1
View File
@@ -496,6 +496,7 @@ surface! {
enum IndirectArgs N;
enum DrawCall N;
struct DrawCommands N;
fn alpha_test_code;
enum IndexOverrun N;
struct MeshDispatch N;
enum MeshGroups N;
+8 -1
View File
@@ -159,7 +159,14 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`:
consumer pushes for it (`PushField::ConstexprSampler`), where the consumer places the device
sampler `CombinedSampler::constexpr_sampler` describes, normalized: the shader scales a pixel
sampler's coordinate. An integer write to a storage slot without a format saturates to the channel
widths the consumer pushes (`PushField::TextureIntegerChannels`). Every precision note is
widths the consumer pushes (`PushField::TextureIntegerChannels`). A fragment function under the
pipeline's private alpha test (`PrivateRenderState::alpha_test_enabled`, a compare function other
than `Never` or `Always`) compares its color 0's alpha with the code the consumer pushes
(`PushField::AlphaTestReference`): `bind::alpha_test_code` of the encoder's
`setAlphaTestReferenceValue:`, 1 until the encoder sets it. It is Metal's 8-bit unorm code of the
reference (a NaN taken as 0, clamped to `[0, 1]`, the exact product with 255 rounded to
nearest), the form the function converts its alpha to, so a consumer that pushes it compares as
Metal does. Every precision note is
static there: no constant or binder decides one. So far they lower a kernel that reaches memory
through its buffer slots and reads, writes, sizes or tests for nil its texture slots and its
argument buffers' textures, and samples its texture slots through its runtime sampler slots