diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 02349ba96..7e1ba64c6 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -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 diff --git a/crates/metal2vulkan-rt/src/encoder.rs b/crates/metal2vulkan-rt/src/encoder.rs index 334f1a355..bf33a8947 100644 --- a/crates/metal2vulkan-rt/src/encoder.rs +++ b/crates/metal2vulkan-rt/src/encoder.rs @@ -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); diff --git a/crates/metal2vulkan-rt/src/pipeline.rs b/crates/metal2vulkan-rt/src/pipeline.rs index 811b8d1d6..d90f74047 100644 --- a/crates/metal2vulkan-rt/src/pipeline.rs +++ b/crates/metal2vulkan-rt/src/pipeline.rs @@ -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 diff --git a/crates/metal2vulkan-rt/src/render.rs b/crates/metal2vulkan-rt/src/render.rs index 41393edaf..e722e980a 100644 --- a/crates/metal2vulkan-rt/src/render.rs +++ b/crates/metal2vulkan-rt/src/render.rs @@ -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)); diff --git a/crates/metal2vulkan-rt/src/render_encoder.rs b/crates/metal2vulkan-rt/src/render_encoder.rs index 096058e49..53168d194 100644 --- a/crates/metal2vulkan-rt/src/render_encoder.rs +++ b/crates/metal2vulkan-rt/src/render_encoder.rs @@ -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, - (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 => {} } diff --git a/crates/metal2vulkan-rt/src/tests/alpha_test.rs b/crates/metal2vulkan-rt/src/tests/alpha_test.rs new file mode 100644 index 000000000..85e447d1b --- /dev/null +++ b/crates/metal2vulkan-rt/src/tests/alpha_test.rs @@ -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, 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 = (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" + ); + }); + } +} diff --git a/crates/metal2vulkan-rt/src/tests/mod.rs b/crates/metal2vulkan-rt/src/tests/mod.rs index 78295644d..7c5c3e1b6 100644 --- a/crates/metal2vulkan-rt/src/tests/mod.rs +++ b/crates/metal2vulkan-rt/src/tests/mod.rs @@ -1,3 +1,4 @@ +mod alpha_test; mod arrays; mod blit; mod cache; diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index e94bcf1a8..0451e3673 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -2804,11 +2804,13 @@ fn shadow_stencil_words(t: &ShadowTemplate, state: &BindState) -> Result 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)), diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index 99a9c62dc..441ed4336 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -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, diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index d185d7af0..5a6bfaee4 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -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 fn metal2vulkan::bind::check_draw_modules pub fn check_draw_modules(device: &Device) -> Result fn metal2vulkan::bind::chroma_convert_module pub fn chroma_convert_module(device: &Device, decode: ChromaDecode) -> Result @@ -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) diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 2a69494af..8d3e121dd 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -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; diff --git a/docs/API.md b/docs/API.md index 7a8c32390..404c3a860 100644 --- a/docs/API.md +++ b/docs/API.md @@ -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