runtime: apply the translator's private sample mask to render pipelines

The translator states GraphicsState::sample_mask: the descriptor's private sampleMask and
sampleCoverage as one Vulkan pSampleMask word, wherever Vulkan's mask keeps the samples Metal's
keeps (otherwise the fragment function applies the masks itself, or the translator refuses the
pipeline). The runtime's render pipelines dropped it. make() chained no pSampleMask, and neither
refuse() nor unbuilt() named the field, so a state made with a guest's private mask wrote every
sample: at one sample with bit 0 clear, Metal draws no colour and the runtime drew all of it. The
consumer passes the guest's private sample mask and coverage to the runtime's descriptor. The
deleted runtime applied the field (pipeline/graphics.rs in 5d725aeec7^, the multisample state's
sample_mask), so the cutover dropped it.

Fixed now carries the mask and make() chains it, as ceil(samples / 32) words, Vulkan's length for
pSampleMask; a word past the first keeps every sample. A pipeline needs no new key: the content key
(queried_render_descriptor_key) already destructures PrivateRenderState in full and hashes
sample_mask, sample_coverage and sample_coverage_invert, so two masks are two contents, each with
its own VkPipelines. The new_render_pipeline_state doc said "one sample" and that the runtime
refuses everything else the translator states; it now lists the raster sample count, the private
sample mask and coverage, and the logic operation.

Test: every_device_keeps_only_the_samples_of_a_private_sample_mask (device cfgs). spc_num_samples
fills an R32Uint target that a pass clears to 0. The state without a mask, made first, draws 1 at
one sample. The state with mask 0 on the same device leaves every pixel at 0, which fails without
this change. At 4 samples, mask 0b0101 writes samples 0 and 2 only (4, 0, 4, 0 per pixel, read
back by ido_samples). Compile and lavapipe jobs are named in the landing note.
This commit is contained in:
Anees Iqbal committed 2026-11-20 16:01:49 -08:00
1 parent 0d13f947b6
commit 38d67fc285
2 files changed
+143 -4

No files matched your search

+21 -4
View File
@@ -237,7 +237,8 @@ struct Module {
}
/// The fixed-function state of a content's `VkPipeline`s, as Vulkan takes it: the descriptor's
/// vertex layout, attachments, blending and sample count, as the translator states them.
/// vertex layout, attachments, blending, sample count and private sample mask, as the translator
/// states them.
struct Fixed {
bindings: Vec<vk::VertexInputBindingDescription>,
/// Each instance-rate binding's divisor other than 1, a per-instance step rate the translator
@@ -249,6 +250,10 @@ struct Fixed {
alpha_to_coverage: bool,
/// `alphaToOneEnabled`, the device's own (`alphaToOne`, which the floor requires).
alpha_to_one: bool,
/// The descriptor's private sample mask and sample coverage as one mask of the samples the
/// draws write (`GraphicsState::sample_mask`), Vulkan's `pSampleMask`; `None` where it keeps
/// every sample or the fragment function applies it itself.
sample_mask: Option<u32>,
blends: Vec<vk::PipelineColorBlendAttachmentState>,
/// The logic operation the translator states (private render state), the device's own
/// (`logicOp`, which the floor requires); `None` with the operation off, or copy or no-op,
@@ -290,8 +295,9 @@ impl crate::Device {
/// Built: one vertex and at most one fragment function, colour attachments of any format the
/// translator maps for the device, a depth and a stencil attachment of a format the device
/// renders depth or stencil in (its format query, through the translator's mapping; another
/// is the translator's refusal), one sample, and every blend state,
/// write mask and vertex descriptor of static strides Vulkan's fixed-function state takes with
/// is the translator's refusal), the raster sample count with the private sample mask and
/// sample coverage, the private logic operation, and every blend state, write mask and
/// vertex descriptor of static strides Vulkan's fixed-function state takes with
/// what device creation enables; what else the translator states is refused at the creation,
/// by kind.
///
@@ -767,6 +773,7 @@ impl Fixed {
samples: vk::SampleCountFlags::from_raw(g.rasterization_samples.as_raw()),
alpha_to_coverage: g.alpha_to_coverage,
alpha_to_one: g.alpha_to_one,
sample_mask: g.sample_mask,
blends,
logic_op: (g.logic_op).map(|op| vk::LogicOp::from_raw(op.as_raw())),
colors,
@@ -1101,10 +1108,20 @@ impl RenderCompiled {
if topology == vk::PrimitiveTopology::LINE_LIST && !lines_by_device_rule(fixed) {
rasterization = rasterization.push_next(&mut line);
}
let multisample = vk::PipelineMultisampleStateCreateInfo::default()
// The private sample mask, which the translator states (`GraphicsState::sample_mask`)
// where Vulkan's mask keeps the samples Metal's keeps. Its one word is the first 32
// samples'; Vulkan's
// `pSampleMask` "has a length equal to ⌈rasterizationSamples / 32⌉ words", and a second
// keeps every sample past them.
let words = fixed.sample_mask.map(|mask| [mask, u32::MAX]);
let count = fixed.samples.as_raw().div_ceil(32) as usize;
let mut multisample = vk::PipelineMultisampleStateCreateInfo::default()
.rasterization_samples(fixed.samples)
.alpha_to_coverage_enable(fixed.alpha_to_coverage)
.alpha_to_one_enable(fixed.alpha_to_one);
if let Some(words) = &words {
multisample = multisample.sample_mask(&words[..count.min(words.len())]);
}
let depth_stencil = vk::PipelineDepthStencilStateCreateInfo::default();
let mut blend = vk::PipelineColorBlendStateCreateInfo::default().attachments(&fixed.blends);
if let Some(op) = fixed.logic_op {
@@ -3204,4 +3204,126 @@ define internal void @_GLOBAL__sub_I_() section "air.static_init" {
println!("{name}: each state drew its own sample count");
});
}
/// A descriptor's private sample mask keeps only its samples' colours, as Metal ANDs it with
/// the coverage (`GraphicsState::sample_mask`): `spc_num_samples` returns the sample count
/// into an `R32Uint` `SIDE` square cleared to 0, covered by `ido_full`'s fullscreen triangle.
/// At one sample the state of a mask of 0 leaves every pixel at its clear, where the state of
/// the same functions without a mask, made first on the same device, draws 1: a mask is part
/// of the content, so neither state's pipeline serves the other. At 4 samples a mask of
/// `0b0101` writes samples 0 and 2 alone, each copied out by `ido_samples`.
#[test]
fn every_device_keeps_only_the_samples_of_a_private_sample_mask() {
let (Some(counts), Some(order)) = (
library(&engine_dir().join("spc_num_samples.ll")),
library(&engine_dir().join("ido_draw_order.ll")),
) else {
return;
};
let function = |library: &Library, name: &str| {
StageSource::Function(FunctionDescriptor::new(
library.function(name).expect("the function"),
))
};
let descriptor = |samples, mask| {
let mut d = RenderPipelineDescriptor::new(function(&order, "ido_full"));
d.fragment = Some(function(&counts, "spc_num_samples"));
d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::R32Uint));
d.raster_sample_count = samples;
d.private.sample_mask = mask;
d
};
let (unmasked, masked, odd) = (
descriptor(1, u64::MAX),
descriptor(1, 0),
descriptor(4, 0b0101),
);
each_device("private_sample_mask", |name, _, device| {
let draw = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}"));
let queue = device.new_command_queue(4).expect("a queue");
for (d, expected) in [(&unmasked, 1), (&masked, 0)] {
let made = state(name, &device, d);
let flat = target(&device, PixelFormat::R32Uint, TextureUsage::RENDER_TARGET);
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut encoder = (command_buffer.render_command_encoder(&pass(&flat, None)))
.unwrap_or_else(|error| panic!("{name}: {error}"));
draw(encoder.set_render_pipeline_state(&made));
draw(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0));
encoder.end_encoding();
run(name, &command_buffer);
let bytes = read(&flat, 4);
let words: Vec<u32> = (bytes.as_chunks::<4>().0.iter())
.map(|&word| u32::from_le_bytes(word))
.collect();
let mask = d.private.sample_mask;
assert_eq!(
words,
[expected; (SIDE * SIDE) as usize],
"{name}: one sample under the mask {mask:#x}"
);
}
(device.grant_indices(IndexClass::Texture, 1, 1))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let mut td = TextureDescriptor::new(
TextureType::Type2DMultisample,
PixelFormat::R32Uint,
SIDE,
SIDE,
);
td.sample_count = 4;
td.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ;
td.storage_mode = StorageMode::Private;
let samples = match device.new_texture(&td, Some(1)) {
Ok(samples) => samples,
Err(Error::Limit(crate::Limit::TextureSamples { .. })) => {
println!("{name}: one sample masked; no 4-sample R32Uint target to mask four");
return;
}
Err(error) => panic!("{name}: {error}"),
};
let four = state(name, &device, &odd);
let function = order.function("ido_samples").expect("the kernel");
let kernel = (device.new_compute_pipeline_state(
&crate::ComputePipelineDescriptor::new(StageSource::Function(
FunctionDescriptor::new(function),
)),
|samplers| Ok(vec![0; samplers.len()]),
))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let mut buffers = Buffers::new(&device);
let out = buffers.of(&device, &[0xffu8; 4 * 4 * (SIDE * SIDE) as usize]);
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut encoder = (command_buffer.render_command_encoder(&pass(&samples, None)))
.unwrap_or_else(|error| panic!("{name}: {error}"));
draw(encoder.set_render_pipeline_state(&four));
draw(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0));
encoder.end_encoding();
let mut compute = (command_buffer.compute_command_encoder(crate::DispatchType::Serial))
.expect("an encoder");
compute
.set_compute_pipeline_state(&kernel)
.expect("the state");
compute.set_texture(Some(&samples), 0).expect("a texture");
compute.set_buffer(Some(&out), 0, 0).expect("a buffer");
(compute.dispatch_threadgroups([1, 1, 1], [SIDE, SIDE, 1]))
.unwrap_or_else(|error| panic!("{name}: {error}"));
compute.end_encoding();
run(name, &command_buffer);
let contents = out.contents().expect("a Shared buffer");
// SAFETY: the buffer holds four words for each of the `SIDE` square's pixels, which
// the finished dispatch wrote and whose writes reach the host.
let words = unsafe {
std::slice::from_raw_parts(
contents.as_ptr().cast::<u32>(),
4 * (SIDE * SIDE) as usize,
)
};
for (pixel, got) in words.chunks(4).enumerate() {
assert_eq!(got, [4, 0, 4, 0], "{name}: pixel {pixel}'s samples");
}
drop(samples);
println!("{name}: each mask kept its own samples");
});
}
}