Take the device's own Depth16 bias and its store of an extended-range, padded or bfloat attachment's untouched texels

The device's depth bias unit on every format, and the device's store of untouched texels in
place of the unused-bits load pass (deleted with its capture machinery); the NaN depth
discard documented as capability. SEMANTICS 1910, RUNTIME 1682.

One work packet, landed as 7 commit(s) (88bcfeaea8..6aec9db4e9 on archive/development-linear-2026-10-28-evening), in order:

* Take the device's depth bias on a Depth16Unorm depth

Rule 1: the device's depth bias is its native form, so it is the only one. A
constant bias (or a slope alone) on a Depth16Unorm depth was recorded through
VK_EXT_depth_bias_control's depthBiasExact as Metal's own rule, c + 1 units of
1/65535 for c of 0 or more and c - 1 below (one unit for a slope alone), in
depth (floatRepresentation) or in 2^-16. Now `metal::state::depth_bias` hands
Metal's constant to vkCmdSetDepthBias in the device's own unit r on every depth
format; Vulkan leaves a fixed-point format's r to the implementation, at most
2 x 2^-16 ("Depth Bias", primsrast.adoc).

Deleted, nothing reading them any more: `depth16_units`, `DepthBiasUnit` and
`DepthBias::unit`, the `depth_format` parameter of `depth_bias` and of the
runtime's `vk_depth_bias`; the runtime's vkCmdSetDepthBias2EXT path
(`DepthBiasCommand`, `depth_bias_command`, the record's pinned representation,
the device's command, its priming and `DEPTH_BIAS_CALLS`, the exit guard's and
recorder's `CmdSetDepthBias2`, `Logged::SetDepthBias2` and its thunk, so
`CommandsReplayed::cmd_set_depth_bias2` goes). VK_EXT_depth_bias_control is
still described but no longer consumed, so the core recommends enabling neither
it nor its three features.

RADV on the 780M no longer takes DriverDeviation::MetalDepth16BiasedStores: it
was measured through the exact unit. MoltenVK keeps it (it hands Metal its
constant, by construction). Elsewhere `unorm-depth-bias` announces the device's
bias; its cost text, docs/API.md's entry, the deviation and property docs and a
new FAST-PATHS device-gap row state it.

Tests: `metal::state::a_unorm_depth_bias_is_metals_constant_in_the_devices_unit`
(the constant as given on lavapipe, NVIDIA and MoltenVK, which have
depthBiasExact or not); the recommendation test leaves the extension and its
features out; the driver-facts test drops RADV's row; the exit-guard tests lose
the priming group and render_state.rs as a keeper of the device's functions.
api_signatures blessed (DepthBiasUnit, DepthBias::unit, depth_bias's signature);
the refusal surface is unchanged. Not bumped here: RUNTIME_VERSION (the versions
commit) and the runtime-sources pin (landing).

Verified: cargo clippy -p metal2vulkan -p metal2vulkan-runtime
-p metal2vulkan-validation --all-targets --all-features -D warnings; nextest of
metal::state, device::tests::{enables,driver_facts,profile}, tests::fast_paths,
api_surface, api_signatures, exit_guard, render_state, degradation_catalogue,
draw_shape_notices and ash_interop: 159 passed.

* Cite the spec that leaves a NaN fragment depth undefined, which makes its discard capability

The native-arithmetic audit asked whether `clamp_depth`'s discard of a positive NaN
depth, on every profile, emulates Metal where the device has a native form. It does
not: Vulkan defines no answer for such a depth. "Depth Clamping and Range
Adjustment" (fragops.adoc, 35.10.1): "If zf is not in the range [zmin, zmax],
then zf is undefined following this step", with or without depthClampEnable, and a
NaN lies in no range; only depthClampZeroOne, which no profile enables, keeps a
float depth unchanged (and then the comparison of a NaN would still pass ALWAYS
and NOT_EQUAL, where Metal's fails every test). So the discard stays, as
capability, and the comment says why, so a later audit does not re-raise it.

Docs only (a doc comment); no behaviour changes.

Verified: cargo fmt --all.

* Drop the cube's unmeasured gradient route from the anisotropic tests' profile comment

The route was deleted with the native cube gradients; the comment still named it as a second
home of the anisotropic emulation. Only a profile without samplerAnisotropy emulates it now.

Verified: comment only; git grep finds no other mention of the unmeasured gradient route.

* Keep the device's store of an extended-range, padded or bfloat attachment's untouched texels

What: a render pass that loads and stores a color attachment of an extended-range, padded
10-bit or bfloat format now keeps the bytes its draws do not write, the device's own load and
store (VK_ATTACHMENT_STORE_OP_STORE of a loaded attachment), on every device. The runtime no
longer reproduces Metal's tile store: the load pass that rewrote the texels' unused bits before
the pass (render/unused_bits_load.rs, bind::unused_bits_module), the capture replay that found
the tiles a pass's draws reach for it (render/capture.rs, bind::capture_assembly_module,
capture_settle_module, tile_reach_module, the translator's capture form
LoweringInputs/VariantKey::captured_positions, CaptureForm, RuntimeFact::CapturedPositions,
PushField/PushHole::CaptureAddress, Feature::TileReach, StatusBits::CAPTURED_REACH_UNMEASURED,
StatusReport::captured_reach_unmeasured) and the pipeline states' capture forms are deleted, with
ExtendedRange::load_code, Degradation::UnreachedTilesRewritten and the WorkCounts fields
unused_bits_load_passes, unused_bits_load_texels and capture_reach_*. Every draw in such a pass
announces extended-range-bits-kept, naming the attachments (render/tile_store.rs, the renamed
module); its catalogue entry, the FAST-PATHS device-gap row and the format docs state what
differs: the unused bits, BGRA10_XR's alpha clamp, a padded sRGB twin's table and a bfloat code
through half, which Metal's pass rewrites in each tile a draw reaches. snorm-minimum-kept and
shared-exponent-kept are unchanged (TileStoreIsMetals still says where the device's store is
Metal's).

The de-indexed and private list forms keep the index read the capture form shared
(PushField::CaptureIndexAddress, CaptureLayout, CapturedIndex); the binder's de-indexed draw no
longer goes through the capture draw, and the vertex function's strip restart return, which only
the capture form's layout could take (a de-indexed strip is NotImplemented(PrimitiveId)), is
gone.

Why: the owner's rule 1. The device has a native load and store; reproducing Metal's tile store
emulated Metal's bits where the device has a native form. The difference is recorded and
announced (rule 2).

Verified: cargo clippy -D warnings, all targets and features, over metal2vulkan,
metal2vulkan-runtime, metal2vulkan-validation and metal2vulkan-conformance, plain and with
--cfg m2v_gpu: clean. api_signatures blessed, REFUSALS.md regenerated. The test runs (translator
and runtime suites, the touched validation lanes on lavapipe and on the M3 Max's MoltenVK) follow
this commit and are reported with the lane.

* Bump the semantics and runtime versions for the device's tile store and depth bias

What: SEMANTICS_VERSION 1907 -> 1908 and RUNTIME_VERSION 1681 -> 1682.

Why: SEMANTICS_VERSION, because the translator's output changes under unchanged keys: the
de-indexed and private list vertex forms no longer carry the strip restart return, and the
capture form, its runtime fact and its push field are gone. RUNTIME_VERSION, because runs of
unchanged artifacts now do something else: a Depth16Unorm depth takes the device's depth bias
(no depthBiasExact or unit rescale), and a pass that loads an extended-range, padded or bfloat
attachment keeps its untouched texels' bytes (no unused-bits load pass, no capture replay) and
announces extended-range-bits-kept. ARTIFACT_FORMAT_VERSION stays: the codec tags variants by
name, and the removed ones (CaptureForm, PushField::CaptureAddress,
RuntimeFact::CapturedPositions) leave their tags unused, so an old entry holding one is a miss.

Verified: the constants alone change; the golden tables and the runtime-sources pin are
re-blessed at landing.

* Hold the lanes and the fact census to the device's store of untouched texels

What: three runtime lanes still expected Metal's tile store after 5e710fb988 made the device's
store the only form, and the mechanism test still counted the deleted
RuntimeFact::CapturedPositions.
- extended_range_blends::a_pass_of_extended_range_and_padded_colors_names_each_loaded_color:
  the padded colors, which the function does not write, keep their bytes (all ones), where
  Metal's pass leaves each word 0xffc0.
- extended_range_blends::a_fetched_two_plane_attachment_written_unblended_stores_metals_write:
  color 2, loaded and unwritten, keeps its bytes, where Metal's pass zeroes its color words' top
  two bits.
- extended_range_blend_table::a_memoryless_color_2_blends_as_a_stored_color_does: the stored
  color 0's bands are compared with the unused bits as Metal's pass leaves them
  (as_metal_leaves), the codes exactly, as the table's other passes already are.
- device::tests::mechanism: the variant census is 0..89 (MergedDraws takes the freed index).

Why: the lanes held the deleted exact form; the device's store is now the contract and
extended-range-bits-kept announces the difference.

Verified: on the M3 Max (MoltenVK, --cfg m2v_gpu, under maclock and memcap) the three lanes and
the rest of extended_range_blends pass (11 of 11, with waiter_submits, which failed once under a
load of 40 and passed on its rerun); on plain, device::tests::mechanism and tests::fast_paths
pass (12 of 12); clippy -D warnings clean, plain and --cfg m2v_gpu, over the four crates.

* 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 21:19:28 +02:00
1 parent 487e23f3ee
commit bd3c50d741
123 files changed
+955 -19351

No files matched your search

@@ -241,13 +241,13 @@ impl Case for ExtendedRangeBlend {
// what this M3 Max and lavapipe both show -- and one that does not shows the code. The
// allowance fails the case if the notice stops firing, so it cannot outlive its reason.
//
// The pass loads and stores an extended-range colour attachment, so our load pass
// (`render/unused_bits_load.rs`) rewrites every 32 x 32 tile of the render area where
// Metal's rewrites only the tiles a draw's primitives reach, announced as
// `unreached-tiles-rewritten`. The difference it names cannot reach this case: the draw is
// one full-screen triangle over the whole 128 x 64 target, so every tile is a reached
// tile, and every stored code compares exactly on MoltenVK and on lavapipe alike. So this
// is a declaration of what our side announced and not a tolerance -- no code is loosened.
// The pass loads and stores an extended-range colour attachment, so its draw announces
// `extended-range-bits-kept`: the device's store keeps the bits the codes leave unused in
// the texels the draw does not write, where Metal's pass makes them canonical. The
// difference it names cannot reach this case: the draw is one full-screen triangle over
// the whole 128 x 64 target under every channel, so it writes every texel, and every
// stored code compares exactly. So this is a declaration of what our side announced and
// not a tolerance -- no code is loosened.
//
// The two extended-range blend kinds (`extended-range-blend-source` and
// `extended-range-blends-stored-codes`) are deliberately **not** named here: neither fired
@@ -268,7 +268,7 @@ impl Case for ExtendedRangeBlend {
.chain(
[
Degradation::HalfOutputFastMathBlend,
Degradation::UnreachedTilesRewritten,
Degradation::ExtendedRangeBitsKept,
]
.into_iter()
.map(|kind| crate::replay::notice_allowance(kind.code())),
@@ -169,10 +169,6 @@ const PASS_NOTICES: &[Degradation] = &[
Degradation::SnormMinimumKept,
// The same for an `RGB9E5Float` word Metal's store normalizes.
Degradation::SharedExponentKept,
// A load pass's rewrite of the tiles no fragment reached, which only an extended-range, padded
// 10-bit or bfloat attachment takes (`render/unused_bits_load.rs`); none of this family's
// formats takes one.
Degradation::UnreachedTilesRewritten,
];
/// The bytes of a `SIDE` by `SIDE` target of `texel` bytes a texel whose every channel holds
@@ -1414,7 +1414,6 @@ impl Gpu for Runtime {
"replayed_cmd_set_color_write_mask",
replayed.cmd_set_color_write_mask,
),
("replayed_cmd_set_depth_bias2", replayed.cmd_set_depth_bias2),
(
"replayed_cmd_bind_index_buffer2",
replayed.cmd_bind_index_buffer2,
@@ -1484,17 +1483,6 @@ impl Gpu for Runtime {
("color_resolve_passes_made", c.color_resolve_passes_made),
("color_resolve_passes_kept", c.color_resolve_passes_kept),
("ahead_nanos", c.ahead_nanos),
("unused_bits_load_passes", c.unused_bits_load_passes),
("unused_bits_load_texels", c.unused_bits_load_texels),
("capture_reach_passes", c.capture_reach_passes),
("capture_reach_primitives", c.capture_reach_primitives),
("capture_reach_tiles_found", c.capture_reach_tiles_found),
("capture_reach_tiles_bound", c.capture_reach_tiles_bound),
("capture_reach_bound_passes", c.capture_reach_bound_passes),
(
"capture_reach_narrower_passes",
c.capture_reach_narrower_passes,
),
("driver_diagnostics_withheld", c.driver_diagnostics_withheld),
("memory_blocks_live", c.memory_blocks_live),
("empty_memory_blocks_live", c.empty_memory_blocks_live),
+3 -46
View File
@@ -134,10 +134,6 @@ pub(super) struct Tables<'a> {
tile_memory: Option<&'a Buffer>,
/// The address-mode maps the command's runtime samplers are bound with (`address_map.rs`).
sampler_maps: SamplerMaps,
/// A capture draw's addresses (`render/capture.rs`): of its first capture record, and of its
/// first index where it is indexed. Its `PushHole::CaptureAddress` and
/// `PushHole::CaptureIndexAddress` take them.
capture: Option<(u64, Option<u64>)>,
/// A de-indexed draw's first index's address (`VariantKey::primitive_id_indices`): its
/// `PushHole::CaptureIndexAddress` takes it.
indices: Option<u64>,
@@ -180,7 +176,6 @@ impl<'a> Tables<'a> {
control_point_indices: None,
tile_memory: None,
sampler_maps: SamplerMaps::default(),
capture: None,
indices: None,
snapshots: None,
merged_header: None,
@@ -206,15 +201,6 @@ impl<'a> Tables<'a> {
.is_some_and(|s| s.slots.contains(&slot.index))
}
/// The tables, with a capture draw's addresses: of its first capture `records`, and of its
/// first index (`indices`) where it is indexed (`render/capture.rs`).
pub(super) fn with_capture(self, records: u64, indices: Option<u64>) -> Tables<'a> {
Tables {
capture: Some((records, indices)),
..self
}
}
/// The tables, with a merged draw replay's header's address (`Tables::merged_header`).
pub(super) fn with_merged_header(self, address: u64) -> Tables<'a> {
Tables {
@@ -725,24 +711,13 @@ pub(super) fn bind_into(
PushHole::CommandRecordsAddress { .. } => {
return Err(Error::NotImplemented(RuntimeGap::CommandReplay));
}
// A capture draw's first record, and its first index where it is indexed
// (`Tables::with_capture`).
PushHole::CaptureAddress { stages, offset } => Hole {
stages: stages.into(),
offset,
address: tables
.capture
.map(|(records, _)| records)
.ok_or_else(|| internal("a capture hole without capture records"))?,
},
// A de-indexed draw's first index, or a private list's (`Tables::with_indices`).
PushHole::CaptureIndexAddress { stages, offset } => Hole {
stages: stages.into(),
offset,
address: tables
.capture
.and_then(|(_, indices)| indices)
.or(tables.indices)
.ok_or_else(|| internal("a capture index hole without capture indices"))?,
.indices
.ok_or_else(|| internal("an index hole without its indices"))?,
},
// A merged draw replay's header, which its vertex function finds its command in.
PushHole::MergedDrawAddress { stages, offset } => Hole {
@@ -2289,24 +2264,6 @@ pub(super) struct CommandUses {
}
impl CommandUses {
/// Add `other`'s uses, as one command's: a key either names stays named, and the keys both
/// reach through the resident set alone stay so (`render/capture.rs`, whose draws record
/// as one command).
pub(super) fn merge(&mut self, other: CommandUses) {
let named = |uses: &CommandUses| -> BTreeSet<ResourceKey> {
uses.uses
.iter()
.map(|used| used.key)
.filter(|key| !uses.resident.contains(key))
.collect()
};
let (own, theirs) = (named(self), named(&other));
self.resident.retain(|key| !theirs.contains(key));
let reached = other.resident.into_iter().filter(|key| !own.contains(key));
self.resident.extend(reached);
self.uses.extend(other.uses);
}
/// Add `used`, which names its key.
pub(super) fn push(&mut self, used: Use<ResourceKey>) {
self.resident.remove(&used.key);
+3 -14
View File
@@ -125,9 +125,8 @@ pub(super) fn stores(store: StoreAction) -> bool {
}
/// The tiles a render pass's draws reach, where Metal loads and stores its attachments, as far as
/// the host decides them: what a `DontCare` load clears (above), which tiles a rotated texture's
/// frame turns (`render/shadows.rs`), and which tiles the load pass of an extended-range or padded
/// attachment rewrites (`render/unused_bits_load.rs`). An execution of an indirect command buffer's
/// the host decides them: what a `DontCare` load clears (above) and which tiles a rotated
/// texture's frame turns (`render/shadows.rs`). An execution of an indirect command buffer's
/// render commands, or a tile dispatch, counts as a draw call that draws (unmeasured).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum PassReach {
@@ -142,7 +141,7 @@ pub(super) enum PassReach {
/// and a pass of more layers are unmeasured: none of them decides it.
Every,
/// The tiles the draws' primitives reach, which the host does not know: each use of it
/// takes every tile and announces it (until the reach is captured).
/// takes every tile and announces it.
Draws,
}
@@ -502,21 +501,11 @@ pub(super) struct DrawnTiles {
}
impl DrawnTiles {
/// A tile's width and height in pixels.
pub(super) fn tile(&self) -> [u32; 2] {
self.tile
}
/// Whether no tile is reached.
pub(super) fn is_empty(&self) -> bool {
self.words.iter().all(|&w| w == 0)
}
/// The reached tiles' count.
pub(super) fn count(&self) -> u64 {
self.words.iter().map(|w| u64::from(w.count_ones())).sum()
}
/// Whether tile `(tx, ty)` is reached: none past the grid.
pub(super) fn contains(&self, tx: u32, ty: u32) -> bool {
let t = (ty as usize) * (self.per_row as usize) + tx as usize;
@@ -11,7 +11,7 @@
//! - **And what fed its work** (`trails.rs`). A thread that made what the command buffer waited
//! for, and holds what it made it with past its signal, holds the device without holding the
//! command buffer: a pool piece between its making's settle and its give-back (a dispatch's or
//! a draw's pipeline, a capture's translation), the reaper with what such a piece gave back to a
//! a draw's pipeline), the reaper with what such a piece gave back to a
//! released state, the twin-decode thread between a decode's end and its job's drop. Each opens
//! a trail before its signal and closes it after its last let-go; the command buffer takes the
//! device's trail mark as it completes, and `wait_until_completed` and its timed form, once the
@@ -630,8 +630,6 @@ pub(super) struct State {
/// A direct mesh draw's object grid lay past what runs (`render/mesh_arguments.rs`): the
/// command buffer fails as for `ExecutionStatus`'s `MESH_GRID_PAST_LIMITS`.
mesh_grid_past: bool,
/// The captured passes' tile masks, which its completion counts (`render/capture.rs`).
pub(super) capture_tallies: Vec<CaptureTally>,
/// The index pool of the commands' index bounds and rewrite passes (`index_bounds.rs`,
/// `index_rewrite.rs`), once a draw needs it: its counter in the arena, starting at 0, and
/// its lease of its queue's block, which its indices lie in (`gpu_pools.rs`).
@@ -1821,7 +1819,6 @@ impl CommandBuffer {
descriptors: DescriptorArena::default(),
status_words: None,
mesh_grid_past: false,
capture_tallies: Vec::new(),
index_pool: None,
mesh_pool: None,
mesh_draws: 0,
@@ -4260,9 +4257,6 @@ impl CommandBufferShared {
/// waiters once the transition's [`Hold`] (and every other) is gone, and they wait for the
/// trails below the mark. Waits from inside these steps answer as [`own`] says.
fn complete(self: &Arc<Self>, result: Result<(), CommandBufferError>) {
// A capture replay found a primitive whose reach was not measured: its pass rewrote
// every tile, announced once the lock is let go (below).
let mut unmeasured_reach = false;
// A thread sleeps on `changed`, as the state's lock below reads.
let parked;
// Its command pool, where it settled, whose primary the device's spares begin ahead once
@@ -4385,12 +4379,7 @@ impl CommandBufferShared {
state.status = CommandBufferStatus::Error;
state.error = Some(CommandBufferError::CubicArgumentSampler);
}
unmeasured_reach = report.captured_reach_unmeasured;
state.report = Some(report);
let counts = &self.device.shared().counts;
for tally in &state.capture_tallies {
counts.capture_reach_tallied(tally.found(), tally.bound);
}
}
Err(error) => {
state.status = CommandBufferStatus::Error;
@@ -4410,7 +4399,6 @@ impl CommandBufferShared {
// failure turns to `Error`.
self.answer(&state);
state.status_words = None;
state.capture_tallies.clear();
// Its heap versions, uploads, pools and descriptor pools go once its completed
// handlers ran (below).
released_versions = state.heaps.clear();
@@ -4452,18 +4440,6 @@ impl CommandBufferShared {
// handler of its runs: a detach from one of them detaches (`detach.rs`).
drop(submitted_holds);
self.wake_parked(parked);
if unmeasured_reach {
self.device
.degrade(Degradation::UnreachedTilesRewritten, || {
(
"a render pass whose draws' tile reach capture replay found".to_owned(),
"a primitive crossed the near or far plane, or lay past what Metal's tile \
rule was measured over, so the pass rewrote every 32x32 tile of its \
render area where Metal's rewrites only the tiles its primitives reach"
.to_owned(),
)
});
}
let buffer = CommandBuffer(Arc::clone(self));
// Each handler leaves the queue under the lock and runs without it, in the order added
// (a handler may query the command buffer).
@@ -4569,37 +4545,6 @@ impl CommandBufferShared {
}
}
/// A captured pass's tile mask, copied where the host reads it once the command buffer completes
/// (`render/capture.rs`), and the tiles its draws' viewports and scissors reach: the counts
/// `WorkCounts::capture_reach_tiles_found` and its kin.
pub(super) struct CaptureTally {
/// The mask's copy: one bit a tile, tile `t` bit `t % 32` of word `t / 32`.
pub(super) mask: Upload,
/// The tiles of the pass's grid: the bits past them count nothing.
pub(super) grid: u64,
/// The tiles the draws' viewports and scissors reach.
pub(super) bound: u64,
}
impl CaptureTally {
/// The tiles the mask names, once the command buffer completed.
fn found(&self) -> u64 {
let bytes = self.mask.read_bytes();
let mut found = 0u64;
for (word, bits) in bytes.as_chunks::<4>().0.iter().enumerate() {
let first = word as u64 * 32;
let within = self.grid.saturating_sub(first).min(32);
let live = match within {
32 => u32::MAX,
n => (1u32 << n) - 1,
};
let bits = u32::from_le_bytes([bits[0], bits[1], bits[2], bits[3]]);
found += u64::from((bits & live).count_ones());
}
found
}
}
/// A command buffer's transition, run in its queue's context.
pub(crate) struct Transition {
/// The command buffer, held until the transition ran.
@@ -4619,14 +4564,9 @@ enum To {
impl Transition {
/// The transition of the command buffer `buffer` holds to `Completed` or `Error`, with
/// `result`: plain where it has no completed handler (none is added after the commit) and no
/// pass that captured its tiles' reach, the one notice it announces as it completes
/// (`render/capture.rs`).
/// `result`: plain where it has no completed handler (none is added after the commit).
fn finished(buffer: Hold<CommandBufferShared>, result: Result<(), CommandBufferError>) -> Self {
let plain = {
let state = lock(&buffer.state);
state.completed.is_empty() && state.capture_tallies.is_empty()
};
let plain = lock(&buffer.state).completed.is_empty();
Transition {
buffer,
to: To::Finished(result),
@@ -9,9 +9,8 @@ use std::fmt;
/// Why an ended encoder kept no log a rebind encodes it again from (`replay.rs`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Unlogged {
/// It logged no calls: the device had no buffer over host pages as it opened, it is of a
/// kind that logs none (a resource state encoder's), or its pass captured its draws' tile
/// reach (`render/capture.rs`).
/// It logged no calls: the device had no buffer over host pages as it opened, or it is of a
/// kind that logs none (a resource state encoder's).
NoCalls,
/// It left work for later that an encoding again does not record at once: a host step's (a
/// GPU-written indirect dispatch's), or a scrub's (`Segment::records_again`).
@@ -66,8 +65,8 @@ impl fmt::Display for Unlogged {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Unlogged::NoCalls => {
"it logged no calls (no buffer over host pages as it opened, a kind that logs \
none, or a pass that captured its draws' tile reach)"
"it logged no calls (no buffer over host pages as it opened, or a kind that \
logs none)"
}
Unlogged::Segments => "it left work for later an encoding again does not record",
Unlogged::Fails => "its command buffer fails it as it commits",
+33 -48
View File
@@ -315,10 +315,12 @@ degradations! {
/// 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`): the device biases
/// and converts the depth.
/// by Metal's constant in its own unit 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 biased depth can store another code than Metal's: the device biases by the \
constant c in its own unit, up to twice 2^-16, where Metal biases by c + 1 units of \
1/65535 (c - 1 below 0, one unit for a slope alone), and rounds the biased sum its \
own way";
/// 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`), or a pass clears one to a depth that a device rounding to nearest
@@ -1059,7 +1061,7 @@ degradations! {
/// access (`texture/attached_reads.rs`): a texture reached through a handle or an
/// argument buffer, a storage binding of a color attachment's texture, the depth or
/// stencil attachment's texture, a texture buffer or a buffer over its bytes, a texture
/// whose copy is not served, or an execution's or a capture's command. Announced where the
/// whose copy is not served, or an execution's command. Announced where the
/// draw records; the payload names its call.
AttachmentReadInPlace = "attachment-read-in-place", Precision,
"the access sees the attachment as the device holds it inside its render pass \
@@ -1219,32 +1221,33 @@ degradations! {
Metal's blit reads from outside the texels: from outside the planes below a width \
of 4, and those an earlier blit left in a row's padding or past a plane, which \
Metal keeps";
/// A draw in a render pass that loads a color attachment of an extended-range or padded
/// 10-bit format (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`, `R10Unorm_X6`,
/// `RG10Unorm_X12` and their sRGB twins, and `RGB10A2Unorm_sRGB`) and does not discard it
/// at the store, where the
/// pass's load pass (`render/unused_bits_load.rs`) does not take it (`render.rs`): a
/// multisampled attachment, a texture held as a shadow of another image or of a heap's
/// bytes, a sparse one, or one whose image the device does not copy both ways (a padded
/// format takes no multisample texture). Metal's pass, once it draws, writes each 32 x 32 tile a
/// draw reaches back with the bits its codes leave unused made canonical, the texels no
/// fragment writes and the channels a write mask leaves out too (on an Apple M4 and an
/// Apple M3 Max), where such an attachment keeps the bytes its draws do not write.
/// Announced at every draw, an indirect command buffer's executed commands' too, naming
/// every such attachment of the pass. Also a GPU blit into, out of or between textures of
/// which one is a `BGRA10_XR` or `BGRA10_XR_sRGB` texture Metal keeps losslessly
/// compressed (`compressed_blit.rs`): Metal's blit moves the texels through the
/// compression, which clears the same bits and clamps the same alpha, where the device's
/// copy keeps the bytes; once per device.
/// A draw in a render pass that loads a color attachment of an extended-range, padded
/// 10-bit or bfloat format (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`, `R10Unorm_X6`,
/// `RG10Unorm_X12` and their sRGB twins, `RGB10A2Unorm_sRGB`, `R16Bfloat`, `RG16Bfloat`
/// and `RGBA16Bfloat`) and does not discard it at the store (`render/tile_store.rs`).
/// Metal's pass, once it draws, writes each 32 x 32 tile a draw reaches back with the bits
/// its codes leave unused made canonical, a padded sRGB twin's codes through Metal's table
/// and a bfloat code through `half` (a NaN to `0x7fc0`), the texels no fragment writes and
/// the channels a write mask leaves out too (on an Apple M4 and an Apple M3 Max), where
/// the device's pass keeps the bytes its draws do not write, on every device. Announced at
/// every draw, an indirect command buffer's executed commands' too, naming every such
/// attachment of the pass. Also a GPU blit into, out of or between textures of which one
/// is a `BGRA10_XR` or `BGRA10_XR_sRGB` texture Metal keeps losslessly compressed
/// (`compressed_blit.rs`): Metal's blit moves the texels through the compression, which
/// clears the same bits and clamps the same alpha, where the device's copy keeps the
/// bytes; once per device.
ExtendedRangeBitsKept = "extended-range-bits-kept", Precision,
"the texels the pass's draws do not write keep their bytes; Metal's pass keeps their \
codes but rewrites the bits they leave unused in each tile a draw reaches \
(BGR10_XR's bits 30 and 31 to ones, BGRA10_XR's low six bits of each field to \
zeros, the two-plane color word's top two bits to zeros) and clamps BGRA10_XR's \
alpha code to [384, 894]: a texel whose bytes no Metal write left (uploaded bytes, \
or an alpha code past 894) keeps bytes Metal's pass would change, and a blit through \
a BGRA10_XR texture Metal compresses keeps the bytes Metal's blit rewrites so; every \
such texel reads the same value either way";
"the texels the pass's draws do not write keep their bytes; Metal's pass rewrites, in \
each tile a draw reaches, the bits their codes leave unused (BGR10_XR's bits 30 and \
31 to ones, BGRA10_XR's low six bits of each field, the two-plane color word's top \
two bits and a padded word's low six bits to zeros), clamps BGRA10_XR's alpha code \
to [384, 894], moves a padded sRGB twin's code through its table and a bfloat code \
through half (out of half's range to an infinity or zero, a NaN to 0x7fc0): a texel \
whose bytes no Metal write left (uploaded bytes, an alpha code past 894, a bfloat \
code off half's grid) keeps bytes Metal's pass would change, and a blit through a \
BGRA10_XR texture Metal compresses keeps the bytes Metal's blit rewrites so; an \
extended-range texel reads the same value either way, a bfloat code off half's grid \
reads its own value where Metal's reads the half it was moved to";
/// A draw in a render pass that loads a single-sampled color attachment of a signed
/// normalized format (`R8Snorm`, `RG8Snorm`, `RGBA8Snorm`, `R16Snorm`, `RG16Snorm`,
/// `RGBA16Snorm`) and does not discard it at the store (`render.rs`). Metal's pass, once
@@ -1427,7 +1430,7 @@ degradations! {
/// encoder the rebind could not encode again (a compute encoder its unit of command
/// predication reaches past: one whose unit laid a step before it opened, or one of its
/// own that the unit's later encoders read, or whose unit holds a loop or leaves work
/// out; a render pass a host step records, or whose end captured its draws' tile reach; work
/// out; a render pass a host step records; work
/// recorded on the GPU alone that no longer runs there; a call that answers otherwise than
/// at its encoding; `replay.rs`). Its reason names where the first such submission found
/// the use (the encoder, and its own commands or work it left for later) and why no rebind
@@ -1464,24 +1467,6 @@ degradations! {
that does not name it reads what an earlier such write left in the stand-in's \
sink, where Metal drops those writes and reads zero; a sampled read, and a size \
query, are Metal's";
/// A render pass that loads a color attachment of an extended-range, padded 10-bit or
/// bfloat format (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`, `R10Unorm_X6`,
/// `RG10Unorm_X12` and their sRGB twins, `RGB10A2Unorm_sRGB`, `R16Bfloat`, `RG16Bfloat`
/// and `RGBA16Bfloat`), stores it and draws, whose load pass
/// (`render/unused_bits_load.rs`) rewrites every 32 x 32 tile of its render area: Metal's
/// pass rewrites only the tiles a draw's primitives reach (on
/// an Apple M4 and an Apple M3 Max, alike), and every tile only where a color
/// attachment of the pass is cleared and stored (announced where none is, or where the
/// pass renders more than one layer). Announced at the pass's end, naming its
/// attachments the load pass took.
UnreachedTilesRewritten = "unreached-tiles-rewritten", Precision,
"in tiles no draw reaches the pass rewrites what Metal keeps: the unused bits made \
canonical (BGR10_XR's bits 30 and 31 ones, BGRA10_XR's low six bits of each field \
and the two-plane color word's top two bits zeros) and BGRA10_XR alpha codes \
clamped to [384, 894], so an out-of-range raw alpha reads back changed, a padded \
word's low six bits zeroed (an sRGB twin's code moved through Metal's table), a \
bfloat code moved through half (out of half's range to an infinity or zero, a NaN \
to 0x7fc0); the tiles a draw reaches are Metal's";
/// A draw in a render pass over a rasterization-rate map of no layers that was made after
/// the device released a map of one or more layers, or reset from one of layers
/// (`rate_mapped_pass.rs`). The draw
+1 -16
View File
@@ -68,7 +68,7 @@ use super::mipmap_scratch::MipmapScratch;
use super::owned_kernel::OwnedKernels;
use super::recycle::{self, BufferMaking, Recycler};
use super::released_programs::Keepers;
use super::render_state::{depth_bias_command, DepthBiasCommand, DepthRanges};
use super::render_state::DepthRanges;
use super::render_target::KeptRenderPasses;
use super::resource_ids::{ResourceIds, SamplerIdReads};
use super::sample_planes::PlanesObjects;
@@ -320,9 +320,6 @@ pub(super) struct DeviceShared {
/// The command that binds an index buffer range of a size, where the device enabled
/// `maintenance5` (`draw_source.rs`).
pub(super) sized_index_bind: Option<SizedIndexBind>,
/// The command that records a depth bias of a pinned unit, where the device enabled
/// `VK_EXT_depth_bias_control` (`render_state.rs`).
pub(super) depth_bias_command: Option<DepthBiasCommand>,
/// The mesh draw commands, where the device enabled `meshShader` (`render/mesh.rs`).
pub(super) mesh_draws: Option<MeshDraws>,
/// `vkCmdPushDescriptorSet`, from Vulkan 1.4 or `VK_KHR_push_descriptor`
@@ -1408,15 +1405,6 @@ impl Device {
}
});
// SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back.
let depth_bias_command = unsafe {
loader_word.restore();
depth_bias_command(&instance.raw, &raw, &enabled)
}
.map(|bias| {
// SAFETY: the device's own command of that name.
unsafe { crate::recorder::through(recording.as_ref(), Command::CmdSetDepthBias2, bias) }
});
// SAFETY: as above; the loader serves `vkGetDeviceProcAddr` once the word is put back.
let color_write_masks = unsafe {
loader_word.restore();
ColorWriteMasks::load(&instance.raw, &raw, &enabled)
@@ -1439,7 +1427,6 @@ impl Device {
let drawn = prime::PrimedDraws {
dynamic: extended_dynamic_state,
color_write_masks,
depth_bias: depth_bias_command,
sized_index_bind,
};
// Before the exit hook is registered for this device (below): the first call of each
@@ -1475,7 +1462,6 @@ impl Device {
extended_dynamic_state: false,
primitive_restart: false,
color_write_masks: false,
depth_bias: false,
sized_index_bind: false,
ycbcr_conversion: ycbcr_formats.primer().is_some(),
}),
@@ -1773,7 +1759,6 @@ impl Device {
shared_pointer_imports: OnceLock::new(),
extended_dynamic_state,
sized_index_bind,
depth_bias_command,
mesh_draws,
push_descriptor,
pushes_after_pipeline_binds,
@@ -82,7 +82,6 @@ use crate::gpu_time::Calibration;
use crate::loader_word::LoaderWord;
use crate::memory;
use crate::release::{self, Generated, Released};
use crate::render_state::DepthBiasCommand;
use crate::sharing::Sharing;
use crate::tracker::Barrier;
use ash::vk;
@@ -174,10 +173,6 @@ pub(crate) const PRIMITIVE_RESTART_CALLS: [Call; 1] = [Call::CmdSetPrimitiveRest
/// primes: a snapshot draw's masks (`dynamic_state.rs`, `render/snapshot.rs`).
pub(crate) const COLOR_WRITE_MASK_CALLS: [Call; 1] = [Call::CmdSetColorWriteMask];
/// The table's entry points a device without `VK_EXT_depth_bias_control` never calls, nor
/// primes: a depth bias in a unit of its own (`render_state.rs`).
pub(crate) const DEPTH_BIAS_CALLS: [Call; 1] = [Call::CmdSetDepthBias2];
/// The table's entry points a device without `maintenance5` never calls, nor primes: an index
/// buffer bound with its size (`draw_source.rs`).
pub(crate) const SIZED_INDEX_BIND_CALLS: [Call; 1] = [Call::CmdBindIndexBuffer2];
@@ -379,7 +374,6 @@ pub(crate) struct Has {
pub(crate) extended_dynamic_state: bool,
pub(crate) primitive_restart: bool,
pub(crate) color_write_masks: bool,
pub(crate) depth_bias: bool,
pub(crate) sized_index_bind: bool,
pub(crate) ycbcr_conversion: bool,
}
@@ -391,7 +385,6 @@ pub(crate) struct Has {
pub(crate) struct PrimedDraws {
pub(crate) dynamic: Option<ExtendedDynamicState>,
pub(crate) color_write_masks: Option<ColorWriteMasks>,
pub(crate) depth_bias: Option<DepthBiasCommand>,
pub(crate) sized_index_bind: Option<SizedIndexBind>,
}
@@ -404,7 +397,6 @@ impl PrimedDraws {
.dynamic
.is_some_and(|dynamic| dynamic.primitive_restart_enable.is_some()),
color_write_masks: self.color_write_masks.is_some(),
depth_bias: self.depth_bias.is_some(),
sized_index_bind: self.sized_index_bind.is_some(),
..has
}
@@ -491,7 +483,7 @@ pub(super) unsafe fn prime(
/// has no push command, those of [`CALIBRATION_CALLS`] where it calibrates no timestamps, those
/// of [`NAMING_CALLS`] where its instance reports no messages, and those of
/// [`EXTENDED_DYNAMIC_STATE_CALLS`], [`PRIMITIVE_RESTART_CALLS`],
/// [`COLOR_WRITE_MASK_CALLS`], [`DEPTH_BIAS_CALLS`] and [`SIZED_INDEX_BIND_CALLS`] where it has
/// [`COLOR_WRITE_MASK_CALLS`] and [`SIZED_INDEX_BIND_CALLS`] where it has
/// not their commands, and those of [`YCBCR_CONVERSION_CALLS`] where it converts no YCbCr format,
/// that `calls` (one bit each) does not hold.
pub(crate) fn missing(calls: u128, has: Has) -> Vec<Call> {
@@ -513,7 +505,6 @@ pub(crate) fn missing(calls: u128, has: Has) -> Vec<Call> {
&& (has.extended_dynamic_state || !EXTENDED_DYNAMIC_STATE_CALLS.contains(&call))
&& (has.primitive_restart || !PRIMITIVE_RESTART_CALLS.contains(&call))
&& (has.color_write_masks || !COLOR_WRITE_MASK_CALLS.contains(&call))
&& (has.depth_bias || !DEPTH_BIAS_CALLS.contains(&call))
&& (has.sized_index_bind || !SIZED_INDEX_BIND_CALLS.contains(&call))
&& (has.ycbcr_conversion || !YCBCR_CONVERSION_CALLS.contains(&call))
})
@@ -1535,10 +1526,6 @@ impl Primer<'_> {
masks(draws, 0, all.len() as u32, all.as_ptr());
self.made(Call::CmdSetColorWriteMask);
}
if let Some(bias) = drawn.depth_bias {
bias(draws, &vk::DepthBiasInfoEXT::default());
self.made(Call::CmdSetDepthBias2);
}
// A clear of the attachment inside the pass, as a render encoder's clear of a stand-in
// records it.
let clear = [vk::ClearAttachment {
+1 -1
View File
@@ -2040,7 +2040,7 @@ pub enum CommandBufferError {
/// mapping update reads its buffer as it runs; a call refused at its encoding is refused
/// again, and the calls after it run); this fails only an encoder that cannot be encoded
/// again: one of a command buffer that used command predication; a render pass recorded later
/// (an indirect command buffer's execution) or whose end captured its draws' tile reach. Each
/// (an indirect command buffer's execution). Each
/// of Metal's submissions holding such an encoder ran nothing (the command buffer's split),
/// every other ran, the event signals fired and the handlers ran. What the command buffer's
/// encoders made resident (`use_resource`, `use_heap`) and what its commands reach unnamed
@@ -482,11 +482,9 @@ calls! {
CmdSetPrimitiveRestartEnable => c"vkCmdSetPrimitiveRestartEnable",
// A render encoder's extension commands, each on a device that has it
// ([`COLOR_WRITE_MASK_CALLS`](crate::device::prime::COLOR_WRITE_MASK_CALLS),
// [`DEPTH_BIAS_CALLS`](crate::device::prime::DEPTH_BIAS_CALLS),
// [`SIZED_INDEX_BIND_CALLS`](crate::device::prime::SIZED_INDEX_BIND_CALLS)), through the
// entry point the device gave (`vkCmdBindIndexBuffer2KHR` where it enables that form).
CmdSetColorWriteMask => c"vkCmdSetColorWriteMaskEXT",
CmdSetDepthBias2 => c"vkCmdSetDepthBias2EXT",
CmdBindIndexBuffer2 => c"vkCmdBindIndexBuffer2",
// The objects a render encoder's lowering makes as it draws (its pass's render pass and
// framebuffer, stand-in and scratch images, `creation.rs`), on the device's lowering thread
@@ -37,10 +37,9 @@ use crate::shader_cache::driver::Making;
use ash::vk;
use metal2vulkan::bind::{
MipmapFilterKernel, RewritePhase, RewriteProgram, ShadowMergeRead, ShadowTexelView,
TessellationScanKernel, TexelWords, YCbCrCodes, YCbCrConversion,
TessellationScanKernel, YCbCrCodes, YCbCrConversion,
};
use metal2vulkan::metal::format::ExtendedRange;
use metal2vulkan::metal::PixelFormat;
use std::collections::HashMap;
/// A crate-owned module the runtime dispatches.
@@ -163,22 +162,9 @@ pub(super) enum OwnedModule {
/// `bind::ycbcr_write_module`: a 4:4:4 YCbCr texture's written texels encoded into its
/// surface's two planes (`ycbcr.rs`), its write shadow bound as a storage image.
YCbCrWrite,
/// `bind::unused_bits_module` of one format held as one kind of words: an extended-range,
/// padded 10-bit or bfloat texture's words in the tiles a mask names rewritten as Metal's tile
/// store leaves them, before a pass that loads it and draws (`render/unused_bits_load.rs`).
UnusedBits(PixelFormat, TexelWords),
/// `bind::tiled_texels_module`: a heap texture's elements moved between its image's tight
/// copy and Metal's tiles in the heap's bytes (`texture/heap_tiled.rs`).
TiledTexels,
/// `bind::capture_assembly_module`: a pass's capture records assembled into its primitives
/// (`render/capture.rs`).
CaptureAssembly,
/// `bind::tile_reach_module`: a pass's primitives binned into the tiles they reach. Needs
/// `shaderInt64`: a device without it fails to build it with `Unsupported`.
TileReach,
/// `bind::capture_settle_module`: the mask made every tile where a primitive's reach was not
/// measured, reported in the status words.
CaptureSettle,
/// `bind::extended_shadow_module` of one form: an extended-range attachment's `half` shadow
/// set from its codes before the instance whose draws first hold it
/// (`render/extended_shadow.rs`). Two storage images: the codes, then the shadow.
@@ -454,27 +440,6 @@ impl OwnedModule {
.map_err(Error::Compile)?;
Ok((module.spirv.to_vec(), 3, 0))
}
OwnedModule::UnusedBits(format, words) => {
let device = device.compile_device();
let module = metal2vulkan::bind::unused_bits_module(device, format, words)
.map_err(Error::Compile)?;
Ok((module.spirv.to_vec(), 3, 0))
}
OwnedModule::CaptureAssembly => {
let module = metal2vulkan::bind::capture_assembly_module(device.compile_device())
.map_err(Error::Compile)?;
Ok((module.spirv.to_vec(), 3, 0))
}
OwnedModule::TileReach => {
let module = metal2vulkan::bind::tile_reach_module(device.compile_device())
.map_err(Error::Compile)?;
Ok((module.spirv.to_vec(), 3, 0))
}
OwnedModule::CaptureSettle => {
let module = metal2vulkan::bind::capture_settle_module(device.compile_device())
.map_err(Error::Compile)?;
Ok((module.spirv.to_vec(), 3, 0))
}
OwnedModule::ExtendedShadowLoad(form) => {
let device = device.compile_device();
let module = metal2vulkan::bind::extended_shadow_module(device, form)
@@ -585,11 +550,7 @@ pub(super) struct OwnedKernels {
two_plane_texels: Option<OwnedKernel>,
plane_bytes_copy: Option<OwnedKernel>,
ycbcr_write: Option<OwnedKernel>,
unused_bits: HashMap<(PixelFormat, TexelWords), OwnedKernel>,
tiled_texels: Option<OwnedKernel>,
capture_assembly: Option<OwnedKernel>,
tile_reach: Option<OwnedKernel>,
capture_settle: Option<OwnedKernel>,
extended_shadow_loads: HashMap<ExtendedRange, OwnedKernel>,
predication_step: Option<OwnedKernel>,
twin_decodes: HashMap<TwinDecode, OwnedKernel>,
@@ -628,9 +589,6 @@ impl OwnedKernels {
self.plane_bytes_copy,
self.ycbcr_write,
self.tiled_texels,
self.capture_assembly,
self.tile_reach,
self.capture_settle,
self.predication_step,
]
.into_iter()
@@ -644,7 +602,6 @@ impl OwnedKernels {
.chain(self.index_rewrite_runs.values().copied())
.chain(self.ycbcr_converts.values().copied())
.chain(self.ycbcr_samples.values().copied())
.chain(self.unused_bits.values().copied())
.chain(self.extended_shadow_loads.values().copied())
.chain(self.twin_decodes.values().copied())
.chain(self.tessellation_scans.values().copied())
@@ -695,9 +652,6 @@ impl OwnedKernels {
OwnedModule::YCbCrSample(sampler, codes) => {
self.ycbcr_samples.get(&(sampler, codes)).copied()
}
OwnedModule::UnusedBits(format, words) => {
self.unused_bits.get(&(format, words)).copied()
}
OwnedModule::ExtendedShadowLoad(form) => self.extended_shadow_loads.get(&form).copied(),
OwnedModule::TwinDecode(decode) => self.twin_decodes.get(&decode).copied(),
OwnedModule::TessellationScan(kernel) => self.tessellation_scans.get(&kernel).copied(),
@@ -735,9 +689,6 @@ impl OwnedKernels {
OwnedModule::YCbCrSample(sampler, codes) => {
self.ycbcr_samples.insert((sampler, codes), kernel);
}
OwnedModule::UnusedBits(format, words) => {
self.unused_bits.insert((format, words), kernel);
}
OwnedModule::ExtendedShadowLoad(form) => {
self.extended_shadow_loads.insert(form, kernel);
}
@@ -788,7 +739,6 @@ impl OwnedKernels {
| OwnedModule::IndexRewriteRun(_)
| OwnedModule::YCbCrConvert(..)
| OwnedModule::YCbCrSample(..)
| OwnedModule::UnusedBits(..)
| OwnedModule::ExtendedShadowLoad(_)
| OwnedModule::TwinDecode(_)
| OwnedModule::TessellationScan(_) => return None,
@@ -813,9 +763,6 @@ impl OwnedKernels {
OwnedModule::PlaneBytesCopy => &mut self.plane_bytes_copy,
OwnedModule::YCbCrWrite => &mut self.ycbcr_write,
OwnedModule::TiledTexels => &mut self.tiled_texels,
OwnedModule::CaptureAssembly => &mut self.capture_assembly,
OwnedModule::TileReach => &mut self.tile_reach,
OwnedModule::CaptureSettle => &mut self.capture_settle,
OwnedModule::PredicationStep => &mut self.predication_step,
})
}
@@ -1001,7 +1001,6 @@ impl VariantObjects {
0.0,
0.0,
0.0,
None,
self.device.compile_device().profile(),
)
.map_err(|error| internal(&format!("a depth bias of no factors refused: {error:?}")))?;
@@ -2,8 +2,7 @@
//! holder of the device.
//!
//! A draw's making handed to the device's pool (`pool.rs`) needs its variant, its pass and its
//! making's ticket, and a capture form's translation its device and its descriptor: each holds
//! the device. Were the piece to hold them, the program could let go of the command buffer, the
//! making's ticket: each holds the device. Were the piece to hold them, the program could let go of the command buffer, the
//! state and the device while the piece waits or runs, and the piece's release would then tear
//! the device down on the pool's thread, perhaps while the process exits: after destructors the
//! exit hook could not precede freed what that teardown calls into, RADV and ANV ended such
@@ -72,9 +72,9 @@ use metal2vulkan::cache::{Hash256, PipelineKey, SpecializationKey, VariantKey};
use metal2vulkan::library::{CompiledFunction, FunctionCompileKey};
use metal2vulkan::metal::{BindingAccess, PixelFormat, PrimitiveTopologyClass, RenderStages};
use metal2vulkan::pipeline::{
CaptureForm, ColorAttachmentDescriptor, CommandWrites, MeshPipelineDescriptor,
PipelineInterface, RenderPipeline, RenderPipelineDescriptor, RuntimeFact, SpecKey,
StageEntries, StageModule, StageSource, TessellationDescriptor,
ColorAttachmentDescriptor, CommandWrites, MeshPipelineDescriptor, PipelineInterface,
RenderPipeline, RenderPipelineDescriptor, RuntimeFact, SpecKey, StageEntries, StageModule,
StageSource, TessellationDescriptor,
};
use metal2vulkan::reflection::{LinkedUseAnswers, RenderPipelineReflection};
use std::any::Any;
@@ -235,16 +235,8 @@ pub(crate) struct Program {
/// alone (`drawn`), two descriptors the key tells apart, so it holds a key of each: a
/// compile is keyed by the descriptor it compiles, a question by the descriptor it asks of.
compiled_key: OnceLock<PipelineKey>,
/// The key of the descriptor its capture forms compile from
/// ([`GraphicsState::capture_key`]), built when the first form translates: one descriptor,
/// `descriptor` without its fragment stage or attachment formats ([`capture_descriptor`]),
/// for every form of every variant, so every form after the first builds none.
capture_key: OnceLock<PipelineKey>,
/// Its part of the pipeline creation log, while the log is on (`creation_log.rs`).
log: Option<StateLog>,
/// Its variants' capture forms (`VariantKey::captured_positions`), as capture replay asked for
/// them (`GraphicsState::capture_variant`): at most [`CAPTURES`].
captures: Mutex<Lru<VariantKey, Capture>>,
/// What its last [`SETTLED`] settles of other shapes settled, in which buffer forms, the
/// latest used first (`GraphicsState::settle_shape`).
settled: Mutex<VecDeque<(BufferForms, Settled)>>,
@@ -253,8 +245,8 @@ pub(crate) struct Program {
last_pipelines: Mutex<VecDeque<LastPipeline>>,
/// Its routing into the pass colors it was last set in a pass of (`GraphicsState::routed`).
routed: Mutex<Option<(PassColors, Result<Arc<Routing>, u32>)>>,
/// What its pool pieces hold (`piece_holds.rs`): its draws' makings and its capture forms'
/// translations, kept here so a pool thread never holds the device's last reference.
/// What its pool pieces hold (`piece_holds.rs`): its draws' makings, kept here so a pool
/// thread never holds the device's last reference.
pieces: Arc<PieceHolds<PieceHeld>>,
/// Its buffer slots whose bind offset class tells the device's view base alignment apart
/// (`argument_table::AtBindViews`), of its base's interface.
@@ -284,8 +276,6 @@ pub(crate) enum PieceHeld {
_variant: Arc<RenderVariant>,
_pass: Arc<RenderPassObject>,
},
/// A capture form's translation: the state's device, which its sources read.
Capture(Device),
}
/// A pass's color formats, by index: what a state's routing is found for
@@ -322,24 +312,6 @@ const SETTLED: usize = 4;
/// shape, whose plan's specialization another draw of the pass does not share.
const LAST_PIPELINES: usize = 4;
/// The most capture forms of its variants a state keeps (`GraphicsState::capture_variant`): a
/// settled key's and the key its plan asks for, of each form a pass draws.
const CAPTURES: usize = 8;
/// A capture form of a state's variant: translated on the device's pool, its objects made on the
/// program's thread once it is, or refused.
#[derive(Clone)]
enum Capture {
/// Being translated on the pool: its outcome once the translation ends (a refusal as
/// `None`).
Translating(Arc<OnceLock<Option<Arc<RenderPipeline>>>>),
/// Its objects made.
Made(Arc<RenderVariant>),
/// Refused: by the compile (a device without the capture's stores, among others) or by its
/// objects. Never asked again while kept.
Refused,
}
impl std::fmt::Debug for RenderPipelineState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.0 {
@@ -1790,8 +1762,6 @@ impl GraphicsState {
texture_accesses: TextureAccessMemo::new(),
descriptor_key: key.map_or_else(OnceLock::new, OnceLock::from),
compiled_key: OnceLock::new(),
capture_key: OnceLock::new(),
captures: Mutex::new(Lru::counted(CAPTURES)),
settled: Mutex::new(VecDeque::with_capacity(SETTLED)),
last_pipelines: Mutex::new(VecDeque::with_capacity(LAST_PIPELINES)),
routed: Mutex::new(None),
@@ -1886,19 +1856,6 @@ impl GraphicsState {
})
}
/// The key of `capture`, the descriptor the state's capture forms compile from
/// ([`capture_descriptor`] of its own), built once and held ([`Program::capture_key`]).
///
/// Its own descriptor's key names another descriptor: a capture form compiles without the
/// fragment stage and the attachment formats, every field of which the key reads. `capture`
/// is fixed for the state's life -- the form a replay asks for is a fact of the variant's
/// key, not of the descriptor -- so the forms of every variant are keyed by this one key.
pub(crate) fn capture_key(&self, capture: &RenderPipelineDescriptor) -> &PipelineKey {
self.0
.capture_key
.get_or_init(|| render_descriptor_key(&self.0.device, capture))
}
/// The state a patch draw an indirect command scales runs on (`None` for a state that does
/// not tessellate, whose draw refuses patches): its twin, of this state's descriptor with
/// `tessellationFactorScaleEnabled` set and without `supportIndirectCommandBuffers`, made
@@ -2236,117 +2193,6 @@ impl GraphicsState {
(plan.variant == base.key && !self.0.stand_in).then_some((base, plan))
}
/// The capture form of the state's variant of `settled`, under `form`, and its plan for
/// `shape`, for capture replay (`render/capture.rs`), where it is ready: `None` while it is
/// not. It is the vertex stage alone, `settled` with `VariantKey::captured_positions`, of the
/// descriptor without its fragment function, color, depth or stencil formats (a pipeline that
/// rasterizes into a pass without attachments): every vertex function's position is
/// invariant, so the positions it writes are the ones the state's own draws rasterize. The
/// first ask hands its translation to the device's pool (bounded, `pool.rs`); the first ask
/// after the translation ended makes its objects here, on the program's thread, in the
/// program's order (the HITCH rule's, `kept.rs`). A form the compile or its objects refuse
/// stays `None` while kept, asked no more; so does one whose plan asks for another variant.
pub(crate) fn capture_variant(
&self,
settled: &VariantKey,
form: CaptureForm,
shape: &BindShape,
) -> Option<(Arc<RenderVariant>, Arc<BindingPlan>)> {
let mut key = settled.clone();
key.captured_positions = Some(form);
// The settled key holds facts of the fragment stage the capture form compiles without,
// so the capture's own plan may ask for its variant under another key, the facts of the
// vertex stage alone: that variant's plan asks for itself (as `settle`'s second
// variant's does).
for _ in 0..2 {
let variant = self.capture_form(&key)?;
let plan = variant.plan(&self.0.device, shape).ok()?;
if plan.variant == variant.key {
return Some((variant, plan));
}
key = plan.variant.clone();
}
None
}
/// The capture form of `key` ([`capture_variant`](Self::capture_variant)'s), where it is
/// ready.
fn capture_form(&self, key: &VariantKey) -> Option<Arc<RenderVariant>> {
let found = lock(&self.0.captures).get(key).cloned();
let entry = match found {
Some(Capture::Made(variant)) => return Some(variant),
Some(Capture::Refused) => return None,
Some(Capture::Translating(outcome)) => match outcome.get() {
None => return None,
Some(None) => Capture::Refused,
Some(Some(pipeline)) => {
let found = CompiledVariant::found(Remembered::Compiled(Arc::clone(pipeline)));
match RenderVariant::of(&self.0.device, key.clone(), found) {
Ok(variant) => Capture::Made(variant),
Err(_) => Capture::Refused,
}
}
},
None => {
let StateDescriptor::Vertex(descriptor) = &self.0.descriptor else {
lock(&self.0.captures).insert(key.clone(), Capture::Refused, 1);
return None;
};
let outcome = Arc::new(OnceLock::new());
let translating = Capture::Translating(Arc::clone(&outcome));
lock(&self.0.captures).insert(key.clone(), translating, 1);
let descriptor = capture_descriptor(descriptor);
// Built here, on the program's thread, where its one descriptor is: every later
// form's translation takes this key rather than building the same digest again.
let descriptor_key = *self.capture_key(&descriptor);
let key = key.clone();
let keeping = self
.0
.pieces
.keep(PieceHeld::Capture(self.0.device.clone()));
self.0.device.shared().pipeline_pool.run(Box::new(move || {
// Where the state let go meanwhile, the piece stops: no one asks again.
let Some((lease, held)) = keeping.start() else {
return;
};
let device = match held {
PieceHeld::Capture(device) => device,
other => return lease.give_back(other, None),
};
let translated = {
let sources = Sources::later(&device);
let entries = device.shared().shader_cache.memo.stage_entries();
RenderVariant::compiled(
&sources,
&descriptor,
&key,
entries,
&descriptor_key,
)
.ok()
.map(|found| match found.remembered {
Remembered::Live(variant) => Arc::clone(&variant.pipeline),
Remembered::Compiled(pipeline) => pipeline,
})
};
// Set once, by its one translation: a later draw may take it, and its command
// buffer complete, while this piece still holds the device, until it gave it
// back. A trail spans that (`trails.rs`).
let trail = device.shared().trails.open();
let _set = outcome.set(translated);
lease.give_back(PieceHeld::Capture(device), Some(trail));
}));
return None;
}
};
let made = match &entry {
Capture::Made(variant) => Some(Arc::clone(variant)),
_ => None,
};
lock(&self.0.captures).insert(key.clone(), entry, 1);
made
}
/// The variant of `key`: the large-buffer form's compiled at creation, or another compiled
/// when first needed.
fn variant(&self, key: &VariantKey) -> Result<Arc<RenderVariant>, Error> {
@@ -2382,22 +2228,6 @@ impl GraphicsState {
}
}
/// The descriptor a state's capture forms compile from: `descriptor` without its fragment
/// function, color, depth or stencil formats, and without alpha-to-coverage or alpha-to-one -- a
/// pipeline of the vertex stage alone that rasterizes into a pass without attachments
/// (`GraphicsState::capture_variant`). It is the same descriptor for every form of every variant
/// of the state, so [`GraphicsState::capture_key`] keys all of them by its one key.
fn capture_descriptor(descriptor: &RenderPipelineDescriptor) -> RenderPipelineDescriptor {
let mut descriptor = descriptor.clone();
descriptor.fragment = None;
descriptor.color_attachments = Default::default();
descriptor.depth_format = None;
descriptor.stencil_format = None;
descriptor.alpha_to_coverage = false;
descriptor.alpha_to_one = false;
descriptor
}
/// The base variant of each color group of the state of `descriptor` whose creation compiled
/// `base` (under stand-ins where `stand_in`), with whether it was compiled under stand-ins
/// (`GraphicsState::color_group`): the first group's is `base`, each later one's compiled as the
@@ -2527,8 +2357,7 @@ fn stage_name(source: &StageSource) -> String {
///
/// The functions are what lets a creation name its stages' modules without hashing their words
/// again ([`stage_words_digest`]). Empty for a pipeline the memo, a binary archive or the disk
/// cache gave whole, and for a mesh pipeline or a capture form, none of which link from compiled
/// functions here.
/// cache gave whole, and for a mesh pipeline, none of which link from compiled functions here.
struct CompiledVariant {
remembered: Remembered<RenderPipeline, RenderVariant>,
functions: Vec<CompiledFunction>,
@@ -2572,7 +2401,7 @@ impl RenderVariant {
/// built or holds: a creation compiles its base, its large-buffer form and each of its color
/// groups' bases, all of one descriptor, so it builds that key once and every one of them
/// looks its pipeline up under it; a state holds the key of each descriptor its later
/// compiles are of (`GraphicsState::compiled_key`, `capture_key`), so a draw builds none.
/// compiles are of (`GraphicsState::compiled_key`), so a draw builds none.
fn compiled(
sources: &Sources<'_>,
descriptor: &RenderPipelineDescriptor,
@@ -273,10 +273,6 @@ enum Logged {
writes: Span,
},
SetColorWriteMask(u32, Span),
SetDepthBias2 {
factors: [f32; 3],
representation: Option<(vk::DepthBiasRepresentationEXT, vk::Bool32)>,
},
BindIndexBuffer2(vk::Buffer, vk::DeviceSize, vk::DeviceSize, vk::IndexType),
DrawMeshTasks(u32, u32, u32),
DrawMeshTasksIndirect(vk::Buffer, vk::DeviceSize, u32, u32),
@@ -1163,33 +1159,6 @@ impl Log {
self.op(Logged::SetColorWriteMask(first, masks));
}
pub(super) unsafe fn cmd_set_depth_bias2(&mut self, info: *const vk::DepthBiasInfoEXT<'_>) {
// SAFETY: the caller's.
let info = unsafe { &*info };
let representation = match info.p_next.is_null() {
true => None,
false => {
// SAFETY: the caller's: a chained structure starts with its type.
let chained =
unsafe { &*info.p_next.cast::<vk::DepthBiasRepresentationInfoEXT<'_>>() };
if chained.s_type != vk::StructureType::DEPTH_BIAS_REPRESENTATION_INFO_EXT
|| !chained.p_next.is_null()
{
unchained("depth bias");
}
Some((chained.depth_bias_representation, chained.depth_bias_exact))
}
};
self.op(Logged::SetDepthBias2 {
factors: [
info.depth_bias_constant_factor,
info.depth_bias_clamp,
info.depth_bias_slope_factor,
],
representation,
});
}
pub(super) unsafe fn cmd_bind_index_buffer2(
&mut self,
buffer: vk::Buffer,
@@ -1772,24 +1741,6 @@ impl Log {
masks.len,
self.masks.get_ptr(masks)
),
Logged::SetDepthBias2 {
factors,
representation,
} => {
let mut chained = representation.map(|(representation, exact)| {
vk::DepthBiasRepresentationInfoEXT::default()
.depth_bias_representation(representation)
.depth_bias_exact(exact != vk::FALSE)
});
let mut info = vk::DepthBiasInfoEXT::default()
.depth_bias_constant_factor(factors[0])
.depth_bias_clamp(factors[1])
.depth_bias_slope_factor(factors[2]);
if let Some(chained) = &mut chained {
info = info.push_next(chained);
}
call!(CmdSetDepthBias2, vk::PFN_vkCmdSetDepthBias2EXT, &info)
}
Logged::BindIndexBuffer2(buffer, offset, size, index_type) => call!(
CmdBindIndexBuffer2,
vk::PFN_vkCmdBindIndexBuffer2KHR,
@@ -393,8 +393,6 @@ commands! {
);
CmdSetColorWriteMask cmd_set_color_write_mask c"vkCmdSetColorWriteMaskEXT"
(first: u32, count: u32, masks: *const vk::ColorComponentFlags);
CmdSetDepthBias2 cmd_set_depth_bias2 c"vkCmdSetDepthBias2EXT"
(info: *const vk::DepthBiasInfoEXT<'_>);
CmdBindIndexBuffer2 cmd_bind_index_buffer2 c"vkCmdBindIndexBuffer2"
(
buffer: vk::Buffer,
+78 -213
View File
@@ -387,7 +387,6 @@ use tile_dispatch::{ScratchEdges, TileDispatch};
mod arguments;
mod bound;
mod call_checks;
mod capture;
mod color_groups;
mod deferral;
mod draw_shape;
@@ -414,8 +413,8 @@ mod table_facts;
mod tessellation_scan;
mod tile_dispatch;
mod tile_memory;
mod tile_store;
mod untouched;
mod unused_bits_load;
mod vertex_reach;
mod vertex_strides;
@@ -748,10 +747,15 @@ enum NineFailure {
/// `PushField::VerticesPerPrimitive`): such a draw runs the variant that draws its indices as
/// vertices from 0 (`BindState::primitive_id_indices`). `None` for every other draw.
fn primitive_id_indices(pipeline: &DrawingState, draw: &DrawCall) -> Option<IndexType> {
match draw {
DrawCall::Indexed { .. } if writes_primitive_ids(pipeline) => {
capture::form(draw)?.index_type()
}
let DrawCall::Indexed { index_type, .. } = *draw else {
return None;
};
if !writes_primitive_ids(pipeline) {
return None;
}
match index_type {
t if t == metal2vulkan::vk::IndexType::UINT16 => Some(IndexType::UInt16),
t if t == metal2vulkan::vk::IndexType::UINT32 => Some(IndexType::UInt32),
_ => None,
}
}
@@ -1436,9 +1440,6 @@ pub(crate) struct RenderLowering {
/// colors out of its subpass (`render/reroute.rs`): a draw that would record elsewhere, or
/// whose variant the interlocked storage form refuses, fails the reroute.
rerouting: bool,
/// The pass's draws kept for capture replay, or the capture draw being recorded
/// (`render/capture.rs`).
keeping: capture::Keeping,
/// The buffer forms its draws' variants take (`BufferForms`): the large-buffer form where it
/// records an execution's commands at its host step, or settles their variants at commit
/// (`render/executions.rs`), so no buffer a command binds asks for another variant; the
@@ -1514,15 +1515,11 @@ pub(crate) struct RenderLowering {
/// form): its descriptor sets view the attachment's image, which then stays the pass's
/// (`kept_bytes.rs`).
inputs_read: BTreeSet<u32>,
/// The pass has a draw call, whether or not it draws anything, or an execution of render
/// commands: Metal's pass rewrites the unused bits of an extended-range or padded attachment
/// it loads in the tiles its draws reach (`render/unused_bits_load.rs`).
rewrites_unused_bits: bool,
/// The kept-attachment notices of the layout as it stands (`degrade_kept_attachments`),
/// decided at the first draw or execution under it; `None` until then, and again each time
/// the encoder changes its layout: installs another, sets a color's store action or resolve,
/// loads a memoryless color, or reroutes the pass.
kept_attachments: Option<unused_bits_load::KeptAttachments>,
kept_attachments: Option<tile_store::KeptAttachments>,
/// The pass's extended-range color attachments an earlier draw or execution of render
/// commands may have written, or whose clear Metal's tile memory holds as values its codes
/// do not read back (`cleared_off_codes`), by index (`degrade_extended_range_blends`).
@@ -1932,7 +1929,6 @@ impl RenderLowering {
log,
grouped,
} = opening;
let keeping = capture::Keeping::of(&layout);
let rerecord = extended.keeps_draws();
// The bind state the device's last ended render encoder left (`live_bind.rs`).
let live = core.device().shared().live_binds.take();
@@ -2011,7 +2007,6 @@ impl RenderLowering {
tile_dispatch_calls: 0,
replaying: false,
rerouting: false,
keeping,
forms: BufferForms::Bound,
replayed: None,
drawn_before: Vec::new(),
@@ -2031,7 +2026,6 @@ impl RenderLowering {
drawn: clear_reach::DrawnArea::default(),
coverage: linear_attachment::Coverage::default(),
inputs_read: BTreeSet::new(),
rewrites_unused_bits: false,
kept_attachments: None,
extended_written,
extended,
@@ -3943,10 +3937,8 @@ impl RenderLowering {
}
/// [`end_encoding`](Self::end_encoding)'s pass, all but its core's end and its later color
/// groups' passes: the core, what the encoder made resident, its log, whether a rebind may
/// encode it again from it (not where its end captured its draws' tile reach, whose tally
/// lies in the command buffer), and what its later color groups draw
/// (`render/color_groups.rs`).
/// groups' passes: the core, what the encoder made resident, its log, and what its later
/// color groups draw (`render/color_groups.rs`).
fn end_pass(mut self: Box<Self>) -> Result<color_groups::Ended, Error> {
const CALL: &str = "end_encoding";
// Over a mutable rasterization-rate map: Metal's GPU hangs at a pass of no draw call until
@@ -3979,10 +3971,6 @@ impl RenderLowering {
// The last instance recorded inline after a split, its commands still kept: recorded
// now, before the pass's plan of the instances after it (`render/inline_splits.rs`).
self.flush_inline()?;
// The tiles the pass's draws reach, from the positions their own vertex functions
// compute, where capture replay finds them: recorded before the pass's other steps
// (`render/capture.rs`).
let captured = self.capture_reach();
// Whether a command of the pass may read an attachment's bytes it did not name.
let unnamed_reads =
self.barrier_inside || self.reaches_unnamed || !self.executions.is_empty();
@@ -4010,7 +3998,6 @@ impl RenderLowering {
drawn,
coverage,
inputs_read,
rewrites_unused_bits,
residency,
extended,
reload_at,
@@ -4129,7 +4116,6 @@ impl RenderLowering {
core,
residency,
log,
keeps_log: captured.is_none(),
later: None,
});
}
@@ -4360,15 +4346,6 @@ impl RenderLowering {
)
});
}
// An extended-range or padded 10-bit attachment the pass loads: the bits its codes leave
// unused made canonical, in the tiles the pass's draws reach, before the pass's other
// steps, as Metal's pass that draws rewrites them (`render/unused_bits_load.rs`).
// None where they reach no tile. The tiles capture replay binned, where it did.
let rewritten = unused_bits_load::TileReach::of(reach, tiles.as_ref(), captured.as_ref())
.filter(|_| rewrites_unused_bits);
if let Some(rewritten) = rewritten {
unused_bits_load::record(&mut core, &layout, rewritten)?;
}
// A color attachment the last instance leaves out does not resolve there: a pass that
// resolves one runs one more instance, of no draws, after its sample planes are merged
// back, which resolves the pass (`sample_planes.rs`).
@@ -5048,11 +5025,6 @@ impl RenderLowering {
if let Some(first) = &first_texel_copies {
core.shadow_copies(first);
}
// A rotated texture's frame the pass loads: its unused bits rewritten over the frame's
// tiles once its shadow's copy in filled it (`render/unused_bits_load.rs`).
if let Some(rewritten) = rewritten {
unused_bits_load::record_frames(&mut core, &layout, rewritten)?;
}
if let Some(write) = nan_depth {
write.record(&mut core);
core.retain(write);
@@ -5605,7 +5577,6 @@ impl RenderLowering {
core,
residency,
log,
keeps_log: captured.is_none(),
later,
})
}
@@ -6386,7 +6357,7 @@ impl RenderLowering {
}
/// Give up the draws recording of `instance`, one the pass replaced or gave up before running
/// it ([`install`](Self::install), `render/reroute.rs`, `render/capture.rs`): never submitted,
/// it ([`install`](Self::install), `render/reroute.rs`): never submitted,
/// a deferred one is never replayed, and one of the pool's ends so the pool goes back to the
/// device's spares unreset (`CommandBuffer::give_up_raw`). One with pieces (the secondaries
/// of draws whose pipelines were being made) is left to the pool's reset; one whose secondary
@@ -6403,7 +6374,7 @@ impl RenderLowering {
// SAFETY: the secondary command buffer is recording, only this encoder records it, and
// nothing executes it; no query is active in it: a query begins or continues only in an
// instance none of whose draws record again (`rerecord` `None`, which `recorded` marks
// too), never one a pass replaces, a reroute leaves, or a capture's.
// too), never one a pass replaces or a reroute leaves.
let ended = unsafe { self.core.command_buffer().give_up_raw(instance.draws) };
if ended.is_ok() {
self.core.device().shared().counts.unrun_instance_ended();
@@ -6714,17 +6685,17 @@ impl RenderLowering {
}
/// Announce the kept-attachment notices at a draw, or an execution of render commands, of
/// each kind whose list of the pass's colors is not empty
/// (`unused_bits_load::KeptAttachments`): decided once for each layout the encoder records
/// under, as its calls change it ([`kept_attachments`](Self::kept_attachments)).
/// each kind whose list of the pass's colors is not empty (`tile_store::KeptAttachments`):
/// decided once for each layout the encoder records under, as its calls change it
/// ([`kept_attachments`](Self::kept_attachments)).
fn degrade_kept_attachments(&mut self) {
let device = self.core.device();
let layout = &self.layout;
let kept = (self.kept_attachments)
.get_or_insert_with(|| unused_bits_load::KeptAttachments::of(layout, device));
.get_or_insert_with(|| tile_store::KeptAttachments::of(layout, device));
debug_assert_eq!(
*kept,
unused_bits_load::KeptAttachments::of(layout, device),
tile_store::KeptAttachments::of(layout, device),
"the kept colors decided for a layout the encoder changed since"
);
Self::degrade_unused_bits(device, &kept.unused_bits);
@@ -6733,11 +6704,10 @@ impl RenderLowering {
}
/// Announce `extended-range-bits-kept` at a draw in a pass that loads a color attachment of
/// an extended-range or padded 10-bit format (and does not discard it at the store), whatever
/// the draw's state, naming every such attachment the load pass does not take, `kept`
/// (`render/unused_bits_load.rs`): Metal's pass, once it draws, rewrites the bits their codes
/// leave unused in each tile a draw reaches, the texels the draws do not write too, where such
/// an attachment keeps those.
/// an extended-range, padded 10-bit or bfloat format (and does not discard it at the store),
/// whatever the draw's state, naming every such attachment, `kept`
/// (`tile_store::bits_kept`): Metal's pass, once it draws, rewrites every texel of each tile a
/// draw reaches, the texels the draws do not write too, where the device's pass keeps those.
fn degrade_unused_bits(device: &Device, kept: &[String]) {
if kept.is_empty() {
return;
@@ -6745,9 +6715,11 @@ impl RenderLowering {
device.degrade(Degradation::ExtendedRangeBitsKept, || {
(
format!("a draw in a render pass that loads {}", kept.join(" and ")),
"the texels the pass's draws do not write keep the bits their codes leave \
unused, and a BGRA10_XR alpha code past [384, 894], which Metal's pass \
rewrites in each tile a draw reaches"
"the texels the pass's draws do not write keep their bytes: the bits their \
codes leave unused, a BGRA10_XR alpha code past [384, 894], a padded word's \
low six bits, a padded sRGB twin's code off Metal's table and a bfloat code \
off half's grid (a NaN other than 0x7fc0), each of which Metal's pass rewrites \
in each tile a draw reaches"
.to_owned(),
)
});
@@ -6756,7 +6728,7 @@ impl RenderLowering {
/// Announce `snorm-minimum-kept` at a draw in a pass that loads a single-sampled color
/// attachment of a signed normalized format (and does not discard it at the store), whatever
/// the draw's state, naming every such attachment, `kept`
/// (`unused_bits_load::snorm_minimum_kept`): Metal's pass, once it draws, writes each tile a
/// (`tile_store::snorm_minimum_kept`): Metal's pass, once it draws, writes each tile a
/// draw reaches back through the channels' values, so a minimum code (-128, or -32768) the
/// draws do not write is stored as the code above it, where such an attachment keeps it. Not
/// on a driver whose pass stores it so too (`DriverFact::TileStoreIsMetals`: MoltenVK's pass
@@ -6778,7 +6750,7 @@ impl RenderLowering {
/// Announce `shared-exponent-kept` at a draw in a pass that loads a single-sampled
/// `RGB9E5Float` color attachment (and does not discard it at the store), whatever the draw's
/// state, naming every such attachment, `kept` (`unused_bits_load::shared_exponent_kept`):
/// state, naming every such attachment, `kept` (`tile_store::shared_exponent_kept`):
/// Metal's pass, once it draws, writes each tile a draw reaches back through its texels'
/// values, so a word the draws do not write whose largest mantissa is below 256 under an
/// exponent above 0 is stored normalized, where such an attachment keeps it. Not on a driver
@@ -7099,7 +7071,6 @@ impl RenderLowering {
// execution (`executions.rs`).
if !self.replaying {
self.degrade_kept_attachments();
self.rewrites_unused_bits = true;
self.degrade_extended_range_blends();
self.degrade_ycbcr_blends();
}
@@ -7292,28 +7263,16 @@ impl RenderLowering {
// from a copy taken before the pass (`render/pass_start_reads.rs`).
// The object and mesh tables' too, and an execution's commands', whose copies record
// into the recording that replays them, before the pass (`render/executions.rs`).
// A capture draw (`render/capture.rs`) runs before the pass: it reads the bytes as they
// were then, in place, and announces nothing its first recording did not.
let capture = self.capture_addresses();
// The device's sampler states, less those at IDs no set-1 sampler array of the variant
// holds (`heap_sets::fit_samplers`): taken where the draw needs them
// (`sampler::ArgumentSamplers`), and at once for a capture draw, whose capture form is
// another variant than the one settled.
let mut argument_samplers = match capture {
Some(_) => ArgumentSamplers::taken(self.core.device()),
None => ArgumentSamplers::untaken(),
};
let pass_start = match capture {
Some(_) => PassStartTables::default(),
None => self.pass_start.tables(
&mut self.core,
[&self.vertex, &self.object, &self.mesh],
&pipeline.base().interface,
)?,
};
if capture.is_none() {
self.degrade_kept_colors(&pipeline, &settings.routing);
}
// (`sampler::ArgumentSamplers`).
let mut argument_samplers = ArgumentSamplers::untaken();
let pass_start = self.pass_start.tables(
&mut self.core,
[&self.vertex, &self.object, &self.mesh],
&pipeline.base().interface,
)?;
self.degrade_kept_colors(&pipeline, &settings.routing);
// The pass colors the draw renders through views of other formats, in an instance of
// its own (`next_instance`). Refused (`NotImplemented(IndirectRenderCommands)`) for an
// execution's command, whose runs' framebuffers are the pass's.
@@ -7329,7 +7288,7 @@ impl RenderLowering {
// A draw that reads its pass's texture after a barrier inside its instance reads it
// through a snapshot where it can (`render/snapshot.rs`): asked of the plan, kept where
// the plan reads so, else `None` and the split.
let mut snapshot = self.snapshot_wanted(&pipeline, &reformats, capture.is_some());
let mut snapshot = self.snapshot_wanted(&pipeline, &reformats);
// Its runtime samplers' address modes as the textures they sample map them: what it
// settles under, and binds with.
let sampler_maps = self.sampler_maps(&pipeline, &pass_start)?;
@@ -7367,28 +7326,12 @@ impl RenderLowering {
}
}
self.give_up_extended_shadows(&pipeline, &live.state);
// The draw's primitive type: an indexed capture draw's layout says whether its strip
// restarts, and a vertex function that writes the primitive ID divides by its vertices per
// primitive (`PushField::VerticesPerPrimitive`).
// The draw's primitive type: a vertex function that writes the primitive ID divides by its
// vertices per primitive (`PushField::VerticesPerPrimitive`), and an indexed strip of it
// does not run de-indexed.
if let Assembly::Primitives(primitive) = assembly {
live.state.primitive_type = Some(primitive);
}
// A capture draw runs its variant's capture form, where its objects are made: else it
// records nothing, and the capture neither.
let (variant, plan) = match capture {
None => (variant, plan),
Some(_) => {
let found = capture::form(&draw)
.and_then(|form| pipeline.capture_variant(variant.key(), form, &shape));
match found {
Some(found) => found,
None => {
self.capture_missed();
return Ok(());
}
}
}
};
let device = self.core.device();
let stages = &variant.pipeline().stages;
if device.argument_pixel_samplers_noted(stages).is_some() {
@@ -7546,9 +7489,6 @@ impl RenderLowering {
.flatten()
.map(|buffer| buffer.identity().key),
) {
if self.capture_missed() {
return Ok(());
}
self.skipped_draw();
return Ok(());
}
@@ -7912,17 +7852,14 @@ impl RenderLowering {
// A draw that samples a color attachment's texture reads the texture's copy, taken before
// its instance; after a memory barrier inside the current instance, which orders one
// pixel alone, it records into a new instance, whose copy holds what the draws before the
// barrier wrote (`texture/attached_reads.rs`). An execution's command and a capture draw
// read the attachment in place: neither takes a copy.
// barrier wrote (`texture/attached_reads.rs`). An execution's command reads the
// attachment in place: it takes no copy.
// A draw that reads through snapshots reads no attachment's texture otherwise
// (`RenderCommandEncoder::snapshot_holds`), and stays in its instance: one recorded inline
// has begun its render pass instance with no color in the feedback loop layout, so the
// draw records into a new one (`render/snapshot.rs`). So does a draw that binds a texture
// the current instance holds in that layout as a storage image.
let attached = capture.is_none()
&& !self.replaying
&& snapshot.is_none()
&& self.samples_attachment(&plan);
let attached = !self.replaying && snapshot.is_none() && self.samples_attachment(&plan);
let after_barrier = attached && (self.current.barriers || self.barrier);
let snapshot_split = snapshot.as_ref().is_some_and(|w| self.snapshot_apart(w));
let storage_colors = self.storage_colors(&plan);
@@ -7935,19 +7872,15 @@ impl RenderLowering {
let unheld_writes = (self.current.inline || deciding)
&& self.writes_memoryless(&pipeline, routing, zeroes_colors);
let first_write = self.current.inline && unheld_writes;
// A capture draw records into the capture's instance, the current one.
let (next, stood) = match capture {
Some(_) => (Next::Current, None),
None => self.next_instance(
(&fetched, Some(&pipeline)),
(stencil_use.is_some(), tests_use.is_some()),
views,
(ordered || after_barrier || apart || first_write) && !self.replaying,
hidden,
&routing.locations,
&reformats,
)?,
};
let (next, stood) = self.next_instance(
(&fetched, Some(&pipeline)),
(stencil_use.is_some(), tests_use.is_some()),
views,
(ordered || after_barrier || apart || first_write) && !self.replaying,
hidden,
&routing.locations,
&reformats,
)?;
if first_write && matches!(next, Next::New { split: true, .. }) {
device.shared().counts.inline_memoryless_write_split();
}
@@ -8175,15 +8108,12 @@ impl RenderLowering {
.ok_or_else(|| internal("a heap's draw without its argument samplers"))?;
tables = tables.with_heap(states, heap);
}
if let Some((records, indices)) = capture {
tables = tables.with_capture(records, indices);
}
if let Some(header) = self.replayed.as_ref().and_then(|r| r.merged_header()) {
tables = tables.with_merged_header(header);
}
// A list in the private list form is read at its address, which the device gives the
// list's memory where it has device addresses, as the form needs.
if capture.is_none() && variant.key().private_list {
if variant.key().private_list {
let address = match (&listed, &rewrite) {
(Some(list), _) => list.address(),
(_, Some(pass)) => pass.address(),
@@ -8194,7 +8124,7 @@ impl RenderLowering {
tables = tables.with_indices(address);
}
// A de-indexed draw's vertex function reads its indices in place, at their address.
if capture.is_none() && variant.key().primitive_id_indices.is_some() {
if variant.key().primitive_id_indices.is_some() {
let address = buffers
.index
.as_ref()
@@ -8303,7 +8233,7 @@ impl RenderLowering {
}
// In a pass of several color groups, what the draw reads of what another group writes
// (`render/color_groups.rs`): checked at its first recording.
if capture.is_none() && !self.rerouting {
if !self.rerouting {
let roots = !commands.root_tables.is_empty();
self.check_group_reads(uses, roots, &plan)?;
}
@@ -8326,9 +8256,6 @@ impl RenderLowering {
.map(|used| used.key)
.filter(|key| !uses.resident().contains(key));
if self.core.skips(named) {
if self.capture_missed() {
return Ok(());
}
self.skipped_draw();
return Ok(());
}
@@ -8354,11 +8281,6 @@ impl RenderLowering {
if self.replaying && !self.gathered().covers(&draw_shadows) {
return Err(Error::NotImplemented(RuntimeGap::IndirectRenderCommands));
}
// A shadowed texture's copies go around its instance, which a capture draw runs before.
if capture.is_some() && !draw_shadows.is_empty() {
self.capture_missed();
return Ok(());
}
// Over the last draw's, in their storage (`LiveBind::vertex_buffers`).
live.vertex_buffers.clear();
for bind in &plan.vertex_buffers {
@@ -8473,8 +8395,8 @@ impl RenderLowering {
}),
};
// A draw that reaches no fragment runs its vertex function alone, through empty scissors,
// and so do unsized points, and a capture draw, which writes its records alone.
if failing == Some(FailingDraw::Untouched) || unsized_points || capture.is_some() {
// and so do unsized points.
if failing == Some(FailingDraw::Untouched) || unsized_points {
for state in draw_states.iter_mut() {
for scissor in state.scissors.iter_mut() {
*scissor = vk::Rect2D::default();
@@ -8617,12 +8539,6 @@ impl RenderLowering {
if reused_state && reused_pipeline {
device.shared().counts.draw_shape_reused();
}
// A capture draw's pipeline is made on the pool: until it is, the capture records
// nothing.
if capture.is_some() && matches!(draw_pipeline, DrawPipeline::Making(_)) {
self.capture_missed();
return Ok(());
}
// A pipeline made at the state's creation announces its notices at the first draw that
// finds it made; a draw that began a making announced them as it began it.
if let DrawPipeline::Made(made) = &draw_pipeline {
@@ -8922,15 +8838,12 @@ impl RenderLowering {
.fold(vk::PipelineStageFlags2::empty(), |all, used| {
all | used.read.stages | used.write.stages
});
// A capture draw's uses are the capture's command's, before the pass (`capture_uses`).
if capture.is_none() {
let reaching = (&**uses, uses.resident());
self.core
.note_reaching(stages, reaching, Some(&mut live.noted))?;
self.unordered.add(uses);
self.pass_start.announce(&device, uses, mesh_before);
self.pass_start.add(uses);
}
let reaching = (&**uses, uses.resident());
self.core
.note_reaching(stages, reaching, Some(&mut live.noted))?;
self.unordered.add(uses);
self.pass_start.announce(&device, uses, mesh_before);
self.pass_start.add(uses);
let heap_set = match heap {
Some(_) => Some(heap_sets::bind(
&device,
@@ -9139,36 +9052,6 @@ impl RenderLowering {
&& tessellation_steps.is_none()
&& draw_shadows.is_empty()
&& snapshot.is_none();
// Whether the draw can run again as a capture draw before the pass, where its pass keeps
// its draws for capture replay (`render/capture.rs`): its primitives' positions, viewport
// and scissor are the ones it rasterizes with, and its reads read what they read.
let capturable = !self.replaying
&& self.layout.samples == 1
&& self.layout.sample_positions.is_empty()
&& self.rate_map.is_none()
&& !self.counts_visibility()
&& !tessellated
&& !meshes
&& !graphics.vertex_writes_memory
&& !graphics.writes_viewport_index
&& !self.amplification.offsets_viewports()
&& views == ViewSetup::default()
&& pushes.len() == 1
&& buffers.indirect.is_none()
&& buffers.patch_indices.is_none()
&& buffers.control_point_indices.is_none()
&& !before_instance
&& bounds.is_none()
&& rewrite.is_none()
&& listed.is_none()
&& mesh_steps.is_none()
&& tessellation_steps.is_none()
&& draw_shadows.is_empty()
&& snapshot.is_none()
&& capture::assembles(assembly)
&& self.state.reach_state().is_some();
// A draw that rasterizes nothing reaches no tile: it changes nothing the capture finds.
let rasterizes = !graphics.rasterizer_discard;
// A draw whose pipeline is being made records between its instance's own draws, which
// an instance recorded inline cannot run: it records into a new instance after it
// (`render/inline_first.rs`).
@@ -9207,23 +9090,14 @@ impl RenderLowering {
let inline = self.inline_begin(
&next,
stood.as_deref(),
(
!empty && !culled,
made_ahead,
capture.is_some(),
unheld_writes,
),
(!empty && !culled, made_ahead, unheld_writes),
feedback,
)?;
// And a later instance of such a pass after a split, where it can, the instance before's
// copies planned (`render/inline_splits.rs`).
let split_inline = match inline {
Some(_) => None,
None => self.inline_split(
&next,
stood.as_deref(),
(!empty && !culled, made_ahead, capture.is_some()),
),
None => self.inline_split(&next, stood.as_deref(), (!empty && !culled, made_ahead)),
};
// A new instance that records inline takes no secondary; any other begins its own.
if inline.is_none() && split_inline.is_none() {
@@ -9615,9 +9489,6 @@ impl RenderLowering {
}
self.current.recorded = true;
self.keep_draw(again, (call, assembly, draw), index);
if rasterizes {
self.keep_capture(capturable, (call, assembly, draw), index);
}
if pushes.len() > 1 {
let count = pushes.len();
device.degrade(Degradation::AmplificationDraws, || {
@@ -9652,8 +9523,7 @@ impl RenderLowering {
}
// The draw binds the variant: the kinds its making announces at every occurrence, but
// where the encoder records a draw again (`render/reroute.rs`), which announced them.
// Nor where it records a capture draw.
if let (Some(tested), false) = (&bound_each, self.rerouting || capture.is_some()) {
if let (Some(tested), false) = (&bound_each, self.rerouting) {
let formats = |slot| tested.iter().find(|(s, _)| *s == slot)?.1;
let compiled = variant.pipeline();
objects.announce_bound(
@@ -9663,17 +9533,15 @@ impl RenderLowering {
}
// A pipeline being made: its creation times once made, and the pass holds it
// (`render/pending.rs`).
// Built only where the device keeps records. A capture draw's runs for the pass's steps.
if capture.is_none() {
self.core.executed(|| {
let executed = ExecutedPipeline::Render(Arc::clone(variant.shared_pipeline()));
let execution = match later {
None => Execution::new(executed, shape, created),
Some(creation) => Execution::made_later(executed, shape, creation),
};
execution.with_index_padding(padding)
});
}
// Built only where the device keeps records.
self.core.executed(|| {
let executed = ExecutedPipeline::Render(Arc::clone(variant.shared_pipeline()));
let execution = match later {
None => Execution::new(executed, shape, created),
Some(creation) => Execution::made_later(executed, shape, creation),
};
execution.with_index_padding(padding)
});
let made = match draw_pipeline {
DrawPipeline::Made(made) => Some(made),
DrawPipeline::Making(_) => None,
@@ -9714,9 +9582,6 @@ impl RenderLowering {
if heap.is_some() && !function_tables.is_empty() {
self.core.retain(function_tables);
}
if capture.is_some() {
self.capture_uses(uses.clone());
}
Ok(())
}
@@ -1,660 +0,0 @@
//! Capture replay: the tiles a pass's draws reach, from the positions its own vertex functions
//! compute, before the pass.
//!
//! An Apple GPU loads and stores only the tiles a pass's primitives reach (`bind::tile_reach`),
//! which decides what the pass's extended-range load rewrites (`render/unused_bits_load.rs`).
//! The host decides that reach where the draws reach nothing or every tile, and bounds it by
//! their viewports and scissors (`clear_reach.rs`); elsewhere the runtime announces
//! `unreached-tiles-rewritten`. Capture replay finds the tiles themselves:
//!
//! - **Kept.** In a pass that consumes its reach (a color attachment the load pass takes, of one
//! sample, Metal's default 32 by 32 tiles, one layer, and no rotated texture's frame among
//! them: `unused_bits_load::consumes_capture`), each draw is kept with the encoder's
//! state at it (`reroute::Rerecord`) while every draw of the pass can run again before it: a
//! direct draw of a triangle list or strip, indexed or not, of any instance count, of one
//! amplification and no views, through a pipeline without tessellation or mesh stages whose
//! vertex function writes no memory and chooses no viewport, under solid fill, outside a
//! rasterization-rate map, a visibility query and custom sample positions, its indices read in
//! place; at most [`MAX_DRAWS`] draws of at most [`MAX_RECORDS`] vertices. Any other draw, a
//! tile dispatch or an execution of render commands ends the keeping for the pass.
//! - **Recorded again.** As the pass ends, before its steps, each kept draw records again with
//! its state, through the capture form of its variant (`GraphicsState::capture_variant`: the
//! vertex stage alone, writing each vertex's clip position to a record), into a pass of no
//! attachments under empty scissors, so no fragment runs. Every vertex function's position is
//! invariant, so the records hold the positions the pass's own draws rasterize. The capture form
//! is translated on the device's pool and its objects and pipeline made at a later pass (the
//! HITCH rule: nothing waits on the program's thread); until each of the pass's draws has both,
//! the pass stays on the host's reach and announces as before.
//! - **Binned.** Before the pass, the capture draws run, then `bind::capture_assembly_module`
//! assembles their records into primitives as Metal's input assembly does (a strip's restarts
//! and parity too), `bind::tile_reach_module` bins them by the measured rule into a tile mask,
//! and `bind::capture_settle_module` makes it every tile where a primitive crossed the near or
//! far plane or lay past what was measured, which it reports through the command buffer's
//! status words: the command buffer announces `unreached-tiles-rewritten` once it completes
//! (`StatusReport::captured_reach_unmeasured`). The load pass rewrites the tiles the mask
//! names. Exact otherwise: the rule is Metal's, measured, and its arithmetic integer.
//! - **Counted.** The mask is also copied where the host reads it once the command buffer
//! completes, which counts its tiles against those the draws' viewports and scissors reach
//! (`WorkCounts::capture_reach_tiles_found` and `capture_reach_tiles_bound`), and the pass as
//! one whose primitives reach every tile of that bound (`capture_reach_bound_passes`: a
//! full-screen draw's, the capture changing nothing rewritten) or fewer
//! (`capture_reach_narrower_passes`).
use super::bound::Bound;
use super::reroute::Rerecord;
use super::shadows::InstanceShadows;
use super::{Assembly, Instance, InterlockedStorage, RenderLowering};
use crate::attachmentless;
use crate::binding::CommandUses;
use crate::clear_reach::{DrawnArea, DrawnTiles, PassReach};
use crate::command_buffer::CaptureTally;
use crate::draw_source::DrawSource;
use crate::owned_kernel::{OwnedKernel, OwnedModule, OwnedSet, OwnedSets};
use crate::render_pass::PassLayout;
use crate::render_target::{self, Feedback};
use crate::tracker::Barrier;
use crate::tracker::{GeometryWrites, IndirectReads};
use crate::values::ResourceOptions;
use crate::versioned::Versioned;
use ash::vk;
use metal2vulkan::bind::{
CaptureAssemblyModule, CaptureSettleModule, DrawCall, ExecutionStatus, TileReachModule,
ViewSetup,
};
use metal2vulkan::metal::{CullMode, IndexType, PrimitiveType};
use metal2vulkan::pipeline::CaptureForm;
use std::sync::Arc;
/// The most draws a pass keeps for capture replay: past them its reach is the host's.
pub(super) const MAX_DRAWS: usize = 256;
/// The most capture records a pass's kept draws write (their vertices or indices, each instance
/// counted): 8 MiB of records, and their primitives' 16 MiB.
pub(super) const MAX_RECORDS: u64 = 1 << 18;
/// What a pass keeps for capture replay (the module docs).
pub(super) enum Keeping {
/// The draws kept so far, and the records they write.
Draws(Vec<Rerecord>, u64),
/// None: the pass does not consume its reach, or one of its draws cannot run again before
/// it.
Stopped,
/// The kept draws record again as capture draws, the pass ending: the one recording now.
Recording(Capturing),
}
impl Keeping {
/// What a pass of `layout` keeps from its start.
pub(super) fn of(layout: &PassLayout) -> Keeping {
match consumes(layout) {
true => Keeping::Draws(Vec::new(), 0),
false => Keeping::Stopped,
}
}
}
/// A capture draw recording (`RenderCommandEncoder::draw_resident` in capture mode).
pub(super) struct Capturing {
/// The device address of the draw's first record.
pub(super) records: u64,
/// The device address of the draw's first index, where it is indexed.
pub(super) indices: Option<u64>,
/// What the capture draws use, as the one command they record in.
pub(super) uses: CommandUses,
/// A capture draw recorded nothing: its capture form's objects or pipeline were not made
/// yet, or it could not record.
pub(super) missed: bool,
}
/// Whether a pass of `layout` consumes its draws' tile reach where capture replay can give it:
/// the load pass takes one of its color attachments and no rotated frame
/// (`unused_bits_load::consumes_capture`), at one sample and one layer, in Metal's default 32 by
/// 32 tiles, which the reach kernel bins (`bind::tile_reach`).
fn consumes(layout: &PassLayout) -> bool {
layout.samples == 1
&& layout.layers == 1
&& layout.tile.tile == Some([32, 32])
&& super::unused_bits_load::consumes_capture(layout, false)
}
/// Whether capture replay assembles draws of `assembly`.
pub(super) fn assembles(assembly: Assembly) -> bool {
matches!(
assembly,
Assembly::Primitives(PrimitiveType::Triangle | PrimitiveType::TriangleStrip)
)
}
/// The capture form of a direct draw `draw`: of its vertices, or of its indices of their type.
pub(super) fn form(draw: &DrawCall) -> Option<CaptureForm> {
match *draw {
DrawCall::Primitives { .. } => Some(CaptureForm::Vertices),
DrawCall::Indexed { index_type, .. } => match index_type {
t if t == metal2vulkan::vk::IndexType::UINT16 => {
Some(CaptureForm::Indexed(IndexType::UInt16))
}
t if t == metal2vulkan::vk::IndexType::UINT32 => {
Some(CaptureForm::Indexed(IndexType::UInt32))
}
_ => None,
},
_ => None,
}
}
/// The vertices or indices of each instance of a direct draw `draw`, and its instances.
fn counts(draw: &DrawCall) -> Option<(u64, u64)> {
match *draw {
DrawCall::Primitives {
vertex_count,
instance_count,
..
} => Some((u64::from(vertex_count), u64::from(instance_count))),
DrawCall::Indexed {
index_count,
instance_count,
..
} => Some((u64::from(index_count), u64::from(instance_count))),
_ => None,
}
}
/// The reach the pass's capture draws give (`RenderCommandEncoder::capture_reach`): the tile
/// mask, recorded before the pass's other steps, in the scratch the command buffer holds.
#[derive(Debug)]
pub(super) struct CapturedReach {
/// The mask's `VkBuffer`, its offset there, and its bytes: one bit a tile, as
/// `bind::TileReachModule` numbers them.
pub(super) mask: (vk::Buffer, u64, u64),
}
/// One kept draw's place among the pass's capture records and tile reach states.
struct Placed {
/// Its first record: instance 0's vertex 0.
first: u64,
/// Its records an instance, and its instances.
count: u64,
instances: u64,
topology: PrimitiveType,
/// It restarts at flagged records: an indexed strip.
restarts: bool,
/// Its cull mode is front or back.
culls: bool,
}
impl RenderLowering {
/// Keep the draw just recorded (`call` of `assembly` and `draw`, its indices from `index`)
/// for capture replay where the pass keeps its draws and `capturable` (the module docs);
/// otherwise the pass keeps none from here on. A draw recorded again (a reroute's, or a
/// capture draw) was kept at its first recording.
pub(super) fn keep_capture(
&mut self,
capturable: bool,
recorded: (&'static str, Assembly, DrawCall),
index: Option<&DrawSource<'_>>,
) {
if self.rerouting {
return;
}
let Keeping::Draws(draws, records) = &self.keeping else {
return;
};
let added = counts(&recorded.2).and_then(|(count, instances)| count.checked_mul(instances));
let total = added.and_then(|added| added.checked_add(*records));
let room = draws.len() < MAX_DRAWS && total.is_some_and(|total| total <= MAX_RECORDS);
let kept = match capturable && room {
true => self.kept_draw(recorded, index),
false => None,
};
match (kept, total, &mut self.keeping) {
(Some(kept), Some(total), Keeping::Draws(draws, records)) => {
draws.push(kept);
*records = total;
}
_ => self.keeping = Keeping::Stopped,
}
}
/// The capture draw recording now: its record and index addresses, where the encoder
/// records one (`draw_resident`).
pub(super) fn capture_addresses(&self) -> Option<(u64, Option<u64>)> {
match &self.keeping {
Keeping::Recording(capturing) => Some((capturing.records, capturing.indices)),
_ => None,
}
}
/// Note that the capture draw recording now records nothing (its capture form's objects or
/// pipeline not made yet): whether one is recording.
pub(super) fn capture_missed(&mut self) -> bool {
match &mut self.keeping {
Keeping::Recording(capturing) => {
capturing.missed = true;
true
}
_ => false,
}
}
/// Note `uses`, the capture draw's recording now, among the capture draws'.
pub(super) fn capture_uses(&mut self, uses: CommandUses) {
if let Keeping::Recording(capturing) = &mut self.keeping {
capturing.uses.merge(uses);
}
}
/// As the pass ends, before its steps: record its kept draws again as capture draws and,
/// before the pass, the steps that bin their primitives into a tile mask (the module docs),
/// where the pass's draws reach some tiles and a load pass rewrites them. `None` where it
/// does not, where a kept draw's capture form or pipeline is not made yet, or where the
/// device cannot: the pass's reach is then the host's, announced as before.
pub(super) fn capture_reach(&mut self) -> Option<CapturedReach> {
let reach = PassReach::of(&self.layout, self.called, self.drew);
let drawn = self.drawn.tiles(&self.layout);
let reaches = drawn.as_ref().is_none_or(|tiles| !tiles.is_empty());
let consumed = super::unused_bits_load::consumes_capture(&self.layout, true);
if !self.rewrites_unused_bits || reach != PassReach::Draws || !reaches || !consumed {
return None;
}
let Keeping::Draws(kept, records) = &self.keeping else {
return None;
};
if kept.is_empty() {
return None;
}
let records = *records;
let mut placed = Vec::with_capacity(kept.len());
let mut states = Vec::with_capacity(kept.len() * TileReachModule::STATE_WORDS as usize * 4);
let mut first = 0u64;
for draw in kept {
let (count, instances) = counts(&draw.draw())?;
let Assembly::Primitives(topology) = draw.assembly() else {
return None;
};
let state = draw.state();
states.extend(state.reach_state()?);
placed.push(Placed {
first,
count,
instances,
topology,
restarts: matches!(draw.draw(), DrawCall::Indexed { .. })
&& topology == PrimitiveType::TriangleStrip,
culls: state.cull_mode() != CullMode::None,
});
first += count * instances;
}
if first != records {
return None;
}
// The entries, one an instance of each draw of some primitives, and the primitives'.
let mut entries = Vec::new();
let mut total = 0u32;
let mut count = 0u32;
for (state, draw) in placed.iter().enumerate() {
let records = u32::try_from(draw.count).ok()?;
let primitives = CaptureAssemblyModule::primitives(draw.topology, records);
if primitives == 0 {
continue;
}
for n in 0..draw.instances {
let at = u32::try_from(draw.first + n * draw.count).ok()?;
entries.extend(CaptureAssemblyModule::draw(
total,
at,
records,
draw.topology,
draw.restarts,
draw.culls,
u32::try_from(state).ok()?,
));
total = total.checked_add(primitives)?;
count += 1;
}
}
if total == 0 {
return None;
}
let steps = self.capture_steps(records, total)?;
let recorded = self.record_captures(&steps)?;
let mut draws = CaptureAssemblyModule::header(count, total).to_vec();
draws.extend(entries);
let area = self.layout.extent;
let mut pass = TileReachModule::header(area, 1, 1, total).to_vec();
pass.extend(states);
// The tiles the host's reach names, which the load pass would rewrite without the
// capture: counted against the mask's once the command buffer completes.
let grid = u64::from(area[0].div_ceil(32)) * u64::from(area[1].div_ceil(32));
let bound = drawn.as_ref().map_or(grid, DrawnTiles::count);
self.record_capture_steps(steps, recorded, (&draws, &pass), (grid, bound))
}
/// The scratch and kernels of a pass's capture of `records` records and `total`
/// primitives: `None` where the device makes no kernel (the tile reach's `shaderInt64`, among
/// others) or gives no device address.
fn capture_steps(&mut self, records: u64, total: u32) -> Option<CaptureSteps> {
let device = self.core.device().clone();
let kernels = [
OwnedModule::CaptureAssembly,
OwnedModule::TileReach,
OwnedModule::CaptureSettle,
]
.map(|which| device.owned_kernel(which).ok());
let [Some(assembly), Some(reach), Some(settle)] = kernels else {
return None;
};
let limits = &device.properties().description.limits;
let align = limits.min_storage_buffer_offset_alignment.max(32);
let mask_words = TileReachModule::mask_words(self.layout.extent, 1, 1);
let groups = |n: u32, local: u32| n.div_ceil(local).max(1);
let most = limits.max_compute_work_group_count[0];
if groups(total, CaptureAssemblyModule::LOCAL_SIZE) > most
|| groups(total, TileReachModule::LOCAL_SIZE) > most
|| groups(mask_words, CaptureSettleModule::LOCAL_SIZE) > most
{
return None;
}
let records_bytes = records * u64::from(CaptureAssemblyModule::RECORD_WORDS) * 4;
let primitives_bytes = u64::from(total) * u64::from(TileReachModule::PRIMITIVE_WORDS) * 4;
let mask_bytes = u64::from(mask_words) * 4;
let range = u64::from(limits.max_storage_buffer_range);
if records_bytes > range || primitives_bytes > range || mask_bytes > range {
return None;
}
let primitives_at = records_bytes.next_multiple_of(align);
let mask_at = (primitives_at + primitives_bytes).next_multiple_of(align);
let scratch = device
.own_buffer(mask_at + mask_bytes, ResourceOptions::private())
.ok()?;
let (raw, at) = scratch.at(0);
let address = scratch.device_address()?;
if !at.is_multiple_of(align) || !address.is_multiple_of(32) {
return None;
}
Some(CaptureSteps {
scratch,
raw,
records: (at, records_bytes, address),
primitives: (at + primitives_at, primitives_bytes),
mask: (at + mask_at, mask_bytes),
kernels: [assembly, reach, settle],
total,
mask_words,
})
}
/// Record the pass's kept draws again as capture draws, each through its capture form into
/// its records in `steps`' scratch, into an instance of a pass without attachments: the
/// instance and the draws' uses, or `None` where a draw records nothing (its capture form's
/// objects or pipeline not made yet, or a refusal). The encoder's current instance stays
/// the pass's; the pass keeps no draw from here on.
fn record_captures(&mut self, steps: &CaptureSteps) -> Option<(Instance, CommandUses)> {
let device = self.core.device().clone();
let shape = attachmentless::shape(1, 0);
let compatible = Arc::new(render_target::compatible_pass(&device, &shape).ok()?);
let draws = self.core.command_buffer().begin_draws(&compatible).ok()?;
let instance = Instance {
draws,
shape: Versioned::new(shape),
compatible,
recorded: false,
shadow: false,
shader_tests: false,
imageblock: false,
interlocked_writes: InterlockedStorage::NONE,
indirect_reads: IndirectReads::new(),
geometry_writes: GeometryWrites::new(),
tile_memory: false,
barriers: false,
views: ViewSetup::default(),
pieces: Vec::new(),
shadows: InstanceShadows::default(),
before: Vec::new(),
reformats: Vec::new(),
positioned: None,
rerecord: None,
bound: Bound::default(),
drawn: DrawnArea::default(),
inline: false,
continues: false,
kept: None,
planned: false,
feedback: Feedback::NONE,
storage_colors: 0,
};
let (_, _, base) = steps.records;
let recording = Keeping::Recording(Capturing {
records: base,
indices: None,
uses: CommandUses::default(),
missed: false,
});
// The kept draws leave the pass's keeping for the capture draws' recording, the pass's
// instance for the capture's: each a state the encoder moves on to, given back below.
let Keeping::Draws(mut kept, _) = std::mem::replace(&mut self.keeping, recording) else {
return None;
};
let current = std::mem::replace(&mut self.current, instance);
let mut first = 0u64;
let mut recorded = true;
for draw in kept.iter_mut() {
let Some((count, instances)) = counts(&draw.draw()) else {
recorded = false;
break;
};
let indices = match draw.index() {
None => Some(None),
Some(index) => index.address().map(Some),
};
let (Some(indices), Keeping::Recording(capturing)) = (indices, &mut self.keeping)
else {
recorded = false;
break;
};
capturing.records = base + first * u64::from(CaptureAssemblyModule::RECORD_WORDS) * 4;
capturing.indices = indices;
let again = self.record_again(draw);
let missed = matches!(&self.keeping, Keeping::Recording(c) if c.missed);
if again.is_err() || missed {
recorded = false;
break;
}
first += count * instances;
}
let instance = std::mem::replace(&mut self.current, current);
// The pass ends: it keeps no draw from here on.
let Keeping::Recording(capturing) = std::mem::replace(&mut self.keeping, Keeping::Stopped)
else {
self.end_unrun(instance);
return None;
};
if !recorded {
// A capture that records nothing is never executed.
self.end_unrun(instance);
return None;
}
Some((instance, capturing.uses))
}
/// Record, into the encoder's command buffer before the pass, the capture draws' instance
/// `recorded` and the kernels over `steps`' scratch: the records the draws write, assembled
/// into the primitives (the draws' `draws` bytes), binned into the mask under the pass's
/// header and states (`pass`), and settled.
fn record_capture_steps(
&mut self,
steps: CaptureSteps,
(instance, uses): (Instance, CommandUses),
(draws, pass): (&[u8], &[u8]),
(grid, bound): (u64, u64),
) -> Option<CapturedReach> {
let device = self.core.device().clone();
// SAFETY: only this encoder records the secondary command buffer.
unsafe { self.core.command_buffer().end_raw(instance.draws) }.ok()?;
let framebuffer = render_target::attachmentless_framebuffer(
&device,
&instance.compatible,
self.layout.extent,
)
.ok()?;
let (draws_upload, pass_upload, status, tally) = {
let mut state = self.core.command_buffer().state();
let draws_upload = state
.uploads
.upload(&device, draws, draws.len() as u64)
.ok()?;
let pass_upload = state
.uploads
.upload(&device, pass, pass.len() as u64)
.ok()?;
let status = state.status_words(&device).ok()?;
let tally = state.uploads.upload(&device, &[], steps.mask.1).ok()?;
(draws_upload, pass_upload, status, tally)
};
let region = |upload: &crate::upload::Upload| (upload.raw(), upload.offset(), upload.len());
let (records_at, records_bytes, _) = steps.records;
let records = (steps.raw, records_at, records_bytes);
let primitives = (steps.raw, steps.primitives.0, steps.primitives.1);
let mask = (steps.raw, steps.mask.0, steps.mask.1);
let status = (status.raw(), status.offset(), ExecutionStatus::BYTES as u64);
let [assembly, reach, settle] = steps.kernels;
let sets = OwnedSets::write_each(
&device,
&[assembly, reach, settle],
&[
buffers(vec![records, region(&draws_upload), primitives]),
buffers(vec![primitives, region(&pass_upload), mask]),
buffers(vec![status, region(&pass_upload), mask]),
],
)
.ok()?;
let descriptor_sets = sets.sets.clone();
let groups = [
steps
.total
.div_ceil(CaptureAssemblyModule::LOCAL_SIZE)
.max(1),
steps.total.div_ceil(TileReachModule::LOCAL_SIZE).max(1),
steps
.mask_words
.div_ceil(CaptureSettleModule::LOCAL_SIZE)
.max(1),
];
let [width, height] = self.layout.extent;
let render_area = vk::Rect2D {
offset: vk::Offset2D { x: 0, y: 0 },
extent: vk::Extent2D { width, height },
};
let (pass_raw, framebuffer_raw, capture_draws) =
(instance.compatible.raw, framebuffer.raw, instance.draws);
let stages = uses.iter().fold(CAPTURE_STAGES, |all, used| {
all | used.read.stages | used.write.stages
});
let (mask_raw, mask_at, mask_bytes) = mask;
let tally_copy = vk::BufferCopy {
src_offset: mask_at,
dst_offset: tally.offset(),
size: mask_bytes,
};
let tally_raw = tally.raw();
self.core
.command_reaching(stages, &uses, uses.resident(), |raw, command_buffer| {
// SAFETY: the encoder's command buffer is recording outside a render pass (the
// pass records after it), and only the encoder records it; the pass without
// attachments, its framebuffer, the capture draws' secondary command buffer
// (recorded against that pass), the scratch, the uploads, the status words and
// the sets are live until the command buffer completes (retained below, the
// uploads and status words with the command buffer); every binding lies inside
// its buffer, and each step reads what the one before it wrote past a barrier.
unsafe {
Barrier::everything().record(raw, command_buffer);
raw.cmd_fill_buffer(command_buffer, mask_raw, mask_at, mask_bytes, 0);
let begin = vk::RenderPassBeginInfo::default()
.render_pass(pass_raw)
.framebuffer(framebuffer_raw)
.render_area(render_area);
raw.cmd_begin_render_pass(
command_buffer,
&begin,
vk::SubpassContents::SECONDARY_COMMAND_BUFFERS,
);
raw.cmd_execute_commands(command_buffer, &[capture_draws]);
raw.cmd_end_render_pass(command_buffer);
for ((kernel, set), groups) in
steps.kernels.iter().zip(&descriptor_sets).zip(groups)
{
Barrier::everything().record(raw, command_buffer);
raw.cmd_bind_pipeline(
command_buffer,
vk::PipelineBindPoint::COMPUTE,
kernel.pipeline,
);
raw.cmd_bind_descriptor_sets(
command_buffer,
vk::PipelineBindPoint::COMPUTE,
kernel.layout,
0,
std::slice::from_ref(set),
&[],
);
raw.cmd_dispatch(command_buffer, groups, 1, 1);
}
Barrier::everything().record(raw, command_buffer);
// The mask where the host counts it once the command buffer completes.
raw.cmd_copy_buffer(command_buffer, mask_raw, tally_raw, &[tally_copy]);
}
});
self.core.retain(steps.scratch);
self.core.retain(sets);
self.core.retain(framebuffer);
self.core.retain(instance.compatible);
device
.shared()
.counts
.capture_reach_recorded(u64::from(steps.total));
let tally = CaptureTally {
mask: tally,
grid,
bound,
};
self.core
.command_buffer()
.state()
.capture_tallies
.push(tally);
Some(CapturedReach { mask })
}
}
/// A set of storage buffers alone, `(buffer, offset, range)` in binding order.
fn buffers(buffers: Vec<(vk::Buffer, u64, u64)>) -> OwnedSet {
OwnedSet {
images: Vec::new(),
storage_images: Vec::new(),
buffers,
}
}
/// The stages the capture steps run in besides their draws' uses'.
const CAPTURE_STAGES: vk::PipelineStageFlags2 = vk::PipelineStageFlags2::from_raw(
vk::PipelineStageFlags2::TRANSFER.as_raw()
| vk::PipelineStageFlags2::VERTEX_SHADER.as_raw()
| vk::PipelineStageFlags2::COMPUTE_SHADER.as_raw(),
);
/// A pass's capture scratch and kernels (`RenderCommandEncoder::capture_steps`).
struct CaptureSteps {
scratch: crate::Buffer,
/// The scratch's `VkBuffer`.
raw: vk::Buffer,
/// The records' offset in `raw`, their bytes, and their device address.
records: (u64, u64, u64),
/// The primitives' offset in `raw` and bytes.
primitives: (u64, u64),
/// The mask's offset in `raw` and bytes.
mask: (u64, u64),
/// The assembly's, the tile reach's and the settle's kernels.
kernels: [OwnedKernel; 3],
/// The primitives, and the mask's words.
total: u32,
mask_words: u32,
}
@@ -75,7 +75,6 @@
//! its texture. A draw that reads its own group's attachments where it runs in that group alone
//! reads them as in any pass (`texture/attached_reads.rs`).
use super::capture;
use super::extended_shadow::ExtendedShadows;
use super::{
reads_handles, DrawingState, Opening, RenderLog, RenderLowering, RenderPipelineState,
@@ -419,16 +418,13 @@ pub(super) struct Ended {
pub(super) core: EncoderCore,
pub(super) residency: Residency,
pub(super) log: Option<RenderLog>,
/// A rebind may encode the encoder again from its log: its end captured no draws' tile
/// reach, whose tally lies in the command buffer (`render/capture.rs`).
pub(super) keeps_log: bool,
pub(super) later: Option<Box<Later>>,
}
impl Ended {
/// The pass's later color groups drawn (the module docs), each over the encoder's core from
/// its log: the core, what the first group's encoder made resident, and the log where a
/// rebind may encode the encoder again from it.
/// its log: the core, what the first group's encoder made resident, and the log, from which
/// a rebind may encode the encoder again.
pub(super) fn with_later_groups(
self,
) -> Result<(EncoderCore, Residency, Option<RenderLog>), Error> {
@@ -436,7 +432,6 @@ impl Ended {
mut core,
residency,
log,
mut keeps_log,
later,
} = self;
if let Some(later) = later {
@@ -452,12 +447,11 @@ impl Ended {
));
}
let ended = encoder.end_pass()?;
keeps_log &= ended.keeps_log;
core = ended.core;
core.device().shared().counts.color_group_pass();
}
}
Ok((core, residency, log.filter(|_| keeps_log)))
Ok((core, residency, log))
}
}
@@ -631,10 +625,8 @@ impl RenderLowering {
!depth_stencil && !writes_colors(state, g.group.colors().len())
}
/// A later group skips the draw: the pass's draws are no longer kept for capture replay in
/// that group's pass, whose reach is then the host's (`render/capture.rs`).
/// A later group skips the draw, counted.
pub(super) fn group_skipped(&mut self) {
self.keeping = capture::Keeping::Stopped;
self.core
.device()
.shared()
@@ -538,8 +538,8 @@ impl ShapeInputs<'_> {
.as_ref()
.and_then(|ds| ds.depth_format)
.or(settings.hidden.then_some(HIDDEN_DEPTH_FORMAT));
let bias = self.state.vk_depth_bias(topology, depth_format, profile)?;
let depth_bias = DepthBiasRecord::of(&bias, device.shared().depth_bias_command)?;
let bias = self.state.vk_depth_bias(topology, profile)?;
let depth_bias = DepthBiasRecord::of(&bias);
// 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);
@@ -545,11 +545,10 @@ impl RenderLowering {
if !icb.descriptor().inherit_pipeline_state {
self.writers.runs(icb.written().named().writes);
}
// An execution rewrites an extended-range or padded attachment as a draw does, of reset
// commands too, and a signed normalized one's minimum codes, and an
// An execution keeps an extended-range, padded or bfloat attachment's texels as a draw
// does, of reset commands too, and a signed normalized one's minimum codes, and an
// `RGB9E5Float` one's words.
self.degrade_kept_attachments();
self.rewrites_unused_bits = true;
self.degrade_extended_range_execution();
// Its commands write the extended-range colors' codes alone: the shadows end.
self.end_extended_shadows();
@@ -654,8 +653,6 @@ impl RenderLowering {
// Its pixels are not bounded by a viewport the host knows of.
self.drawn.everywhere();
self.coverage.everywhere();
// Nor do its positions run again before the pass (`render/capture.rs`).
self.keeping = super::capture::Keeping::Stopped;
let inherited = icb.descriptor().inherit_buffers;
// An execution's commands take their flat inputs from the first vertex whatever the
// encoder's provoking vertex mode (Metal probes on the M3 Max, macOS 27.0.1).
@@ -2388,7 +2385,6 @@ impl RenderExecution {
tile_dispatch_calls: 0,
replaying: true,
rerouting: false,
keeping: super::capture::Keeping::Stopped,
forms,
replayed: None,
drawn_before: snapshot.drawn.clone(),
@@ -2410,9 +2406,6 @@ impl RenderExecution {
// A pass that executes render commands keeps its attachments over buffers in place
// (`kept_bytes.rs`), whatever its draws read.
inputs_read: BTreeSet::new(),
// The encoder that executes the commands records the pass's load pass
// (`defer_execution`); this one records only the commands' draws.
rewrites_unused_bits: false,
kept_attachments: None,
// The executing encoder announces for the execution (`defer_execution`).
extended_written: BTreeSet::new(),
@@ -33,7 +33,7 @@
//! commands or a tile dispatch, whose commands write the codes alone, gives up every shadow:
//! the codes hold the encode of the last `half` written, and the draws after it see them, as
//! before the shadow. None starts again in the pass. Not while the encoder records an
//! execution's commands or a capture draw (`render/capture.rs`), which bind no shadow.
//! execution's commands, which bind no shadow.
//! - **The announcement**. A draw that held a color's shadow read what Metal's tile memory holds,
//! so `extended-range-blends-stored-codes` names only the colors a draw read from the codes
//! (`degrade_extended_range_blends`, `ExtendedShadows::held`).
@@ -413,10 +413,10 @@ fn color(
impl RenderLowering {
/// The shadows a draw binds: the held ones, none while the encoder records an execution's
/// commands or a capture draw.
/// commands.
pub(super) fn extended_shadows_bound(&self) -> &BTreeSet<u32> {
static NONE: BTreeSet<u32> = BTreeSet::new();
match self.replaying || self.capture_addresses().is_some() {
match self.replaying {
true => &NONE,
false => &self.extended.live,
}
@@ -430,7 +430,6 @@ impl RenderLowering {
if !self.extended.holds
|| self.replaying
|| self.rerouting
|| self.capture_addresses().is_some()
|| pipeline.descriptor().vertex().is_none()
{
return Ok(());
@@ -540,7 +539,7 @@ impl RenderLowering {
/// Once a draw of `pipeline` installed its instance: the shadows that instance first holds
/// are set before it, and what it may write is noted.
pub(super) fn installed_extended_draw(&mut self, pipeline: &DrawingState) {
if self.replaying || self.capture_addresses().is_some() {
if self.replaying {
return;
}
let at = self.earlier.len();
@@ -306,8 +306,8 @@ impl RenderLowering {
/// Where the pass's first instance may record inline (`Inline::Open`) and the draw about to
/// record into `next` is its first that records (`records`), decide: where the instance
/// allows it (the module docs; `made` its pipeline, `capture` a capture draw, `writes` that
/// the draw writes a memoryless color, `stood` a stand-in arriving with it), its render pass
/// allows it (the module docs; `made` its pipeline, `writes` that the draw writes a
/// memoryless color, `stood` a stand-in arriving with it), its render pass
/// and framebuffer, and the command buffer the
/// encoder holds for it, for [`begin_inline`](Self::begin_inline) once the draw installed
/// its instance; else `None`, and the pass records as before: so for a draw whose `feedback`
@@ -321,14 +321,14 @@ impl RenderLowering {
&mut self,
next: &Next,
stood: Option<&PassLayout>,
(records, made, capture, writes): (bool, bool, bool, bool),
(records, made, writes): (bool, bool, bool),
feedback: Feedback,
) -> Result<Option<InlineBegin>, Error> {
let begin = match feedback == Feedback::NONE {
true => self.decide_inline(next, stood, (records, made, capture, writes))?,
true => self.decide_inline(next, stood, (records, made, writes))?,
false => {
// Decided at this draw: the pass records its first instance in a secondary.
if matches!(self.inline, Inline::Open { .. }) && records && !capture {
if matches!(self.inline, Inline::Open { .. }) && records {
self.inline = Inline::Never;
(self.core.device().shared().counts).pass_not_inline(NotInline::Draws);
}
@@ -350,12 +350,12 @@ impl RenderLowering {
&mut self,
next: &Next,
stood: Option<&PassLayout>,
(records, made, capture, writes): (bool, bool, bool, bool),
(records, made, writes): (bool, bool, bool),
) -> Result<Option<InlineBegin>, Error> {
let Inline::Open { splits } = self.inline else {
return Ok(None);
};
if !records || capture {
if !records {
return Ok(None);
}
// Decided at this draw, either way.
@@ -243,14 +243,14 @@ pub(super) struct SplitBegin {
impl RenderLowering {
/// Whether the draw about to record into `next` begins a new instance that records inline
/// after the current one (the module docs; `records`: the draw records, `made` its pipeline,
/// `capture` a capture draw, `stood` a stand-in arriving with it); where it does, the current
/// `stood` a stand-in arriving with it); where it does, the current
/// instance's copies planned, which the draw records once installed. `None` where it does
/// not, or where the plan is refused (the pass's end plans it again, and refuses it there).
pub(super) fn inline_split(
&mut self,
next: &Next,
stood: Option<&PassLayout>,
(records, made, capture): (bool, bool, bool),
(records, made): (bool, bool),
) -> Option<SplitBegin> {
let inline_first::Inline::Begun(begun) = &self.inline else {
return None;
@@ -271,7 +271,6 @@ impl RenderLowering {
let admitted = begun.splits
&& records
&& made
&& !capture
&& self.current.inline
&& !self.current.continues
&& !self.replaying
@@ -12,9 +12,7 @@
//! - **Kept** as the compute encoder's log is (`EncoderCore::end_with_replay`): where a command
//! named a buffer over host pages, and the pass left no segment for later but its executions of
//! indirect command buffers, which the encoding again records at once on the GPU alone, as its
//! commit did (no draw whose pipeline was still being made). A pass whose draws' tile
//! reach its end captures (`capture.rs`) keeps none: the capture's tally lies in the command
//! buffer, where an encoding again would leave the first one's beside its own.
//! commit did (no draw whose pipeline was still being made).
//! - **Per-stage calls** share a variant, with the [`Table`] they set.
use super::RenderLowering;
@@ -62,28 +62,6 @@ pub(super) struct Rerecord {
held: Held,
}
impl Rerecord {
/// The draw.
pub(super) fn draw(&self) -> DrawCall {
self.draw
}
/// What the draw assembles.
pub(super) fn assembly(&self) -> Assembly {
self.assembly
}
/// The encoder's state at the draw.
pub(super) fn state(&self) -> &EncoderState {
&self.held.state
}
/// The draw's indices, read in place.
pub(super) fn index(&self) -> Option<&KeptSource> {
self.index.as_ref()
}
}
/// The encoder's state a draw reads, as it stood at the draw.
struct Held {
pipeline: Option<RenderPipelineState>,
@@ -151,7 +129,6 @@ impl RenderLowering {
.is_some_and(|draws| !draws.is_empty());
if self.replaying
|| self.rerouting
|| self.capture_addresses().is_some()
|| !current.recorded
|| !kept
|| self.layout.fetch_inputs
@@ -267,27 +244,6 @@ impl RenderLowering {
}
}
/// The draw just recorded (`call` of `assembly` and `draw`, its indices from `index`) with
/// the encoder's state at it, kept for recording again elsewhere (`render/capture.rs`);
/// `None` where its indices cannot be kept.
pub(super) fn kept_draw(
&self,
(call, assembly, draw): (&'static str, Assembly, DrawCall),
index: Option<&DrawSource<'_>>,
) -> Option<Rerecord> {
let index = match index {
Some(source) => Some(source.kept()?),
None => None,
};
Some(Rerecord {
call,
assembly,
draw,
index,
held: self.held(),
})
}
/// Exchange the encoder's state a draw reads with `held`.
fn swap_held(&mut self, held: &mut Held) {
std::mem::swap(&mut self.pipeline, &mut held.pipeline);
@@ -20,9 +20,8 @@
//! back. A pass whose draws do reach tiles, some or (where it clears and stores an attachment)
//! every one, changes a color attachment it loads (as the encoder set its load, so no clear
//! before the pass reaches it: a clear past the render area clears attachments loaded `Clear`
//! alone, `clear_reach.rs`) only inside its draws' scissors (`clear_reach::DrawnArea`), the
//! load pass of a format whose tiles Metal stores otherwise rewriting the buffer's bytes before
//! it (`render/unused_bits_load.rs`): only those texels are copied back, and, where the pass
//! alone, `clear_reach.rs`) only inside its draws' scissors (`clear_reach::DrawnArea`): only
//! those texels are copied back, and, where the pass
//! takes the texture in no other way, only those are copied in, as nothing the pass reads
//! outside them reaches anything but the image (its load is stored back unchanged, and a
//! fragment reads the attachment at its own pixel alone). A texture over a buffer with an
@@ -70,7 +70,7 @@
//! - **Where it runs** (each check else the split, as before): the device enabled
//! `attachmentFeedbackLoopLayout`, `extendedDynamicState3ColorWriteMask` and
//! `fragmentShaderPixelInterlock` (`dynamic_state::ColorWriteMasks`); the draw follows a barrier
//! inside its instance, records no execution's command, capture or reroute, and runs in a pass
//! inside its instance, records no execution's command or reroute, and runs in a pass
//! with no visibility query active, no input attachment fetch, rasterization-rate map, views or
//! more than one sample or layer; every slot of the draw that reads a color attachment's texture
//! is a fragment slot its function can read through a snapshot (`StageModule::snapshot_textures`)
@@ -256,9 +256,8 @@ impl RenderLowering {
&self,
pipeline: &DrawingState,
reformats: &[Reformat],
capture: bool,
) -> Option<Wanted> {
if capture || self.replaying || self.rerouting || !(self.current.barriers || self.barrier) {
if self.replaying || self.rerouting || !(self.current.barriers || self.barrier) {
return None;
}
let base = pipeline.base();
@@ -1237,8 +1237,6 @@ impl RenderLowering {
// Its pixels are not bounded by a viewport the host knows of.
self.drawn.everywhere();
self.coverage.everywhere();
// Nor do its positions run again before the pass (`render/capture.rs`).
self.keeping = super::capture::Keeping::Stopped;
let executed = || ExecutedPipeline::Compute(Arc::clone(variant.shared_pipeline()));
match (&made_pipelines, creation) {
(Some(made), _) => self.core.executed(|| {
@@ -0,0 +1,150 @@
//! What a render pass's store keeps of the texels its draws do not write, where Metal's tile store
//! rewrites them: the kept-attachment notices a draw announces.
//!
//! - **Metal's answer** (an Apple M3 Max under macOS 27.0.1, and an Apple M4). An Apple GPU stores
//! a render pass's attachments a 32 x 32 tile at a time, and a pass that loads a color attachment
//! and records a draw writes every texel of each tile a draw's primitives reach back, through its
//! tile memory: the texels no fragment covers, fragments that discard or fail a test, and
//! channels a write mask leaves out among them. A tile no draw reaches keeps its bytes, and a
//! pass that draws nothing keeps every texel.
//! - An extended-range or padded 10-bit attachment (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`,
//! `R10Unorm_X6`, `RG10Unorm_X12` or one of their `_sRGB` twins) keeps each texel's codes with
//! the bits they leave unused made canonical: `BGR10_XR`'s bits 30 and 31 ones,
//! `BGRA10_XR`'s low six bits of each field zeros and its alpha code clamped to `[384, 894]`,
//! the two-plane color word's top two bits zeros, a padded word's low six bits zeros, a padded
//! `_sRGB` twin's codes through Metal's table.
//! - A bfloat attachment (`R16Bfloat`, `RG16Bfloat`, `RGBA16Bfloat`) holds `half` values in its
//! tiles: every code of each tile it stores back goes through `half` to nearest even and back
//! to the nearest bfloat code, a NaN to `0x7fc0` (on the M4, every code of each format: 56,829
//! move; on the M3 Max our probe `bfl`, every code of the tile a small triangle reached).
//! - A single-sampled signed normalized attachment stores a channel's minimum code (-128, or
//! -32768) as the code above it, and an `RGB9E5Float` one normalizes a word whose largest
//! mantissa is below 256 under an exponent above 0 (the M3 Max).
//! - **The runtime's answer: the device's load and store.** The device's pass keeps every byte its
//! draws do not write (`VK_ATTACHMENT_STORE_OP_STORE` of a loaded attachment), on every device:
//! no code is rewritten before or after the pass. A draw announces what differs, naming the
//! attachments of its pass: `extended-range-bits-kept` for an extended-range, padded or bfloat
//! one ([`bits_kept`]), `snorm-minimum-kept` ([`snorm_minimum_kept`]) and
//! `shared-exponent-kept` ([`shared_exponent_kept`]), the last two but on a driver whose pass
//! stores them as Metal's (`DriverFact::TileStoreIsMetals`: MoltenVK's pass is a Metal pass). A
//! pass whose store discards the attachment (`DontCare`) keeps nothing either way. The first
//! notice holds on MoltenVK too: an extended-range, padded or bfloat attachment is an image of
//! an unsigned integer format on every device (`metal::format::ExtendedRange`), whose codes a
//! Metal pass stores as they are.
use crate::device::Device;
use crate::render_pass::{ColorTarget, PassLayout, Target};
use crate::render_values::{LoadAction, StoreAction};
use metal2vulkan::device::DriverFact;
use metal2vulkan::metal::format::ExtendedRange;
use metal2vulkan::metal::PixelFormat;
/// The texture's own target of `color`: a stand-in's (`attachment_stand_in.rs`) is the one it
/// stands in for.
fn own(color: &ColorTarget) -> &Target {
color.stand_in.as_ref().map_or(&color.target, |s| &s.own)
}
/// Whether `device`'s render pass stores a signed normalized minimum code and an `RGB9E5Float`
/// word as Metal's tile store does (`DriverFact::TileStoreIsMetals`: MoltenVK's pass is a Metal
/// pass).
pub(super) fn metals_store(device: &Device) -> bool {
device
.properties()
.driver_facts
.contains(&DriverFact::TileStoreIsMetals)
}
/// Whether `color` is an attachment of an extended-range, padded 10-bit or bfloat format, loaded
/// and not discarded at the store (a store action the encoder decides later counts as storing):
/// Metal's pass, once it draws, rewrites the texels its draws do not write, where the device's
/// pass keeps their bytes (the module docs).
pub(super) fn bits_kept(color: &ColorTarget) -> bool {
let discarded = color.store == StoreAction::DontCare && !color.late_store;
ExtendedRange::of(own(color).texture.pixel_format()).is_some()
&& color.load == LoadAction::Load
&& !color.memoryless
&& !discarded
}
/// The signed normalized color formats whose minimum code Metal's tile store rewrites, as
/// measured on an Apple M3 Max (`snorm-minimum-kept`).
const SNORM_MINIMUM: [PixelFormat; 6] = [
PixelFormat::R8Snorm,
PixelFormat::RG8Snorm,
PixelFormat::RGBA8Snorm,
PixelFormat::R16Snorm,
PixelFormat::RG16Snorm,
PixelFormat::RGBA16Snorm,
];
/// Whether `color` is a single-sampled attachment of a signed normalized format
/// ([`SNORM_MINIMUM`]), loaded and not discarded at the store: Metal's pass, once it draws, writes
/// each tile a draw reaches back through the channels' values, so a minimum code (-128, or -32768)
/// is stored as the code above it, where the device's pass keeps the bytes its draws do not write
/// (`degrade_snorm_minimum`, which reads `DriverFact::TileStoreIsMetals`: a driver whose pass
/// stores them as Metal's).
pub(super) fn snorm_minimum_kept(color: &ColorTarget) -> bool {
kept_through_store(color, |format| SNORM_MINIMUM.contains(&format))
}
/// Whether `color` is a single-sampled `RGB9E5Float` attachment, loaded and not discarded at the
/// store: Metal's pass, once it draws, writes each tile a draw reaches back through its texels'
/// values, so a word whose largest mantissa is below 256 under an exponent above 0 (one no Metal
/// write leaves) is stored normalized, its mantissas shifted up as its exponent steps down, where
/// the device's pass keeps the bytes its draws do not write (`degrade_shared_exponent`, which reads
/// `DriverFact::TileStoreIsMetals`).
pub(super) fn shared_exponent_kept(color: &ColorTarget) -> bool {
kept_through_store(color, |format| format == PixelFormat::RGB9E5Float)
}
/// Whether `color` is a single-sampled attachment of a format `of` takes, loaded and not
/// discarded at the store.
fn kept_through_store(color: &ColorTarget, of: impl Fn(PixelFormat) -> bool) -> bool {
let target = own(color);
let discarded = color.store == StoreAction::DontCare && !color.late_store;
of(target.texture.pixel_format())
&& target.samples == 1
&& color.load == LoadAction::Load
&& !color.memoryless
&& !discarded
}
/// The color attachments of a pass's layout that each of a draw's kept-attachment notices names, as
/// `color {index}, {format:?}`: the extended-range, padded and bfloat ones ([`bits_kept`],
/// `degrade_unused_bits`) and, on a driver whose pass does not store as Metal's
/// ([`metals_store`]), the signed normalized ones ([`snorm_minimum_kept`],
/// `degrade_snorm_minimum`) and the `RGB9E5Float` ones ([`shared_exponent_kept`],
/// `degrade_shared_exponent`). They read the layout's colors, their textures' formats and samples,
/// and the device's driver facts; all but the layout are fixed at creation, so an encoder decides
/// them once for each layout it records under.
#[derive(Debug, Default, PartialEq)]
pub(super) struct KeptAttachments {
pub(super) unused_bits: Vec<String>,
pub(super) snorm_minimum: Vec<String>,
pub(super) shared_exponent: Vec<String>,
}
impl KeptAttachments {
/// The kept attachments of `layout`, a pass of `device`'s.
pub(super) fn of(layout: &PassLayout, device: &Device) -> Self {
let metals = metals_store(device);
let mut kept = Self::default();
for (index, color) in layout.colors.iter().enumerate() {
let Some(color) = color else {
continue;
};
let name = || format!("color {index}, {:?}", color.target.texture.pixel_format());
if bits_kept(color) {
kept.unused_bits.push(name());
}
if !metals && snorm_minimum_kept(color) {
kept.snorm_minimum.push(name());
}
if !metals && shared_exponent_kept(color) {
kept.shared_exponent.push(name());
}
}
kept
}
}
@@ -1,877 +0,0 @@
//! The load pass of an extended-range, padded 10-bit or bfloat color attachment.
//!
//! - **Metal's answer** (on an Apple M4 under macOS 27.0.1 and on the consumer's Apple M3 Max under
//! macOS 26.7, alike; on both). An Apple GPU stores a render pass's attachments a 32 x 32 tile at
//! a time. A pass that loads a color attachment of `BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`,
//! `R10Unorm_X6`, `RG10Unorm_X12` or one of their `_sRGB` twins and records a draw writes every
//! texel of each tile it stores back: a channel a fragment writes takes the write, and every
//! other texel keeps its codes with the bits they leave unused made canonical
//! (`bind::unused_bits_module`: `BGR10_XR`'s bits 30 and 31 ones, `BGRA10_XR`'s low six bits of
//! each field zeros and its alpha code clamped to `[384, 894]`, the two-plane color word's top
//! two bits zeros, a padded word's low six bits zeros, the padded `_sRGB` twins' codes through
//! Metal's table). That includes the texels no fragment covers, fragments that discard or fail a
//! test, and channels a write mask leaves out. A pass that loads a bfloat color attachment
//! (`R16Bfloat`, `RG16Bfloat`, `RGBA16Bfloat`) and draws does so too, its tiles holding `half`
//! values: every code of each tile it stores back goes through `half` to nearest even and back to
//! the nearest bfloat code, a NaN to `0x7fc0` (`ExtendedRange::load_code`; on an Apple M4
//! under macOS 27.0.1, every code of each format: 56,829 move, and only in the tiles the draws'
//! primitives reach; the M3 Max under macOS 27.0.1 alike, our probe `bfl`: every code of the
//! tile a small triangle reached, of each format, and none elsewhere). The tiles it stores are those a draw's primitives reach (the half of a rect
//! whose edge lies on x = 32 reaches the tiles right of it; a zero-area rect or one off the
//! target reaches none), within the render area rounded up to 32 texels a side from the origin
//! and kept within the texture; every tile of it where a color attachment of the pass is cleared
//! and stored, a draw of nothing (of no vertices, say) too. A pass that draws nothing keeps every
//! texel.
//! - **The runtime's answer.** Before a pass that loads such an attachment, stores it and records
//! a draw call or an execution of render commands, ahead of the pass's other steps (a shadow's
//! or a stand-in's copy in among them), the encoder copies the region's texels into a scratch
//! buffer, rewrites the words of each tile a [`TileReach`] names there (one dispatch of
//! `bind::unused_bits_module` of the attachment's form a band of rows), and copies them back.
//! The texels come from the buffer's bytes of a texture over a buffer, a surface's plane, or a
//! texture buffer's attachment twin (`Texture::attachment_twin`), a 2D texture or a 2D array
//! view of one layer (a two-plane format's plane 0 color words alone, `TexelWords::ColorPlane`),
//! and from the image of any other single-sampled texture the runtime holds as an image of its
//! own (`TexelWords::Raw`), every layer the pass renders of its level. The pass then loads
//! Metal's texels, and a write mask, a discard, a test and a texel no draw covers keep them as
//! Metal's pass does. A pass whose store discards the attachment (`DontCare`, which leaves the
//! bytes as they were) is left alone.
//! - **A rotated texture's frame**. A rotated texture renders through its twin of the pass's frame
//! (`rotated.rs`), an image the shadow's copy in fills from the plane's bytes by Metal's load map
//! (`Turn::Load`, in a pass that draws). Its tiles are the frame's, so the load pass rewrites
//! that image instead, right after the pass's shadows' copies in ([`record_frames`]) and before
//! its stand-ins' copies and clears: the frame's texels of each tile, mapped back through the
//! rotation by the copy out (`Turn::Store`) as the pass's own writes are, which leaves the
//! plane's words as Metal's pass leaves them, by Metal's tile rule and rotation maps (each
//! measured on its own).
//! - **The reach** ([`TileReach`], from the pass's `clear_reach::PassReach`). None in a pass whose
//! draws reach no tile (each draws nothing, of no vertex or instance or through a pipeline that
//! rasterizes nothing, and no attachment is cleared and stored): the pass keeps every texel, as
//! Metal's does. Every tile of the region, exact, where an attachment of a pass of one layer is
//! cleared and stored. Elsewhere the tiles the draws' viewports and scissors reach
//! (`clear_reach::DrawnArea`; every tile through a rasterization-rate map, an execution of render
//! commands or a tile dispatch), and `unreached-tiles-rewritten` names the attachments, whose
//! tiles there no draw reaches are rewritten here where Metal keeps them; but where capture
//! replay found the tiles the draws' primitives reach (`render/capture.rs`, Metal's, announced by
//! the command buffer where a primitive's reach was not measured).
//! - **A signed normalized or `RGB9E5Float` attachment** keeps the device's load and store. The
//! same pass, once it draws, writes a single-sampled such attachment's tiles back through their
//! values (an Apple M3 Max under macOS 27.0.1): a channel's minimum code (-128, or -32768) is
//! stored as the code above it, and a word whose largest mantissa is below 256 under an exponent
//! above 0 normalized. The device's pass keeps such a code or word, and a draw announces
//! `snorm-minimum-kept` or `shared-exponent-kept` ([`snorm_minimum_kept`],
//! [`shared_exponent_kept`]), but on a driver whose pass stores them as Metal's
//! (`DriverFact::TileStoreIsMetals`: MoltenVK's pass is a Metal pass).
//! - **Not here** (`degrade_unused_bits` announces `extended-range-bits-kept` at each draw): a
//! multisampled attachment (no copy reaches its samples), a texture held as a shadow of another
//! image or of a heap's bytes, a sparse one, and one whose image the device does not copy both
//! ways. A padded format takes no multisample texture, Metal's validation stopping one, and
//! reaches the rest through a heap or a sparse heap, which make one of it as the device does
//! (`metal::format::padded_words`).
use super::capture::CapturedReach;
use crate::buffer_texture::Texels;
use crate::clear_reach::{DrawnTiles, PassReach};
use crate::degradation::Degradation;
use crate::device::functions::Vk;
use crate::device::Device;
use crate::encoder::EncoderCore;
use crate::error::{internal, Error};
use crate::owned_kernel::{OwnedModule, OwnedSets};
use crate::render_pass::{ColorTarget, PassLayout, Target};
use crate::render_values::{LoadAction, StoreAction};
use crate::shadow::ShadowTarget;
use crate::texture::Texture;
use crate::tracker::{Access, Barrier, Use, UseRange};
use crate::values::ResourceOptions;
use ash::vk;
use metal2vulkan::bind::{TexelWords, UnusedBitsModule};
use metal2vulkan::device::DriverFact;
use metal2vulkan::metal::format::ExtendedRange;
use metal2vulkan::metal::{PixelFormat, TextureType};
use metal2vulkan::vk::{ImageType, ImageUsageFlags};
/// The side, in texels, of the tiles Metal stores.
const TILE: u32 = UnusedBitsModule::TILE;
/// The scratch's largest band of rows: 32 MiB.
const MAX_SCRATCH: u64 = 32 << 20;
/// The tiles of a pass's region whose texels the load pass rewrites: those Metal's tile store
/// writes back, the tiles its draws reach (the module docs).
#[derive(Clone, Copy, Debug)]
pub(super) enum TileReach<'a> {
/// Every tile: Metal's answer where `exact`, else where Metal's are the tiles the draws'
/// primitives reach, until those are captured.
Every { exact: bool },
/// The tiles the draws' viewports and scissors reach (`clear_reach::DrawnTiles`, 32 by 32):
/// Metal's answer in each tile outside them, every tile inside rewritten.
Within(&'a DrawnTiles),
/// The tiles the draws' primitives reach, as capture replay binned them before the pass
/// (`render/capture.rs`): Metal's answer, but where a primitive's reach was not measured,
/// where the mask holds every tile and the command buffer announces it as it completes.
Captured(&'a CapturedReach),
}
/// What fills a load pass's tile mask ([`TileReach::mask`]).
enum Mask {
/// Every tile.
Every,
/// These words.
Words(Vec<u32>),
/// The words of capture replay's mask: its `VkBuffer`, offset and bytes.
Captured((vk::Buffer, u64, u64)),
}
impl<'a> TileReach<'a> {
/// The tiles the load pass rewrites in a pass whose draws reach `reach`: those `captured`
/// names where capture replay binned them, else within `tiles` where those bound them; none
/// where they reach none (`clear_reach.rs`).
pub(super) fn of(
reach: PassReach,
tiles: Option<&'a DrawnTiles>,
captured: Option<&'a CapturedReach>,
) -> Option<TileReach<'a>> {
match (reach, captured, tiles) {
(PassReach::Nothing, ..) => None,
(PassReach::Every, ..) => Some(TileReach::Every { exact: true }),
(PassReach::Draws, Some(captured), _) => Some(TileReach::Captured(captured)),
(PassReach::Draws, None, None) => Some(TileReach::Every { exact: false }),
(PassReach::Draws, None, Some(tiles)) => Some(TileReach::Within(tiles)),
}
}
/// Whether the reach is Metal's (a captured one's where its primitives' reach was measured,
/// which the command buffer announces otherwise).
fn exact(self) -> bool {
match self {
TileReach::Every { exact } => exact,
TileReach::Within(_) => false,
TileReach::Captured(_) => true,
}
}
/// The mask (one bit a tile, `bind::UnusedBitsModule`'s order) of `layers` layers of
/// `tile_rows` rows of `tiles_per_row` tiles, of `bytes` bytes. A captured mask is binned in
/// the same order over the render area (`bind::TileReachModule`, of one layer), whose tiles
/// are the region's: its bytes are the mask's, else the load pass is refused.
fn mask(
self,
tiles_per_row: u64,
tile_rows: u64,
(layers, bytes): (u64, u64),
) -> Result<Mask, Error> {
// A pass's tiles are 32 by 32 at one sample, the only count the load pass takes.
let tiles = match self {
TileReach::Within(tiles) if tiles.tile() == [TILE, TILE] => tiles,
TileReach::Captured(captured) => {
let (_, _, captured_bytes) = captured.mask;
return match layers == 1 && captured_bytes == bytes {
true => Ok(Mask::Captured(captured.mask)),
false => Err(internal("a captured tile mask of another grid")),
};
}
_ => return Ok(Mask::Every),
};
let per_layer = tiles_per_row * tile_rows;
let mut words = vec![0u32; (layers * per_layer).div_ceil(32) as usize];
for layer in 0..layers {
for ty in 0..tile_rows {
for tx in 0..tiles_per_row {
let reached = match (u32::try_from(tx), u32::try_from(ty)) {
(Ok(tx), Ok(ty)) => tiles.contains(tx, ty),
_ => true,
};
if reached {
let t = (layer * per_layer + ty * tiles_per_row + tx) as usize;
words[t / 32] |= 1 << (t % 32);
}
}
}
}
Ok(Mask::Words(words))
}
}
/// Record `mask` (of `bytes`) into `buffer` at `offset`.
///
/// # Safety
///
/// `command_buffer` is recording, outside a render pass, and `offset..offset + bytes` lies in
/// `buffer`, a multiple of 4 from a multiple of 4, and is not in use; a mask's words are
/// `bytes / 4` words, and a captured mask's bytes are `bytes` of a live buffer, written before a
/// barrier the command buffer recorded already.
unsafe fn record_mask(
raw: &Vk,
command_buffer: vk::CommandBuffer,
(buffer, offset, bytes): (vk::Buffer, u64, u64),
mask: &Mask,
) {
match mask {
// SAFETY: the caller's contract.
Mask::Every => unsafe {
raw.cmd_fill_buffer(command_buffer, buffer, offset, bytes, u32::MAX)
},
Mask::Captured((from, at, _)) => {
let region = vk::BufferCopy {
src_offset: *at,
dst_offset: offset,
size: bytes,
};
// SAFETY: the caller's contract.
unsafe { raw.cmd_copy_buffer(command_buffer, *from, buffer, &[region]) };
}
// At most 65536 bytes an update, as `vkCmdUpdateBuffer` takes.
Mask::Words(words) => {
for (i, chunk) in words.chunks(1 << 14).enumerate() {
let bytes: Vec<u8> = chunk.iter().flat_map(|w| w.to_le_bytes()).collect();
let at = offset + (i as u64) * (4 << 14);
// SAFETY: the caller's contract; the chunk lies in the mask's bytes.
unsafe { raw.cmd_update_buffer(command_buffer, buffer, at, &bytes) };
}
}
}
}
/// Where the load pass finds a taken attachment's texels.
enum Source<'a> {
/// The rows of a buffer's bytes, held as the words named.
Bytes(&'a Texels, TexelWords),
/// The texture's own image, its raw texels.
Image,
/// A rotated texture's image of the pass's frame, its raw texels, rewritten after the pass's
/// shadows' copies in ([`record_frames`]).
Frame,
}
/// A color attachment the load pass takes: its format, the target whose texels it rewrites (the
/// texture's own, where a stand-in renders for it), and where it finds them.
struct Taken<'a> {
format: PixelFormat,
target: &'a Target,
source: Source<'a>,
}
/// The texture's own target of `color`: a stand-in's (`attachment_stand_in.rs`) is the one it
/// stands in for.
fn own(color: &ColorTarget) -> &Target {
color.stand_in.as_ref().map_or(&color.target, |s| &s.own)
}
/// Whether the load pass rewrites a texture of `texture`'s format: an extended-range, padded or
/// bfloat one's.
fn rewrites(texture: &Texture) -> bool {
ExtendedRange::of(texture.pixel_format()).is_some()
}
/// Whether `device`'s render pass stores a signed normalized minimum code and an `RGB9E5Float`
/// word as Metal's tile store does (`DriverFact::TileStoreIsMetals`: MoltenVK's pass is a Metal
/// pass).
pub(super) fn metals_store(device: &Device) -> bool {
device
.properties()
.driver_facts
.contains(&DriverFact::TileStoreIsMetals)
}
/// Whether `color` is of a format the load pass rewrites ([`rewrites`]), loaded and not
/// discarded at the store; `late` counts a store action the encoder decides later as storing.
fn loaded(color: &ColorTarget, late: bool) -> bool {
let discarded = color.store == StoreAction::DontCare && !(late && color.late_store);
rewrites(&own(color).texture)
&& color.load == LoadAction::Load
&& !color.memoryless
&& !discarded
}
/// The color attachment `color` as the load pass takes it (the module docs), or `None` where it
/// does not.
fn takes(color: &ColorTarget, late: bool) -> Option<Taken<'_>> {
if !loaded(color, late) {
return None;
}
let target = own(color);
let texture = &target.texture;
let format = texture.pixel_format();
let turned = texture
.shadow()
.is_some_and(|copies| matches!(copies.target(), Some(ShadowTarget::Rotated { .. })));
if target.samples != 1 {
return None;
}
let copied = ImageUsageFlags::TRANSFER_SRC | ImageUsageFlags::TRANSFER_DST;
let copies_both_ways = || {
texture
.image_plan()
.is_ok_and(|plan| plan.usage.contains(copied))
};
// A rotated texture's frame, which its shadow's copy in fills.
if turned {
return copies_both_ways().then_some(Taken {
format,
target,
source: Source::Frame,
});
}
if let Some(texels) = texture.buffer_texels() {
let words = match ExtendedRange::of(format) {
Some(ExtendedRange::Planes { .. }) => TexelWords::ColorPlane,
_ => TexelWords::Raw,
};
let flat = matches!(
texture.texture_type(),
TextureType::Type2D | TextureType::Type2DArray
) && target.layers == 1;
let texel = u64::from(UnusedBitsModule::texel_bytes(format, words)?);
let rows_of_texels = texels.layout.row_bytes == u64::from(target.extent[0]) * texel;
return (flat && rows_of_texels).then_some(Taken {
format,
target,
source: Source::Bytes(texels, words),
});
}
let image = texture.shadow().is_none() && !texture.is_sparse() && copies_both_ways();
image.then_some(Taken {
format,
target,
source: Source::Image,
})
}
/// Whether capture replay's reach has a consumer in a pass of `layout` (`render/capture.rs`): the
/// load pass takes one of its color attachments, as the pass begins (`ended` false) or as it ends
/// (`ended`: its store actions set, one still `Unknown` discarding), and no rotated texture's
/// frame among them. A frame's twin is copied out whole (`rotated.rs`), so a tile no primitive
/// reaches would store the texels its copy in loaded where Metal's pass keeps the plane's (a
/// mirror at rotation 4): such a pass keeps the host's reach, announced.
pub(super) fn consumes_capture(layout: &PassLayout, ended: bool) -> bool {
let mut taken = layout
.colors
.iter()
.flatten()
.filter(|color| !ended || color.store != StoreAction::Unknown)
.filter_map(|color| takes(color, !ended))
.peekable();
taken.peek().is_some() && taken.all(|taken| !matches!(taken.source, Source::Frame))
}
/// Whether `color` is of an extended-range, padded or bfloat format, loaded and not discarded at
/// the store, where the load pass does not take it (`degrade_unused_bits`).
pub(super) fn untaken(color: &ColorTarget) -> bool {
ExtendedRange::of(own(color).texture.pixel_format()).is_some()
&& loaded(color, true)
&& takes(color, true).is_none()
}
/// The signed normalized color formats whose minimum code Metal's tile store rewrites, as
/// measured on an Apple M3 Max (`snorm-minimum-kept`).
const SNORM_MINIMUM: [PixelFormat; 6] = [
PixelFormat::R8Snorm,
PixelFormat::RG8Snorm,
PixelFormat::RGBA8Snorm,
PixelFormat::R16Snorm,
PixelFormat::RG16Snorm,
PixelFormat::RGBA16Snorm,
];
/// Whether `color` is a single-sampled attachment of a signed normalized format
/// ([`SNORM_MINIMUM`]), loaded and not discarded at the store: Metal's pass, once it draws, writes
/// each tile a draw reaches back through the channels' values, so a minimum code (-128, or -32768)
/// is stored as the code above it, where the device's pass keeps the bytes its draws do not write
/// (`degrade_snorm_minimum`, which reads `DriverFact::TileStoreIsMetals`: a driver whose pass
/// stores them as Metal's).
pub(super) fn snorm_minimum_kept(color: &ColorTarget) -> bool {
kept_through_store(color, |format| SNORM_MINIMUM.contains(&format))
}
/// Whether `color` is a single-sampled `RGB9E5Float` attachment, loaded and not discarded at the
/// store: Metal's pass, once it draws, writes each tile a draw reaches back through its texels'
/// values, so a word whose largest mantissa is below 256 under an exponent above 0 (one no Metal
/// write leaves) is stored normalized, its mantissas shifted up as its exponent steps down, where
/// the device's pass keeps the bytes its draws do not write (`degrade_shared_exponent`, which reads
/// `DriverFact::TileStoreIsMetals`).
pub(super) fn shared_exponent_kept(color: &ColorTarget) -> bool {
kept_through_store(color, |format| format == PixelFormat::RGB9E5Float)
}
/// Whether `color` is a single-sampled attachment of a format `of` takes, loaded and not
/// discarded at the store.
fn kept_through_store(color: &ColorTarget, of: impl Fn(PixelFormat) -> bool) -> bool {
let target = own(color);
let discarded = color.store == StoreAction::DontCare && !color.late_store;
of(target.texture.pixel_format())
&& target.samples == 1
&& color.load == LoadAction::Load
&& !color.memoryless
&& !discarded
}
/// The color attachments of a pass's layout that each of a draw's kept-attachment notices names, as
/// `color {index}, {format:?}`: the extended-range or padded ones the load pass does not take
/// ([`untaken`], `degrade_unused_bits`) and, on a driver whose pass does not store as Metal's
/// ([`metals_store`]), the signed normalized ones ([`snorm_minimum_kept`],
/// `degrade_snorm_minimum`) and the `RGB9E5Float` ones ([`shared_exponent_kept`],
/// `degrade_shared_exponent`). They read the layout's colors, their textures' formats, samples,
/// shadows and image plans, and the device's driver facts; all but the
/// layout are fixed at creation, so an encoder decides them once for each layout it records
/// under.
#[derive(Debug, Default, PartialEq)]
pub(super) struct KeptAttachments {
pub(super) unused_bits: Vec<String>,
pub(super) snorm_minimum: Vec<String>,
pub(super) shared_exponent: Vec<String>,
}
impl KeptAttachments {
/// The kept attachments of `layout`, a pass of `device`'s.
pub(super) fn of(layout: &PassLayout, device: &Device) -> Self {
let metals = metals_store(device);
let mut kept = Self::default();
for (index, color) in layout.colors.iter().enumerate() {
let Some(color) = color else {
continue;
};
let name = || format!("color {index}, {:?}", color.target.texture.pixel_format());
if untaken(color) {
kept.unused_bits.push(name());
}
if !metals && snorm_minimum_kept(color) {
kept.snorm_minimum.push(name());
}
if !metals && shared_exponent_kept(color) {
kept.shared_exponent.push(name());
}
}
kept
}
}
/// The texels of one attachment's region: its columns, the rows of each layer, its layers, and
/// the bytes of a texel and of each row in the scratch (the texels', then any padding to a
/// word).
#[derive(Clone, Copy)]
struct Region {
columns: u64,
rows: u64,
layers: u64,
texel: u64,
stride: u64,
}
impl Region {
/// The bytes of each row's texels.
fn row_bytes(&self) -> u64 {
self.columns * self.texel
}
}
/// One band of a region's rows: its first row (counted across the layers) and its rows.
#[derive(Clone, Copy)]
struct Band {
first_row: u64,
rows: u64,
}
/// Record, into `core` before the pass of `layout` whose store actions are settled, the load
/// pass of each color attachment it takes over the tiles of `reach` (the module docs), but for a
/// rotated texture's frame ([`record_frames`]), and announce `unreached-tiles-rewritten` where
/// `reach` is not Metal's, naming every attachment either rewrites. The caller calls it only for
/// a pass that recorded a draw call or an execution of render commands, whose draws reach a
/// tile.
pub(super) fn record(
core: &mut EncoderCore,
layout: &PassLayout,
reach: TileReach<'_>,
) -> Result<(), Error> {
let rewritten: Vec<String> = layout
.colors
.iter()
.enumerate()
.filter_map(|(index, color)| {
let taken = takes(color.as_ref()?, false)?;
let format = taken.target.texture.pixel_format();
Some(format!("color {index}, {format:?}"))
})
.collect();
record_taken(core, layout, reach, false)?;
if !rewritten.is_empty() && !reach.exact() {
core.device()
.degrade(Degradation::UnreachedTilesRewritten, || {
(
format!(
"a render pass that loads {} and draws",
rewritten.join(" and ")
),
"the pass rewrites every 32x32 tile of its render area, where Metal's \
rewrites only the tiles a draw's primitives reach (or every tile where a \
color attachment is cleared): in tiles no draw reaches the unused bits are \
made canonical and BGRA10_XR alpha codes clamped to [384, 894], a padded \
word's low six bits zeroed (an _sRGB twin's code through Metal's table) and \
a bfloat code moved through half, where Metal keeps those texels' bytes"
.to_owned(),
)
});
}
Ok(())
}
/// Record, into `core` right after the shadows' copies in of the pass of `layout` (and before
/// its stand-ins' copies and clears), the load pass of each rotated texture's frame it takes over
/// the tiles of `reach` (the module docs). [`record`] announces them. The caller calls it only
/// for a pass that recorded a draw call or an execution of render commands, whose draws reach a
/// tile.
pub(super) fn record_frames(
core: &mut EncoderCore,
layout: &PassLayout,
reach: TileReach<'_>,
) -> Result<(), Error> {
record_taken(core, layout, reach, true)
}
/// Record the load pass of each color attachment of `layout` taken from a rotated texture's
/// frame (`frames`), or of each other one taken.
fn record_taken(
core: &mut EncoderCore,
layout: &PassLayout,
reach: TileReach<'_>,
frames: bool,
) -> Result<(), Error> {
for color in layout.colors.iter().flatten() {
let Some(taken) = takes(color, false) else {
continue;
};
if matches!(taken.source, Source::Frame) != frames {
continue;
}
let target = taken.target;
let [width, height] = target.extent;
let words = match taken.source {
Source::Bytes(_, words) => words,
Source::Image | Source::Frame => TexelWords::Raw,
};
let texel = UnusedBitsModule::texel_bytes(taken.format, words)
.ok_or_else(|| internal("an unused bits attachment without its words"))?;
let columns = u64::from(layout.extent[0].next_multiple_of(TILE).min(width));
let rows = u64::from(layout.extent[1].next_multiple_of(TILE).min(height));
let texel = u64::from(texel);
let region = Region {
columns,
rows,
layers: u64::from(target.layers),
texel,
stride: (columns * texel).next_multiple_of(4),
};
if columns == 0 || rows == 0 || region.layers == 0 {
continue;
}
rewrite(core, &taken, words, region, reach)?;
core.device()
.shared()
.counts
.unused_bits_load_recorded(columns * rows * region.layers);
}
Ok(())
}
/// Rewrite the words of `taken`'s `region`, held as `words`, in the tiles of `reach`, as Metal's
/// tile store leaves them.
fn rewrite(
core: &mut EncoderCore,
taken: &Taken<'_>,
words: TexelWords,
region: Region,
reach: TileReach<'_>,
) -> Result<(), Error> {
let device = core.device().clone();
let limits = &device.properties().description.limits;
// A storage buffer's binding offset, and an image copy's buffer offset (a texel's bytes).
let align = limits.min_storage_buffer_offset_alignment.max(8);
let per_dispatch =
u64::from(UnusedBitsModule::LOCAL_SIZE) * u64::from(limits.max_compute_work_group_count[0]);
let most = MAX_SCRATCH
.min(u64::from(limits.max_storage_buffer_range))
.min(4 * per_dispatch);
let all_rows = region.rows * region.layers;
let band_rows = (most / region.stride).min(all_rows);
if band_rows == 0 {
return Err(internal("an unused bits row past a storage buffer's range"));
}
let bands: Vec<Band> = (0..all_rows)
.step_by(band_rows as usize)
.map(|first_row| Band {
first_row,
rows: band_rows.min(all_rows - first_row),
})
.collect();
let tiles_per_row = region.columns.div_ceil(u64::from(TILE));
let tiles = region.layers * region.rows.div_ceil(u64::from(TILE)) * tiles_per_row;
let mask_bytes = 4 * tiles.div_ceil(32);
let tile_rows = region.rows.div_ceil(u64::from(TILE));
let mask = reach.mask(tiles_per_row, tile_rows, (region.layers, mask_bytes))?;
let narrow = |v: u64| u32::try_from(v).map_err(|_| internal("an unused bits region past u32"));
let shapes: Vec<[u8; 16]> = bands
.iter()
.map(|band| {
Ok(UnusedBitsModule::shape(
narrow(region.stride / 4)?,
narrow(band.first_row)?,
narrow(region.rows)?,
narrow(tiles_per_row)?,
))
})
.collect::<Result<_, Error>>()?;
// The scratch: a band's rows, the mask, then each band's shape.
let words_bytes = (band_rows * region.stride).next_multiple_of(align);
let mask_at = words_bytes;
let shapes_at = mask_at + mask_bytes.next_multiple_of(align);
let slot = 16u64.next_multiple_of(align);
let scratch_bytes = shapes_at + slot * bands.len() as u64;
let scratch = device.own_buffer(scratch_bytes, ResourceOptions::private())?;
let (raw_scratch, at) = scratch.at(0);
if !at.is_multiple_of(align) {
return Err(internal("an unused bits scratch off its alignment"));
}
let kernel = device.owned_kernel(OwnedModule::UnusedBits(taken.format, words))?;
let ranges: Vec<_> = bands
.iter()
.enumerate()
.map(|(b, band)| {
vec![
(raw_scratch, at, band.rows * region.stride),
(raw_scratch, at + mask_at, mask_bytes),
(raw_scratch, at + shapes_at + slot * b as u64, 16),
]
})
.collect();
let sets = OwnedSets::write(&device, &kernel, &ranges)?;
let groups: Vec<u32> = bands
.iter()
.map(|band| {
narrow(
(band.rows * region.stride / 4).div_ceil(u64::from(UnusedBitsModule::LOCAL_SIZE)),
)
})
.collect::<Result<_, Error>>()?;
let access = Access::new(
vk::PipelineStageFlags2::TRANSFER,
vk::AccessFlags2::TRANSFER_READ | vk::AccessFlags2::TRANSFER_WRITE,
);
let target = taken.target;
let (copies, uses) = match taken.source {
Source::Bytes(texels, _) => {
let layout = &texels.layout;
let (raw_buffer, base) = texels.buffer.at(layout.offset);
let row_bytes = region.row_bytes();
let copies: Vec<Vec<vk::BufferCopy>> = bands
.iter()
.map(|band| {
(0..band.rows)
.map(|row| vk::BufferCopy {
src_offset: base + (band.first_row + row) * layout.row_pitch,
dst_offset: at + row * region.stride,
size: row_bytes,
})
.collect()
})
.collect();
let span =
layout.offset..layout.offset + (region.rows - 1) * layout.row_pitch + row_bytes;
let (identity, range) = texels.buffer.tracked(span);
let uses = vec![Use::writes(
identity.key,
identity.tracked,
UseRange::Bytes(range),
access,
)];
core.retain(texels.buffer.clone());
(Copies::Bytes(raw_buffer, copies), uses)
}
Source::Image | Source::Frame => {
let texture = &target.texture;
let image = texture.raw_image()?;
let deep = texture.image_plan()?.image_type == ImageType::TYPE_3D;
let regions: Vec<Vec<vk::BufferImageCopy>> = bands
.iter()
.map(|band| image_regions(target, region, *band, at, deep))
.collect();
let level = target.level..target.level + 1;
let layers = target.layer..target.layer + target.layers;
let uses = vec![texture.image_use(level, layers, access, true)?];
core.retain(texture.clone());
(Copies::Image(image, regions), uses)
}
};
let descriptor_sets = sets.sets.clone();
let stages = vk::PipelineStageFlags2::TRANSFER | vk::PipelineStageFlags2::COMPUTE_SHADER;
core.command(stages, &uses, |raw, command_buffer| {
// SAFETY: the command buffer is recording outside a render pass (the pass records after
// it), and only the encoder records it; the texels' buffer or image, the scratch and the
// sets are retained until it completes; every copy lies inside the texels (the target's
// rows, its level and layers) and the scratch (a band's rows), and every binding inside
// the scratch; each step reads what the one before it wrote past a barrier, and the
// scratch's rows are written again only past a barrier after the band before is done
// with them. The image rests in `GENERAL`.
unsafe {
Barrier::everything().record(raw, command_buffer);
record_mask(
raw,
command_buffer,
(raw_scratch, at + mask_at, mask_bytes),
&mask,
);
for (b, shape) in shapes.iter().enumerate() {
let offset = at + shapes_at + slot * b as u64;
raw.cmd_update_buffer(command_buffer, raw_scratch, offset, shape);
}
raw.cmd_bind_pipeline(
command_buffer,
vk::PipelineBindPoint::COMPUTE,
kernel.pipeline,
);
for (b, (set, groups)) in descriptor_sets.iter().zip(&groups).enumerate() {
Barrier::everything().record(raw, command_buffer);
copies.to_scratch(raw, command_buffer, raw_scratch, b);
Barrier::everything().record(raw, command_buffer);
raw.cmd_bind_descriptor_sets(
command_buffer,
vk::PipelineBindPoint::COMPUTE,
kernel.layout,
0,
std::slice::from_ref(set),
&[],
);
raw.cmd_dispatch(command_buffer, *groups, 1, 1);
Barrier::everything().record(raw, command_buffer);
copies.back(raw, command_buffer, raw_scratch, b);
}
Barrier::everything().record(raw, command_buffer);
}
});
core.retain(scratch);
core.retain(sets);
Ok(())
}
/// Each band's copies between the texels and the scratch, into it (and back, swapped).
enum Copies {
/// Each row of a buffer's bytes.
Bytes(vk::Buffer, Vec<Vec<vk::BufferCopy>>),
/// Each layer's rows of an image's level.
Image(vk::Image, Vec<Vec<vk::BufferImageCopy>>),
}
impl Copies {
/// Record band `b`'s copy into `scratch`.
///
/// # Safety
///
/// `command_buffer` is recording, outside a render pass; the copies lie in their resources,
/// which are live until it completes, and an image rests in `GENERAL`.
unsafe fn to_scratch(
&self,
raw: &Vk,
command_buffer: vk::CommandBuffer,
scratch: vk::Buffer,
b: usize,
) {
// SAFETY: the caller's contract.
unsafe {
match self {
Copies::Bytes(buffer, copies) => {
raw.cmd_copy_buffer(command_buffer, *buffer, scratch, &copies[b])
}
Copies::Image(image, regions) => raw.cmd_copy_image_to_buffer(
command_buffer,
*image,
vk::ImageLayout::GENERAL,
scratch,
&regions[b],
),
}
}
}
/// Record band `b`'s copy back from `scratch`.
///
/// # Safety
///
/// As [`to_scratch`](Self::to_scratch).
unsafe fn back(
&self,
raw: &Vk,
command_buffer: vk::CommandBuffer,
scratch: vk::Buffer,
b: usize,
) {
// SAFETY: the caller's contract.
unsafe {
match self {
Copies::Bytes(buffer, copies) => {
let back: Vec<vk::BufferCopy> = copies[b]
.iter()
.map(|c| vk::BufferCopy {
src_offset: c.dst_offset,
dst_offset: c.src_offset,
size: c.size,
})
.collect();
raw.cmd_copy_buffer(command_buffer, scratch, *buffer, &back)
}
Copies::Image(image, regions) => raw.cmd_copy_buffer_to_image(
command_buffer,
scratch,
*image,
vk::ImageLayout::GENERAL,
&regions[b],
),
}
}
}
}
/// The copies between `target`'s level and the scratch at `at` of `band`'s rows of `region`:
/// one per layer the band meets, a 3D image's depth planes (`deep`) by its z offset, another's
/// array layers by its layer.
fn image_regions(
target: &Target,
region: Region,
band: Band,
at: u64,
deep: bool,
) -> Vec<vk::BufferImageCopy> {
let mut regions = Vec::new();
let mut row = band.first_row;
let end = band.first_row + band.rows;
while row < end {
let layer = row / region.rows;
let y = row % region.rows;
let rows = (region.rows - y).min(end - row);
let layer = target.layer + layer as u32;
let (base_array_layer, z) = match deep {
true => (0, layer as i32),
false => (layer, 0),
};
regions.push(vk::BufferImageCopy {
buffer_offset: at + (row - band.first_row) * region.stride,
buffer_row_length: 0,
buffer_image_height: 0,
image_subresource: vk::ImageSubresourceLayers {
aspect_mask: vk::ImageAspectFlags::COLOR,
mip_level: target.level,
base_array_layer,
layer_count: 1,
},
image_offset: vk::Offset3D {
x: 0,
y: y as i32,
z,
},
image_extent: vk::Extent3D {
width: region.columns as u32,
height: rows as u32,
depth: 1,
},
});
row += rows;
}
regions
}
+32 -146
View File
@@ -106,7 +106,7 @@ use super::render_values::{ScissorRect, Viewport};
use super::Device;
use ash::vk;
use metal2vulkan::bind::{CompensatedViewport, RegionLimits};
use metal2vulkan::device::{DeviceProfile, EnableSet, VkExtension, VkFeature};
use metal2vulkan::device::{DeviceProfile, VkExtension, VkFeature};
use metal2vulkan::error::{Capability, Feature, RuntimeDriverDefect, Unsupported};
use metal2vulkan::metal::{
CullMode, DepthClipMode, PixelFormat, StencilOperation, TriangleFillMode, Winding,
@@ -786,7 +786,7 @@ impl EncoderState {
topology: metal2vulkan::vk::PrimitiveTopology,
profile: &DeviceProfile,
) -> Result<Option<DepthBiasEffect>, Error> {
let biased = metal2vulkan::metal::state::depth_bias(topology, 0.0, 0.0, 0.0, None, profile)
let biased = metal2vulkan::metal::state::depth_bias(topology, 0.0, 0.0, 0.0, profile)
.map_err(device_error)?
.enable;
Ok(biased.then_some(self.depth_bias))
@@ -797,32 +797,6 @@ impl EncoderState {
&self.scissors[0]
}
/// The cull mode.
pub(super) fn cull_mode(&self) -> CullMode {
self.cull_mode
}
/// The state the tile reach rule bins a draw's primitives under
/// (`bind::TileReachModule::state`), for a draw of a pipeline that selects no viewport: the
/// first viewport as the rasterizer takes it (in `f32`), the first scissor rectangle, the
/// cull mode, the winding and the depth clip mode. `None` under a fill mode other than
/// `Fill`, whose triangles draw as lines, and for a rectangle past `u32`.
pub(super) fn reach_state(&self) -> Option<[u8; 48]> {
if self.fill_mode != TriangleFillMode::Fill {
return None;
}
let v = self.viewports.first()?;
let s = self.scissors.first()?;
let side = |x: u64| u32::try_from(x).ok();
Some(metal2vulkan::bind::TileReachModule::state(
[v.origin_x, v.origin_y, v.width, v.height].map(|f| f as f32),
[side(s.x)?, side(s.y)?, side(s.width)?, side(s.height)?],
self.cull_mode.as_raw(),
self.winding.as_raw(),
self.clip_mode.as_raw(),
))
}
/// The powers of two `[sx, sy]` a draw of points widens the Vulkan viewports it uses by,
/// about their centers ([`EncoderState::vk_viewports`]), its vertex stage scaling the
/// position by their inverses and culling at Metal's guard band ([`guard_points`]): on each
@@ -1082,15 +1056,12 @@ impl EncoderState {
Ok([first.znear as f32, first.zfar as f32])
}
/// The draw's depth bias for `topology` in a pass whose depth attachment's texture is of
/// `depth_format` (`metal::state::depth_bias`): a clamp needs `depthBiasClamp`, and a
/// `Depth16Unorm` depth's constant counts Metal's unit where the device pins Vulkan's. A
/// saturated bias or an offset biases nothing here: the draw's viewports take it
/// ([`EncoderState::draw_viewports`]).
/// The draw's depth bias for `topology` (`metal::state::depth_bias`): a clamp needs
/// `depthBiasClamp`, and the constant counts the device's unit. A saturated bias or an offset
/// biases nothing here: the draw's viewports take it ([`EncoderState::draw_viewports`]).
pub(super) fn vk_depth_bias(
&self,
topology: metal2vulkan::vk::PrimitiveTopology,
depth_format: Option<PixelFormat>,
profile: &DeviceProfile,
) -> Result<metal2vulkan::metal::state::DepthBias, Error> {
let [bias, slope, clamp] = match self.depth_bias {
@@ -1101,7 +1072,7 @@ impl EncoderState {
} => [constant, slope, clamp],
DepthBiasEffect::Saturated { .. } | DepthBiasEffect::Offset(_) => [0.0; 3],
};
metal2vulkan::metal::state::depth_bias(topology, bias, slope, clamp, depth_format, profile)
metal2vulkan::metal::state::depth_bias(topology, bias, slope, clamp, profile)
.map_err(device_error)
}
@@ -1874,7 +1845,7 @@ pub(super) fn written_depth_clamp(
);
}
let profile = device.compile_device().profile();
let biased = metal2vulkan::metal::state::depth_bias(topology, 0.0, 0.0, 0.0, None, profile)
let biased = metal2vulkan::metal::state::depth_bias(topology, 0.0, 0.0, 0.0, profile)
.map_err(device_error)?
.enable;
if biased && !matches!(state.depth_bias, DepthBiasEffect::Factors { .. }) {
@@ -1950,20 +1921,19 @@ fn clamp_range(viewport: &Viewport) -> [f32; 2] {
}
/// Announce once what a draw of `depth_stencil` stores in a `Depth16Unorm` depth
/// (`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).
/// (`depth_format`) under the Vulkan bias `bias`: the device biases and 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`, adds the bias to
/// the depth rounded toward zero, and stores the sum rounded to nearest, a tie up (probes); the
/// device biases by `c` of its own unit (`metal::state::depth_bias`).
pub(super) fn announce_unorm_depth(
device: &Device,
depth_format: Option<PixelFormat>,
depth_stencil: &metal2vulkan::metal::state::DepthStencilState,
bias: &metal2vulkan::metal::state::DepthBias,
) {
use metal2vulkan::metal::state::DepthBiasUnit;
if depth_format != Some(PixelFormat::Depth16Unorm) {
return;
}
@@ -1991,107 +1961,43 @@ pub(super) fn announce_unorm_depth(
let object = "a draw biasing a Depth16Unorm depth by a constant, or by a slope that \
brings Metal's constant unit"
.to_owned();
let reason = match bias.unit {
DepthBiasUnit::Device => "the device lacks VK_EXT_depth_bias_control's \
depthBiasExact, so the bias counts its own unit, up to \
twice 2^-16, where Metal's is c + 1 units of 1/65535 for c \
of 0 or more (a slope alone brings one) and c - 1 below"
.to_owned(),
_ => "the device adds Metal's bias to the depth and converts the sum in its own \
rounding, where Metal adds it rounding toward zero: a biased depth near a \
code's midpoint can store the code next to Metal's"
.to_owned(),
};
let reason = "the device biases by the constant c in its own unit, up to twice 2^-16 \
(none for a slope alone), and converts the sum in its own rounding, where \
Metal biases by c + 1 units of 1/65535 for c of 0 or more (a slope alone \
brings one) and c - 1 below, adding them rounding toward zero: a biased \
depth can store another code than Metal's"
.to_owned();
(object, reason)
});
}
/// `vkCmdSetDepthBias2EXT` (`VK_EXT_depth_bias_control`): records a depth bias whose constant
/// factor counts the unit a chained `VkDepthBiasRepresentationInfoEXT` names.
pub(super) type DepthBiasCommand = vk::PFN_vkCmdSetDepthBias2EXT;
/// The device's [`DepthBiasCommand`], where it enabled `VK_EXT_depth_bias_control`.
///
/// # Safety
///
/// `device` was made from `instance` with `enabled` enabled, and the loader serves
/// `vkGetDeviceProcAddr` for it (its loader word is in place).
pub(super) unsafe fn depth_bias_command(
instance: &ash::Instance,
device: &ash::Device,
enabled: &EnableSet,
) -> Option<DepthBiasCommand> {
if !enabled
.extensions
.contains(&VkExtension::ExtDepthBiasControl)
{
return None;
}
// SAFETY: the caller's; a command the device does not have is null.
let command = unsafe {
instance.get_device_proc_addr(device.handle(), c"vkCmdSetDepthBias2EXT".as_ptr())
}?;
// SAFETY: the device gave the command of this name.
Some(unsafe { std::mem::transmute::<unsafe extern "system" fn(), DepthBiasCommand>(command) })
}
/// What a depth bias command sets, as the command carries it: the factors' bits and a pinned
/// unit's representation. Two records set the same state where theirs are equal. It keeps no
/// command, so what keeps it keeps none of the device's functions.
/// What a depth bias command sets: the factors' bits. Two records set the same state where
/// theirs are equal.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) struct DepthBiasSetting {
factors: [u32; 3],
representation: Option<vk::DepthBiasRepresentationEXT>,
}
/// How a draw records its depth bias ([`metal2vulkan::metal::state::DepthBias`]).
/// How a draw records its depth bias ([`metal2vulkan::metal::state::DepthBias`]):
/// `vkCmdSetDepthBias` of its factors.
#[derive(Clone, Copy, PartialEq)]
pub(super) struct DepthBiasRecord {
/// Constant factor, clamp, slope factor.
factors: [f32; 3],
/// The command and the representation of a pinned unit (`DepthBiasUnit::Depth` or
/// `ExactFormatUnit`); `None`: `vkCmdSetDepthBias`, the device's unit.
pinned: Option<(DepthBiasCommand, vk::DepthBiasRepresentationEXT)>,
}
impl DepthBiasRecord {
/// How `bias` records on a device whose depth bias command is `command`: a pinned unit on a
/// device without the command is an internal error, since `metal::state::depth_bias` pins
/// one only where the device enabled the extension's `depthBiasExact`.
pub(super) fn of(
bias: &metal2vulkan::metal::state::DepthBias,
command: Option<DepthBiasCommand>,
) -> Result<DepthBiasRecord, Error> {
use metal2vulkan::metal::state::DepthBiasUnit;
let representation = match bias.unit {
DepthBiasUnit::Device => None,
DepthBiasUnit::Depth => Some(vk::DepthBiasRepresentationEXT::FLOAT),
DepthBiasUnit::ExactFormatUnit => {
Some(vk::DepthBiasRepresentationEXT::LEAST_REPRESENTABLE_VALUE_FORMAT)
}
unit => return Err(internal(&format!("a depth bias unit of {unit:?}"))),
};
let pinned = match (representation, command) {
(None, _) => None,
(Some(representation), Some(command)) => Some((command, representation)),
(Some(_), None) => {
return Err(internal(
"a pinned depth bias unit on a device without vkCmdSetDepthBias2EXT",
))
}
};
Ok(DepthBiasRecord {
/// How `bias` records.
pub(super) fn of(bias: &metal2vulkan::metal::state::DepthBias) -> DepthBiasRecord {
DepthBiasRecord {
factors: [bias.constant_factor, bias.clamp, bias.slope_factor],
pinned,
})
}
}
/// What recording it sets: its factors, bit for bit, in its representation, without the
/// command (the device's, the same for every record of the device).
/// What recording it sets: its factors, bit for bit.
pub(super) fn setting(&self) -> DepthBiasSetting {
DepthBiasSetting {
factors: self.factors.map(f32::to_bits),
representation: self.pinned.map(|(_, representation)| representation),
}
}
@@ -2103,26 +2009,8 @@ impl DepthBiasRecord {
/// dynamic state.
pub(super) unsafe fn record(&self, raw: &ash::Device, command_buffer: vk::CommandBuffer) {
let [constant, clamp, slope] = self.factors;
match self.pinned {
None => {
// SAFETY: the caller's.
unsafe { raw.cmd_set_depth_bias(command_buffer, constant, clamp, slope) }
}
Some((command, representation)) => {
let mut exact = vk::DepthBiasRepresentationInfoEXT::default()
.depth_bias_representation(representation)
.depth_bias_exact(true);
let info = vk::DepthBiasInfoEXT::default()
.depth_bias_constant_factor(constant)
.depth_bias_clamp(clamp)
.depth_bias_slope_factor(slope)
.push_next(&mut exact);
// SAFETY: the caller's; the device enabled the extension the command is of,
// and `depthBiasExact` and, for the float representation, `floatRepresentation`,
// which `metal::state::depth_bias` pinned the unit for.
unsafe { command(command_buffer, &info) }
}
}
// SAFETY: the caller's.
unsafe { raw.cmd_set_depth_bias(command_buffer, constant, clamp, slope) }
}
}
@@ -3303,9 +3191,7 @@ mod tests {
gap,
"an offset in clamp mode"
);
let bias = state
.vk_depth_bias(T::TRIANGLE_LIST, Some(PixelFormat::Depth16Unorm), profile)
.unwrap();
let bias = state.vk_depth_bias(T::TRIANGLE_LIST, profile).unwrap();
assert_eq!(
[bias.constant_factor, bias.slope_factor, bias.clamp],
[0.0; 3],
@@ -2047,16 +2047,6 @@ pub(super) fn framebuffer_over(
Ok(made)
}
/// The framebuffer of `pass`, a pass without attachments (`attachmentless.rs`), over `extent`
/// and one layer: capture replay's (`render/capture.rs`).
pub(super) fn attachmentless_framebuffer(
device: &Device,
pass: &RenderPassObject,
extent: [u32; 2],
) -> Result<FramebufferObject, Error> {
made_framebuffer(device, pass, &[], extent, 1)
}
/// The framebuffer of `pass` with `attachments`, over `extent` and `layers`: each view of one
/// level and of those layers, or of the views of a multiview pass's one layer, at least `extent`
/// large.
@@ -1,12 +1,11 @@
//! A state's draws build **no** descriptor key, and its capture forms build one between them
//! (`descriptor_keys_built`): the key of the descriptor a compile is keyed by belongs to that
//! descriptor, and the state holds one per descriptor it compiles as.
//! A state's draws build **no** descriptor key (`descriptor_keys_built`): the key of the
//! descriptor a compile is keyed by belongs to that descriptor, and the state holds one per
//! descriptor it compiles as.
//!
//! The creation's half of this is `descriptor_key_once.rs`, which this continues: a creation
//! builds the key of its descriptor once and the state keeps it. What was left there is the
//! draw's half -- a variant a draw of another bind shape needs, and a capture form a replay
//! needs, each compiled under a key built at the draw: the same digest of the same fixed
//! descriptor, built again for every variant and every form.
//! draw's half -- a variant a draw of another bind shape needs, compiled under a key built at the
//! draw: the same digest of the same fixed descriptor, built again for every variant.
//!
//! # Which descriptor keys which compile
//!
@@ -17,9 +16,7 @@
//! * the descriptor it draws as (`GraphicsState::descriptor_key`), which for a twin of a color
//! group holds its group's color attachments alone and clears
//! `supportIndirectCommandBuffers` -- fields the key reads, so the twin's two descriptors are
//! two keys;
//! * the descriptor its capture forms compile from: the vertex stage alone, without the fragment
//! function or any attachment format.
//! two keys.
//!
//! Each key stays with its own descriptor. Keying a compile by a descriptor it does not compile
//! would look its pipeline up among another descriptor's entries in the shader cache, which
@@ -43,9 +40,8 @@ use super::descriptor_key_once::{built, descriptor};
use crate::pipeline::{BufferForms, GraphicsState, RenderStateKind};
use crate::{PipelineOptions, RenderPipelineState};
use metal2vulkan::bind::BindShape;
use metal2vulkan::cache::VariantKey;
use metal2vulkan::metal::{IndexType, PixelFormat};
use metal2vulkan::pipeline::{CaptureForm, ColorAttachmentDescriptor, RenderPipelineDescriptor};
use metal2vulkan::metal::PixelFormat;
use metal2vulkan::pipeline::ColorAttachmentDescriptor;
use std::collections::BTreeSet;
use std::sync::Arc;
@@ -57,21 +53,6 @@ fn graphics(state: &RenderPipelineState) -> &GraphicsState {
}
}
/// `descriptor` as a state's capture forms compile it, as `pipeline::render`'s own
/// `capture_descriptor` makes it: the vertex stage alone, rasterizing into a pass without
/// attachments. Written here from the descriptor, so the key the state holds is held to the key
/// of a descriptor this test built, not to one the product handed it.
fn captured(descriptor: &RenderPipelineDescriptor) -> RenderPipelineDescriptor {
let mut descriptor = descriptor.clone();
descriptor.fragment = None;
descriptor.color_attachments = Default::default();
descriptor.depth_format = None;
descriptor.stencil_format = None;
descriptor.alpha_to_coverage = false;
descriptor.alpha_to_one = false;
descriptor
}
/// The variant a draw of another bind shape needs is compiled under the key the state's creation
/// built: the draw builds none, and a later draw of the shape finds the variant and builds none
/// either. A pass without the pipeline's color attachment, whose writes Metal drops
@@ -154,55 +135,6 @@ fn a_states_compile_key_is_its_descriptors() {
);
}
/// Every capture form of every variant of one state compiles from one descriptor, so the forms
/// build one key between them: the first builds it, each later one takes it. The key is the key
/// of that descriptor, which is not the state's own.
#[test]
fn capture_forms_of_one_state_build_one_descriptor_key() {
let scratch = Scratch::new("descriptor-key-capture");
let device = device(&scratch.0);
let descriptor = descriptor(&device);
let state = device
.new_render_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap();
let state = graphics(&state);
let shape = BindShape::default();
let settled = VariantKey::default();
let before = built(&device);
// Three forms of the one variant: a replay of a draw of primitives, and of an indexed draw
// of each index type (`render/capture.rs`). Each asks for a compile of its own; a form is
// `None` while its translation runs, which is what every first ask answers.
for form in [
CaptureForm::Vertices,
CaptureForm::Indexed(IndexType::UInt16),
CaptureForm::Indexed(IndexType::UInt32),
] {
let _ = state.capture_variant(&settled, form, &shape);
}
assert_eq!(
built(&device)[0] - before[0],
1,
"descriptor keys three capture forms of one state built"
);
let capture = captured(&descriptor);
let held = *state.capture_key(&capture);
assert_eq!(
built(&device)[0] - before[0],
1,
"descriptor keys a read of the held capture key built"
);
assert_eq!(
held,
device.compile_device().render_descriptor_key(&capture),
"the key the forms were compiled under is the key of the descriptor they compile from"
);
assert_ne!(
held,
*state.descriptor_key(),
"a capture form's descriptor is not the state's: its key may not be the state's"
);
}
/// The two descriptors a twin of a color group holds are keyed apart: the descriptor it was made
/// from, which its variants compile from, and the group's color attachments alone, which it draws
/// as and answers questions of. A compile keyed by the second would be looked up among the
@@ -1649,7 +1649,7 @@ fn the_device_s_functions_are_reached_through_checked_accessors() {
/// tuple field, a type argument or a by-value parameter) fails
/// `only_the_listed_modules_keep_the_device_s_functions`; so does a listed module that keeps none
/// any more.
const KEEPERS: [(&str, &str); 24] = [
const KEEPERS: [(&str, &str); 23] = [
(
"binding.rs",
"the push command (vkCmdPushDescriptorSet), a call's parameter (`push_set`) and the \
@@ -1738,10 +1738,6 @@ const KEEPERS: [(&str, &str); 24] = [
"render/pending.rs",
"a pending draw's recording, held by its command buffer",
),
(
"render_state.rs",
"a draw's recording (vkCmd*), held by what holds its command buffer",
),
(
"scheduler/mod.rs",
"the scheduler's nudge, signalled and waited for only while its thread waits on the \
@@ -2084,10 +2080,10 @@ fn the_table_names_each_entry_point_once() {
#[test]
fn the_priming_check_names_what_was_not_made() {
use crate::device::prime::{
missing, Has, CALIBRATION_CALLS, COLOR_WRITE_MASK_CALLS, DEPTH_BIAS_CALLS,
DEVICE_ADDRESS_CALLS, EXTENDED_DYNAMIC_STATE_CALLS, GENERATED_COMMANDS_CALLS,
HOST_QUERY_RESET_CALLS, NAMING_CALLS, PRIMITIVE_RESTART_CALLS, PUSH_DESCRIPTOR_CALLS,
SIZED_INDEX_BIND_CALLS, SPARSE_CALLS, TIMESTAMP_CALLS, UNPRIMED, YCBCR_CONVERSION_CALLS,
missing, Has, CALIBRATION_CALLS, COLOR_WRITE_MASK_CALLS, DEVICE_ADDRESS_CALLS,
EXTENDED_DYNAMIC_STATE_CALLS, GENERATED_COMMANDS_CALLS, HOST_QUERY_RESET_CALLS,
NAMING_CALLS, PRIMITIVE_RESTART_CALLS, PUSH_DESCRIPTOR_CALLS, SIZED_INDEX_BIND_CALLS,
SPARSE_CALLS, TIMESTAMP_CALLS, UNPRIMED, YCBCR_CONVERSION_CALLS,
};
let has = |timestamps, device_addresses| Has {
timestamps,
@@ -2101,7 +2097,6 @@ fn the_priming_check_names_what_was_not_made() {
extended_dynamic_state: true,
primitive_restart: true,
color_write_masks: true,
depth_bias: true,
sized_index_bind: true,
ycbcr_conversion: true,
};
@@ -2200,7 +2195,7 @@ fn the_priming_check_names_what_was_not_made() {
assert!(missing(unnamed, without).is_empty());
assert_eq!(missing(unnamed, has(true, true)), NAMING_CALLS);
// Without a render encoder's command of an extension or of Vulkan 1.3, nor is that command.
let groups: [(&[Call], fn(Has) -> Has); 6] = [
let groups: [(&[Call], fn(Has) -> Has); 5] = [
(&EXTENDED_DYNAMIC_STATE_CALLS, |has| Has {
extended_dynamic_state: false,
..has
@@ -2213,10 +2208,6 @@ fn the_priming_check_names_what_was_not_made() {
color_write_masks: false,
..has
}),
(&DEPTH_BIAS_CALLS, |has| Has {
depth_bias: false,
..has
}),
(&SIZED_INDEX_BIND_CALLS, |has| Has {
sized_index_bind: false,
..has
@@ -92,7 +92,8 @@ fn a_regions_tail_reads_zero_over_a_dirty_chunk() {
FIRST_CHUNK_BYTES,
"the region is the whole chunk"
);
assert_eq!(region.read_bytes(), poison, "the poison was written");
let whole = region.read::<{ FIRST_CHUNK_BYTES as usize }>();
assert_eq!(whole.as_slice(), poison, "the poison was written");
}
until("the chunk was parked", || parked() > before_parked);
// The chunk comes back for the next arena of the same making, holding the poison.
@@ -103,7 +104,7 @@ fn a_regions_tail_reads_zero_over_a_dirty_chunk() {
.upload(&device, &data, 64)
.expect("a short region of a recycled chunk");
let cleared = device.work_counts().new_buffer_bytes_cleared - before;
let bytes = region.read_bytes();
let bytes = region.read::<64>();
assert_eq!(&bytes[..8], &data, "the region holds its data");
assert_eq!(
&bytes[8..],
-18
View File
@@ -358,22 +358,4 @@ impl Upload {
}
bytes
}
/// The region's bytes as the device left them, under [`read`](Self::read)'s contract.
pub(super) fn read_bytes(&self) -> Vec<u8> {
let Some(mapped) = self.buffer.contents() else {
unreachable!("upload chunks are Shared buffers")
};
let mut bytes = vec![0; self.len as usize];
// SAFETY: the region lies inside the mapping, and no command writes it any more (the
// caller's contract); the memory is host-coherent.
unsafe {
std::ptr::copy_nonoverlapping(
mapped.as_ptr().add(self.offset as usize),
bytes.as_mut_ptr(),
bytes.len(),
);
}
bytes
}
}
+4 -80
View File
@@ -103,14 +103,6 @@ pub(crate) struct Counters {
color_resolve_passes_made: AtomicU64,
color_resolve_passes_kept: AtomicU64,
ahead_nanos: AtomicU64,
unused_bits_load_passes: AtomicU64,
unused_bits_load_texels: AtomicU64,
capture_reach_passes: AtomicU64,
capture_reach_primitives: AtomicU64,
capture_reach_tiles_found: AtomicU64,
capture_reach_tiles_bound: AtomicU64,
capture_reach_bound_passes: AtomicU64,
capture_reach_narrower_passes: AtomicU64,
driver_diagnostics_withheld: AtomicU64,
stand_ins_made: AtomicU64,
stand_in_bytes: AtomicU64,
@@ -1128,36 +1120,6 @@ impl Counters {
.fetch_add(1, Ordering::Relaxed);
}
/// An encoder recorded the load pass of an extended-range or padded color attachment over a
/// region of `texels` texels (`render/unused_bits_load.rs`).
pub(crate) fn unused_bits_load_recorded(&self, texels: u64) {
self.unused_bits_load_passes.fetch_add(1, Ordering::Relaxed);
self.unused_bits_load_texels
.fetch_add(texels, Ordering::Relaxed);
}
/// An encoder recorded a pass's capture replay over `primitives` primitives
/// (`render/capture.rs`).
pub(crate) fn capture_reach_recorded(&self, primitives: u64) {
self.capture_reach_passes.fetch_add(1, Ordering::Relaxed);
self.capture_reach_primitives
.fetch_add(primitives, Ordering::Relaxed);
}
/// A captured pass's command buffer completed: its primitives reach `found` tiles, of the
/// `bound` its draws' viewports and scissors reach.
pub(crate) fn capture_reach_tallied(&self, found: u64, bound: u64) {
self.capture_reach_tiles_found
.fetch_add(found, Ordering::Relaxed);
self.capture_reach_tiles_bound
.fetch_add(bound, Ordering::Relaxed);
match found >= bound {
true => &self.capture_reach_bound_passes,
false => &self.capture_reach_narrower_passes,
}
.fetch_add(1, Ordering::Relaxed);
}
/// A driver call reported `withheld` diagnostics its driver facts measure it to report, which
/// the device's sink was not handed (`driver_facts.rs`).
pub(crate) fn driver_diagnostics_withheld(&self, withheld: u64) {
@@ -2830,8 +2792,8 @@ pub struct WorkCounts {
/// runtime thread held to make what the command buffer's work waited for had not gone yet.
pub trail_waits_blocked: u64,
/// Command buffers whose transition to `Completed` or `Error` ran on the queue waiter that
/// saw their work complete, with no handler thread woken: those with no completed handler, no
/// pass that captured its tiles' reach, and no earlier transition of their queue that runs
/// saw their work complete, with no handler thread woken: those with no completed handler and
/// no earlier transition of their queue that runs
/// the program's code or runs on a handler thread then, while the runtime held none of the
/// program's objects a release drops or runs (`command_buffer/completion.rs`).
pub completed_where_seen: u64,
@@ -3111,34 +3073,6 @@ pub struct WorkCounts {
/// Nanoseconds commits spent making ahead for their render passes' host steps, kept
/// backings included.
pub ahead_nanos: u64,
/// Load passes render encoders recorded: one per extended-range, padded 10-bit or bfloat
/// color attachment that a pass which draws loads and stores, whose words a dispatch rewrote in
/// the tiles the pass's draws reach before the pass, as Metal's tile store leaves them
/// (`render/unused_bits_load.rs`).
pub unused_bits_load_passes: u64,
/// The texels of those passes' regions (the render area rounded up to 32 texels a side,
/// within the texture, of every layer the pass renders).
pub unused_bits_load_texels: u64,
/// Passes whose draws' tile reach capture replay found before the pass, from the positions
/// their own vertex functions compute (`render/capture.rs`): the load pass rewrites the tiles
/// those reach, as Metal's pass does.
pub capture_reach_passes: u64,
/// The primitives those passes' capture draws assembled and binned.
pub capture_reach_primitives: u64,
/// The tiles those passes' primitives reach, as their masks held them once their command
/// buffers completed (every tile of the pass where its capture fell back, a primitive's
/// reach not measured): those the load passes rewrote.
pub capture_reach_tiles_found: u64,
/// The tiles their draws' viewports and scissors reach (`clear_reach::DrawnArea`): those the
/// load passes would rewrite without the capture.
pub capture_reach_tiles_bound: u64,
/// Those passes whose primitives reach every tile their viewports and scissors reach (a
/// full-screen draw's, say): the capture changed nothing the load pass rewrote, but for the
/// announcement.
pub capture_reach_bound_passes: u64,
/// Those passes whose primitives reach fewer: the tiles between were kept, as Metal keeps
/// them, where the load pass would have rewritten them.
pub capture_reach_narrower_passes: u64,
/// Driver diagnostics withheld from the device's message sink: messages a driver diagnostic
/// fact (`DriverFact::pipeline_creation_diagnostics`) measures the driver to report inside a
/// call the runtime made, reported there (`driver_facts.rs`). MoltenVK 1.4.1's warning of a
@@ -3648,8 +3582,8 @@ pub struct WorkCounts {
/// **Inside an encoder**, orders a blit's untracked uses by key and range).
pub command_barriers: u64,
/// Render pass instances a pass replaced or gave up before running them (a draw that needed
/// another shape before any draw recorded, a reroute's instance left behind, a capture that
/// recorded nothing, a first instance whose draws record inline instead), whose draws
/// another shape before any draw recorded, a reroute's instance left behind, a first instance
/// whose draws record inline instead), whose draws
/// recording the runtime gave up: never replayed where deferred (`recorder`), else ended, so
/// their command pool goes back to the device's spares unreset
/// (`WorkCounts::spare_command_pools_reset` counts the others). A pass's first instance that
@@ -4850,16 +4784,6 @@ impl Device {
color_resolve_passes_made: counters.color_resolve_passes_made.load(Ordering::Relaxed),
color_resolve_passes_kept: counters.color_resolve_passes_kept.load(Ordering::Relaxed),
ahead_nanos: counters.ahead_nanos.load(Ordering::Relaxed),
unused_bits_load_passes: counters.unused_bits_load_passes.load(Ordering::Relaxed),
unused_bits_load_texels: counters.unused_bits_load_texels.load(Ordering::Relaxed),
capture_reach_passes: counters.capture_reach_passes.load(Ordering::Relaxed),
capture_reach_primitives: counters.capture_reach_primitives.load(Ordering::Relaxed),
capture_reach_tiles_found: counters.capture_reach_tiles_found.load(Ordering::Relaxed),
capture_reach_tiles_bound: counters.capture_reach_tiles_bound.load(Ordering::Relaxed),
capture_reach_bound_passes: counters.capture_reach_bound_passes.load(Ordering::Relaxed),
capture_reach_narrower_passes: counters
.capture_reach_narrower_passes
.load(Ordering::Relaxed),
driver_diagnostics_withheld: counters
.driver_diagnostics_withheld
.load(Ordering::Relaxed),
+2 -2
View File
@@ -994,8 +994,8 @@ struct YCbCrLoad {
groups: [u32; 2],
}
/// The side of the tiles Metal loads and stores a render pass's attachment by
/// (`bind::tile_reach`): a pass that loads a two-plane YCbCr attachment stores every texel of
/// The side of the tiles Metal loads and stores a render pass's attachment by (32 x 32 on Apple's
/// GPUs): a pass that loads a two-plane YCbCr attachment stores every texel of
/// each tile it reaches, its codes re-encoded from what the tile loaded.
const TILE: u32 = 32;
File diff suppressed because it is too large. Load diff
@@ -1 +1 @@
5444426c46744d1bdcdb9fa83307a75b6b7d8d8775c91df28b9b53b4b8668816
3e69f4be31b028e09fc942e6bd99f1344af32d5748d3c0a31af90f77eb90fe71
@@ -1491,16 +1491,9 @@ fn pipeline(
constant,
slope,
clamp,
Some(metal2vulkan::metal::PixelFormat::Depth32Float),
profile,
)
.map_err(|error| format!("the product's depth bias: {error}"))?;
if bias.unit != metal2vulkan::metal::state::DepthBiasUnit::Device {
return Err(format!(
"a depth bias in {:?}, not the device's unit",
bias.unit
));
}
// The viewport's depth range, near and far, as specialization constants 0 and 1.
let range_entries = [
vk::SpecializationMapEntry {
@@ -281,10 +281,6 @@ mod cache;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod capabilities;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod capture_costs;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod capture_reach;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod chosen_pointers;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod chroma_pairs;
@@ -822,8 +818,6 @@ mod tile_normalized;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod tile_path_costs;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod tile_reach_kernel;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod tile_shadows;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
mod tile_states;
@@ -19,10 +19,10 @@
//! - **Loads.** A 256-texel-wide target holding every bfloat code once (each channel of each
//! texel the next code), through one pass that stores it: loaded with no draw, which keeps
//! every code; loaded under a full-screen draw that writes another attachment alone, which
//! rewrites every code through `half` (`ExtendedRange::load_code`: 56,829 codes move); with a
//! `DontCare` load under that draw, which stores zeros, or with no draw, which keeps every code;
//! and cleared to `(0.5, -2, 3e38, 1e-30)` under that draw. Metal's answer is the SHA-256 of
//! the target's bytes after the pass. The probe's bfloat target was its pass's color
//! rewrites every code through `half` (56,829 codes move), where the device's store keeps every
//! code (`extended-range-bits-kept`); with a `DontCare` load under that draw, which stores
//! zeros, or with no draw, which keeps every code; and cleared to `(0.5, -2, 3e38, 1e-30)` under
//! that draw. Metal's answer is the SHA-256 of the target's bytes after the pass. The probe's bfloat target was its pass's color
//! attachment 0 and the drawn one attachment 1; here they are swapped, since the owned fixture
//! `rt6_samples`'s fill writes color 0 (Metal's pass rewrites each loaded attachment of every
//! tile a draw reaches, whichever it writes).
@@ -610,11 +610,12 @@ fn load_case(lane: &Lane, pf: PixelFormat, channels: u64, case: Case) -> Vec<u8>
read_buffer(&back, 0, length).unwrap()
}
/// A pass over a bfloat target that holds every code leaves Metal's codes: a load keeps them
/// where nothing draws and takes them through `half` where a draw reaches their tiles, a
/// `DontCare` load under a draw stores zeros, and a clear under a draw stores the clear's.
/// A pass over a bfloat target that holds every code leaves the device's codes: a load keeps them
/// where nothing draws and where a draw reaches their tiles (the device's store, where Metal's
/// takes them through `half`: its digest is printed), a `DontCare` load under a draw stores
/// zeros, and a clear under a draw stores the clear's, Metal's codes.
#[test]
fn bfloat_load_passes_leave_metal_s_codes() {
fn bfloat_load_passes_leave_the_devices_codes() {
let (messages, _cache, lane) = lane();
let mut wrong = Vec::new();
for (pf, channels, _, cleared) in FORMATS {
@@ -626,14 +627,14 @@ fn bfloat_load_passes_leave_metal_s_codes() {
Case::DontCareKept,
Case::Cleared,
] {
// Metal's, but for a loaded target under a draw, whose codes the device's store keeps.
let metal = match case {
Case::Kept | Case::DontCareKept => EVERY_CODE,
Case::Loaded => LOADED,
Case::Kept | Case::DontCareKept | Case::Loaded => EVERY_CODE,
Case::DontCare => DONT_CARE,
Case::Cleared => cleared,
};
let got = load_case(&lane, pf, channels, case);
// The model's bytes: every code, its load code, zeros, or the clear's texel.
// The model's bytes: every code, zeros, or the clear's texel.
let model: Vec<u8> = got
.chunks(2)
.enumerate()
@@ -641,8 +642,7 @@ fn bfloat_load_passes_leave_metal_s_codes() {
let code = i as u32 & 0xffff;
let texel = form.clear_texel([0.5, -2.0, 3e38, 1e-30], ClearRoute::ThroughHalf);
let stored = match case {
Case::Kept | Case::DontCareKept => code,
Case::Loaded => form.load_code(code).expect("a bfloat code"),
Case::Kept | Case::DontCareKept | Case::Loaded => code,
Case::DontCare => 0,
Case::Cleared => texel[i % channels as usize],
};
@@ -650,6 +650,9 @@ fn bfloat_load_passes_leave_metal_s_codes() {
})
.collect();
assert_eq!(digest(&model), metal, "{pf:?} {case:?}: the model's");
if case == Case::Loaded {
println!("BFLOAT-TARGETS-KEPT {pf:?}: every code kept, Metal's {LOADED}");
}
if digest(&got) != metal {
let first = got
.chunks(2)
@@ -1,342 +0,0 @@
//! What capture replay (`render/capture.rs`) costs a pass, on the device the cfg selects, without
//! the validation layer.
//!
//! Each shape is a pass that loads and stores a `BGR10_XR` color attachment, under a pipeline of
//! the owned fixture `rch_vertex_math` (identity matrices: each position is the buffer's) whose
//! color's write mask is none of its channels, in two modes:
//!
//! - **exact**: the shape's draws, then a triangle off the target. Its capture replay is ready
//! (the shape runs until a pass announces nothing), so each pass draws its captures and bins
//! their primitives before it, and its load rewrites the tiles they reach.
//! - **every tile**: the shape's draws, then a line off the target, which no capture replays: the
//! pass rewrites every tile its scissors reach and announces `unreached-tiles-rewritten`.
//!
//! The shapes:
//!
//! - `cells`: a 384x256 target and two scissored cells (0, 0, 166, 166 and 166, 0, 166, 166) of
//! four small rects each, each rect an indexed (`uint16`) triangle list of 6 indices over its 4
//! vertices: an atlas pass of eight draws.
//! - `heavy`: a 1024x1024 target and four draws of 3 x 2^14 vertices (3 x 2^10 on a CPU ICD) of
//! zero-area triangles, as the `vertex_cost` lane spreads them: the capture shades each vertex
//! again.
//!
//! Each sample is one command buffer of [`PASSES`] passes of one mode, the modes alternating, 20
//! samples a mode after 3 warm ones (`CAPTURE-COST`, a pass's share of each): the host's time to
//! encode it, the command buffer's GPU time (MoltenVK's GPU times of a render pass are not the
//! pass's), and the host's time from the commit to the completion; medians and
//! fastest. Measures; asserts only that each mode took its path.
use super::degrade_notices::counts;
use super::{buffer_with, validated_device_with, Messages, ScratchCache, WAIT};
use crate::air_library::AirLibrary;
use crate::gpu::TEST_DEVICE;
use metal2vulkan::metal::{ColorWriteMask, IndexType, PixelFormat, PrimitiveType, TextureUsage};
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
use metal2vulkan_runtime::{
Buffer, CommandQueue, Degradation, Device, LoadAction, PipelineOptions, RenderCommandEncoder,
RenderPassDescriptor, RenderPipelineState, ResourceOptions, ScissorRect, StoreAction,
TextureDescriptor,
};
use std::time::{Duration, Instant};
/// The passes of each sample's command buffer.
const PASSES: usize = 16;
/// The kind a pass announces where its draws' tile reach is not captured.
const UNREACHED_TILES: Degradation = Degradation::UnreachedTilesRewritten;
/// The vertices of each `heavy` draw: 2^14 triangles on a GPU.
#[cfg(m2v_gpu)]
const HEAVY_VERTICES: u32 = 3 << 14;
/// The vertices of each `heavy` draw on a CPU ICD, which shades them on the CPU: 2^10 triangles.
#[cfg(not(m2v_gpu))]
const HEAVY_VERTICES: u32 = 3 << 10;
/// The `cells` shape's scissored cells.
const CELLS: [ScissorRect; 2] = [
ScissorRect {
x: 0,
y: 0,
width: 166,
height: 166,
},
ScissorRect {
x: 166,
y: 0,
width: 166,
height: 166,
},
];
/// A pass's tail draw: a triangle off the target (exact), or a line off it (every tile).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Mode {
Exact,
EveryTile,
}
/// One shape's target side, positions, indices, and draws.
struct Shape {
name: &'static str,
extent: [u64; 2],
positions: Vec<[f32; 4]>,
/// The `cells` rects' indices (a list of two triangles over 4 vertices), where it draws them.
indices: Option<Vec<u16>>,
}
/// The off-target vertices each shape's positions end in: a triangle's three, then a line's two.
const OFF: [[f32; 4]; 5] = [[-2.0, -2.0, 0.5, 1.0]; 5];
/// The clip-space position of window pixel `(x, y)` of a target of `extent` under Metal's default
/// viewport.
fn clip([w, h]: [u64; 2], x: f32, y: f32) -> [f32; 4] {
[2.0 * x / w as f32 - 1.0, 1.0 - 2.0 * y / h as f32, 0.5, 1.0]
}
/// The `cells` shape: four 24x24 rects in each cell, each from its own 4 vertices.
fn cells() -> Shape {
let extent = [384, 256];
let mut positions = Vec::new();
for cell in CELLS {
for r in 0..4u64 {
let x = (cell.x + 12 + 70 * (r % 2)) as f32;
let y = (cell.y + 12 + 70 * (r / 2)) as f32;
for (dx, dy) in [(0.0, 0.0), (24.0, 0.0), (0.0, 24.0), (24.0, 24.0)] {
positions.push(clip(extent, x + dx, y + dy));
}
}
}
positions.extend(OFF);
Shape {
name: "cells",
extent,
positions,
indices: Some(vec![0, 1, 2, 2, 1, 3]),
}
}
/// The `heavy` shape: triangle `k`'s three vertices at one point of the target, spread by a
/// multiplicative hash of `k`.
fn heavy() -> Shape {
let mut positions = Vec::with_capacity(HEAVY_VERTICES as usize + OFF.len());
for k in 0..HEAVY_VERTICES / 3 {
let h = k.wrapping_mul(2654435761);
let x = f32::from(h as u16) / 32767.5 - 1.0;
let y = f32::from((h >> 16) as u16) / 32767.5 - 1.0;
positions.extend([[x, y, 0.5, 1.0]; 3]);
}
positions.extend(OFF);
Shape {
name: "heavy",
extent: [1024, 1024],
positions,
indices: None,
}
}
/// The fixture's uniforms: identity model, view and projection matrices.
fn identity() -> Vec<u8> {
let one = |i: usize| (0..4).map(move |j| if i == j { 1.0f32 } else { 0.0 });
(0..3)
.flat_map(|_| (0..4).flat_map(one))
.flat_map(f32::to_le_bytes)
.collect()
}
/// A shape's objects on one device.
struct Bench {
queue: CommandQueue,
state: RenderPipelineState,
positions: Buffer,
uniforms: Buffer,
indices: Option<Buffer>,
pass: RenderPassDescriptor,
shape: Shape,
}
impl Bench {
fn new(device: &Device, state: &RenderPipelineState, shape: Shape) -> Bench {
let bytes: Vec<u8> = shape
.positions
.iter()
.flatten()
.flat_map(|v| v.to_le_bytes())
.collect();
let indices = shape.indices.as_ref().map(|indices| {
let bytes: Vec<u8> = indices.iter().flat_map(|i| i.to_le_bytes()).collect();
buffer_with(device, &bytes).unwrap()
});
let [w, h] = shape.extent;
let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::BGR10XR, w, h, false);
descriptor.usage = TextureUsage::RENDER_TARGET;
descriptor.resource_options = ResourceOptions::private();
let target = device.new_texture(&descriptor).unwrap();
let mut pass = RenderPassDescriptor::new();
let color = &mut pass.color_attachments[0];
color.texture = Some(target);
color.load_action = LoadAction::Load;
color.store_action = StoreAction::Store;
Bench {
queue: device.new_command_queue().unwrap(),
state: state.clone(),
positions: buffer_with(device, &bytes).unwrap(),
uniforms: buffer_with(device, &identity()).unwrap(),
indices,
pass,
shape,
}
}
/// The draws of one pass in `mode`.
fn draws(&self, e: &mut RenderCommandEncoder, mode: Mode) {
e.set_render_pipeline_state(&self.state).unwrap();
e.set_vertex_buffer(Some(&self.positions), 0, 0).unwrap();
e.set_vertex_buffer(Some(&self.uniforms), 0, 1).unwrap();
match &self.indices {
Some(indices) => {
for (c, cell) in CELLS.into_iter().enumerate() {
e.set_scissor_rect(cell).unwrap();
for r in 0..4 {
let base = 4 * (4 * c + r) as i32;
e.draw_indexed_primitives(
PrimitiveType::Triangle,
6,
IndexType::UInt16,
indices,
0,
1,
base,
0,
)
.unwrap();
}
}
}
None => {
for _ in 0..4 {
e.draw_primitives(PrimitiveType::Triangle, 0, HEAVY_VERTICES, 1, 0)
.unwrap();
}
}
}
let off = (self.shape.positions.len() - OFF.len()) as u32;
match mode {
Mode::Exact => e.draw_primitives(PrimitiveType::Triangle, off, 3, 1, 0),
Mode::EveryTile => e.draw_primitives(PrimitiveType::Line, off + 3, 2, 1, 0),
}
.unwrap();
}
/// One command buffer of `passes` passes in `mode`: the host's encode time, the GPU time and
/// the host's time from commit to completion, in milliseconds a pass.
fn sample(&self, mode: Mode, passes: usize) -> [f64; 3] {
let began = Instant::now();
let command_buffer = self.queue.command_buffer().unwrap();
for _ in 0..passes {
let mut e = command_buffer.render_command_encoder(&self.pass).unwrap();
self.draws(&mut e, mode);
e.end_encoding().unwrap();
}
let encoded = began.elapsed().as_secs_f64();
let committed = Instant::now();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
let wall = committed.elapsed().as_secs_f64();
assert_eq!(command_buffer.error(), None, "{} {mode:?}", self.shape.name);
let gpu = command_buffer.gpu_end_time().unwrap() - command_buffer.gpu_start_time().unwrap();
let per = |s: f64| s * 1e3 / passes as f64;
[per(encoded), per(gpu), per(wall)]
}
}
/// Each shape's passes in both modes (the module docs).
#[test]
fn capture_replay_costs() {
let cache = ScratchCache::new().unwrap();
let messages = Messages::default();
let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| {
options.layers.clear();
options.announce_each = [UNREACHED_TILES].into_iter().collect();
})
.unwrap();
let bitcode = llvm_assemble(&engine_dir().join("rch_vertex_math.ll")).unwrap();
let library = device.new_library_with_air(&bitcode).unwrap();
let function = |name: &str| {
StageSource::Function(
library
.new_function_with_name(name)
.unwrap()
.function_descriptor(),
)
};
let mut state = RenderPipelineDescriptor::new(function("rch_vertex_math"));
state.fragment = Some(function("rch_vertex_math_color"));
let mut none = ColorAttachmentDescriptor::new(PixelFormat::BGR10XR);
none.write_mask = ColorWriteMask::NONE;
state.color_attachments[0] = Some(none);
let state = device
.new_render_pipeline_state(&state, &PipelineOptions::default())
.unwrap();
let announced = || counts(&messages.take_notices()).contains_key(&UNREACHED_TILES);
for shape in [cells(), heavy()] {
let bench = Bench::new(&device, &state, shape);
let name = bench.shape.name;
// Until the shape's capture forms and pipelines are made.
announced();
let began = Instant::now();
loop {
bench.sample(Mode::Exact, 1);
if !announced() {
break;
}
assert!(began.elapsed() < WAIT, "{name}: no capture within {WAIT:?}");
std::thread::sleep(Duration::from_millis(20));
}
let mut times = [Vec::new(), Vec::new()];
let tallied = device.work_counts();
for k in 0..23 {
for (m, mode) in [Mode::Exact, Mode::EveryTile].into_iter().enumerate() {
let before = device.work_counts().capture_reach_passes;
let sample = bench.sample(mode, PASSES);
let captured = device.work_counts().capture_reach_passes - before;
let every = announced();
match mode {
Mode::Exact => assert!(captured == PASSES as u64 && !every, "{name} {k}"),
Mode::EveryTile => assert!(captured == 0 && every, "{name} {k}"),
}
if k >= 3 {
times[m].push(sample);
}
}
}
let after = device.work_counts();
let passes = after.capture_reach_passes - tallied.capture_reach_passes;
eprintln!(
"CAPTURE-TALLY {name}: {passes} captured passes found {} of the {} tiles their \
scissors bound; {} at their bound, {} narrower",
after.capture_reach_tiles_found - tallied.capture_reach_tiles_found,
after.capture_reach_tiles_bound - tallied.capture_reach_tiles_bound,
after.capture_reach_bound_passes - tallied.capture_reach_bound_passes,
after.capture_reach_narrower_passes - tallied.capture_reach_narrower_passes,
);
let stat = |samples: &[[f64; 3]], i: usize| {
let mut v: Vec<f64> = samples.iter().map(|s| s[i]).collect();
v.sort_by(f64::total_cmp);
(v[v.len() / 2], v[0])
};
for (m, mode) in ["exact", "every-tile"].into_iter().enumerate() {
let (encode, encode_fast) = stat(&times[m], 0);
let (gpu, gpu_fast) = stat(&times[m], 1);
let (wall, wall_fast) = stat(&times[m], 2);
eprintln!(
"CAPTURE-COST {name} {mode} a pass ({PASSES} passes a command buffer): encode \
median {encode:.4} ms, fastest {encode_fast:.4} ms; GPU median {gpu:.4} ms, \
fastest {gpu_fast:.4} ms; commit to completion median {wall:.4} ms, fastest \
{wall_fast:.4} ms"
);
}
}
messages.take_notices();
}
@@ -1,448 +0,0 @@
//! Capture replay (`render/capture.rs`) on the device the cfg selects, under the validation layer:
//! a pass's load of an extended-range color rewrites the tiles its draws' primitives reach, as the
//! capture of their own positions bins them.
//!
//! A 128x128 `BGR10_XR` target of zero words, loaded and stored, under a pipeline of the owned
//! fixture `rch_vertex_math` (identity matrices: each position is the buffer's) whose color's
//! write mask is none of its channels, draws a triangle list's triangle in tile (1, 2), and an
//! indexed (`uint16`) triangle strip of two instances whose all-ones index restarts it: its first
//! piece's two triangles over tiles (2, 0) and (3, 0), its second's one in tile (0, 3). Metal's
//! pass rewrites the words of each tile a primitive reaches (bits 30 and 31 ones), and keeps the
//! others. The pass's first run asks for its draws' capture forms, which the device translates on
//! its pool and makes at later passes: it rewrites every tile and announces
//! `unreached-tiles-rewritten` (the device announces the kind at every occurrence). A later run,
//! once every capture form and pipeline is made, rewrites the four tiles alone, Metal's answer, and
//! announces nothing; so does the run after it. The same draws in a pass that loads the color
//! `DontCare` or `Clear` run no capture: no load pass takes the color.
//!
//! An atlas pass as the consumer's draw them does the same over its scissored cells' small rects
//! (an `RGB10A8_2P_XR10` target beside memoryless colors and depth): its first run rewrites every
//! tile the scissors reach, a later run the tiles the rects reach alone.
use super::degrade_notices::counts;
use super::resolves::{lane_with, quiet};
use super::{buffer_with, WAIT};
use crate::air_library::AirLibrary;
use metal2vulkan::metal::{ColorWriteMask, IndexType, PixelFormat, PrimitiveType, TextureUsage};
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
use metal2vulkan_devtools::{engine_dir, llvm_assemble};
use metal2vulkan_runtime::{
BlitOption, Degradation, LoadAction, PipelineOptions, Region, RenderCommandEncoder,
RenderPassDescriptor, ResourceOptions, ScissorRect, StoreAction, TextureDescriptor, WorkCounts,
};
use std::time::{Duration, Instant};
/// The target's side, in pixels: four 32x32 tiles a side.
const SIDE: u64 = 128;
/// The kind the pass announces until its draws' tile reach is captured.
const UNREACHED_TILES: Degradation = Degradation::UnreachedTilesRewritten;
/// The tiles the draws' primitives reach, `(x, y)`.
const REACHED: [(u64, u64); 4] = [(1, 2), (2, 0), (3, 0), (0, 3)];
/// The strip's indices: its first piece (vertices 3 to 6), the restart, its second (7 to 9).
const STRIP: [u16; 8] = [3, 4, 5, 6, 0xffff, 7, 8, 9];
/// The clip-space position of window pixel `(x, y)` of the target under Metal's default
/// viewport.
fn clip(x: f32, y: f32) -> [f32; 4] {
[x / 64.0 - 1.0, 1.0 - y / 64.0, 0.5, 1.0]
}
/// The positions: the list's triangle in tile (1, 2), the strip's first piece's four vertices
/// over tiles (2, 0) and (3, 0), and its second piece's triangle in tile (0, 3).
fn positions() -> Vec<u8> {
[
clip(40.0, 70.0),
clip(50.0, 70.0),
clip(40.0, 80.0),
clip(70.0, 8.0),
clip(70.0, 20.0),
clip(120.0, 8.0),
clip(120.0, 20.0),
clip(5.0, 100.0),
clip(20.0, 100.0),
clip(5.0, 115.0),
]
.iter()
.flatten()
.flat_map(|v| v.to_le_bytes())
.collect()
}
/// The fixture's uniforms: identity model, view and projection matrices.
fn identity() -> Vec<u8> {
let one = |i: usize| (0..4).map(move |j| if i == j { 1.0f32 } else { 0.0 });
(0..3)
.flat_map(|_| (0..4).flat_map(one))
.flat_map(f32::to_le_bytes)
.collect()
}
/// The target's words once a pass rewrote the tiles `tiles` and kept every other.
fn rewritten(tiles: &[(u64, u64)]) -> Vec<u8> {
(0..SIDE)
.flat_map(|y| (0..SIDE).map(move |x| (x, y)))
.flat_map(|(x, y)| match tiles.contains(&(x / 32, y / 32)) {
true => 0xc000_0000u32.to_le_bytes(),
false => [0; 4],
})
.collect()
}
/// The capture tally between `before` and `after` (`WorkCounts`): the tiles found and bound, and
/// the passes found at their bound and narrower.
fn tally(before: &WorkCounts, after: &WorkCounts) -> (u64, u64, u64, u64) {
(
after.capture_reach_tiles_found - before.capture_reach_tiles_found,
after.capture_reach_tiles_bound - before.capture_reach_tiles_bound,
after.capture_reach_bound_passes - before.capture_reach_bound_passes,
after.capture_reach_narrower_passes - before.capture_reach_narrower_passes,
)
}
/// Every tile of the target.
fn every_tile() -> Vec<(u64, u64)> {
(0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect()
}
/// The pass's first run rewrites every tile and announces `unreached-tiles-rewritten`; a later
/// run, once its draws' capture forms and pipelines are made, rewrites only the tiles their
/// primitives reach and announces nothing (the module docs).
#[test]
fn a_load_pass_rewrites_the_tiles_its_captured_primitives_reach() {
let (messages, _cache, lane) = lane_with(|options| {
options.announce_each = [UNREACHED_TILES].into_iter().collect();
});
let bitcode = llvm_assemble(&engine_dir().join("rch_vertex_math.ll")).unwrap();
let library = lane.device.new_library_with_air(&bitcode).unwrap();
let function = |name: &str| {
StageSource::Function(
library
.new_function_with_name(name)
.unwrap()
.function_descriptor(),
)
};
let pf = PixelFormat::BGR10XR;
let mut state = RenderPipelineDescriptor::new(function("rch_vertex_math"));
state.fragment = Some(function("rch_vertex_math_color"));
let mut none = ColorAttachmentDescriptor::new(pf);
none.write_mask = ColorWriteMask::NONE;
state.color_attachments[0] = Some(none);
let state = lane
.device
.new_render_pipeline_state(&state, &PipelineOptions::default())
.unwrap();
let positions = buffer_with(&lane.device, &positions()).unwrap();
let uniforms = buffer_with(&lane.device, &identity()).unwrap();
let indices: Vec<u8> = STRIP.iter().flat_map(|i| i.to_le_bytes()).collect();
let indices = buffer_with(&lane.device, &indices).unwrap();
let mut descriptor = TextureDescriptor::texture_2d(pf, SIDE, SIDE, false);
descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ;
descriptor.resource_options = ResourceOptions::shared();
let target = lane.device.new_texture(&descriptor).unwrap();
let mut pass = RenderPassDescriptor::new();
let color = &mut pass.color_attachments[0];
color.texture = Some(target.clone());
color.load_action = LoadAction::Load;
color.store_action = StoreAction::Store;
let zeros = vec![0u8; (4 * SIDE * SIDE) as usize];
// The pass's draws.
let draw = |e: &mut RenderCommandEncoder| {
e.set_render_pipeline_state(&state).unwrap();
e.set_vertex_buffer(Some(&positions), 0, 0).unwrap();
e.set_vertex_buffer(Some(&uniforms), 0, 1).unwrap();
e.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0)
.unwrap();
e.draw_indexed_primitives(
PrimitiveType::TriangleStrip,
STRIP.len() as u32,
IndexType::UInt16,
&indices,
0,
2,
0,
0,
)
.unwrap();
};
// One run of the pass over zero words: the words it leaves, and whether it announced.
let run = || {
target
.replace_region(Region::new_2d(0, 0, SIDE, SIDE), 0, 0, &zeros, 4 * SIDE, 0)
.unwrap();
lane.run(&pass, |_, e, _| draw(e)).unwrap();
let words = lane.read(&target, (0, 0), 4, BlitOption::None);
let announced = counts(&messages.take_notices()).contains_key(&UNREACHED_TILES);
(words, announced)
};
let before = lane.device.work_counts();
let (words, announced) = run();
assert!(announced, "the first run announces");
assert!(
words == rewritten(&every_tile()),
"the first run rewrites every tile"
);
// The capture forms are translated on the pool, then made at later runs.
let began = Instant::now();
let exact = loop {
let (words, announced) = run();
if !announced {
break words;
}
assert!(words == rewritten(&every_tile()), "an announced run");
assert!(
began.elapsed() < WAIT,
"no run's capture was ready within {WAIT:?}"
);
std::thread::sleep(Duration::from_millis(20));
};
assert!(exact == rewritten(&REACHED), "the captured run's tiles");
let tallied = lane.device.work_counts();
let (words, announced) = run();
assert!(!announced && words == exact, "the run after it");
let after = lane.device.work_counts();
assert!(
after.capture_reach_passes - before.capture_reach_passes >= 2,
"{before:?} {after:?}"
);
// Its tally: the primitives reach 4 of the 16 tiles its viewport reaches.
assert_eq!(tally(&tallied, &after), (4, 16, 0, 1));
// The same draws in a pass that loads the color `DontCare` (a dont-care load's clear,
// `clear_reach.rs`) or `Clear`: no load pass takes it, so no capture runs.
for load in [LoadAction::DontCare, LoadAction::Clear] {
let mut other = RenderPassDescriptor::new();
let color = &mut other.color_attachments[0];
color.texture = Some(target.clone());
color.load_action = load;
color.store_action = StoreAction::Store;
let counted = lane.device.work_counts().capture_reach_passes;
lane.run(&other, |_, e, _| draw(e)).unwrap();
let captured = lane.device.work_counts().capture_reach_passes - counted;
assert_eq!(captured, 0, "a {load:?} load captures nothing");
messages.take_notices();
}
quiet(lane, &messages);
}
/// The atlas passes' height, in pixels: eight tiles.
const ATLAS_HEIGHT: u64 = 256;
/// The atlas passes' scissored cells.
const CELLS: [ScissorRect; 2] = [
ScissorRect {
x: 0,
y: 0,
width: 166,
height: 166,
},
ScissorRect {
x: 166,
y: 0,
width: 166,
height: 166,
},
];
/// Each cell's small rects, `[x0, y0, x1, y1]` in pixels: their edges off the tile grid, one
/// rect across x = 64.
const RECTS: [&[[f32; 4]]; 2] = [
&[
[10.0, 10.0, 26.0, 26.0],
[60.0, 40.0, 70.0, 50.0],
[100.0, 130.0, 120.0, 150.0],
],
&[[180.0, 10.0, 200.0, 20.0], [290.0, 140.0, 300.0, 158.0]],
];
/// The tiles each cell's rects reach, `(x, y)`.
const RECT_TILES: [&[(u64, u64)]; 2] =
[&[(0, 0), (1, 1), (2, 1), (3, 4)], &[(5, 0), (6, 0), (9, 4)]];
/// A two-plane target's color words of every bit, once a pass rewrote the tiles `tiles` (the
/// top two bits zeroed) and kept every other.
fn two_plane_rewritten([width, height]: [u64; 2], tiles: &[(u64, u64)]) -> Vec<u8> {
(0..height)
.flat_map(|y| (0..width).map(move |x| (x, y)))
.flat_map(|(x, y)| match tiles.contains(&(x / 32, y / 32)) {
true => 0x3fff_ffffu32.to_le_bytes(),
false => u32::MAX.to_le_bytes(),
})
.collect()
}
/// An atlas pass as the consumer's draw them: an `RGB10A8_2P_XR10` color attachment of 256x256 (one
/// cell) or 384x256 (both) whose color words hold every bit, loaded and stored, beside two
/// memoryless `RGBA16Float` colors and a memoryless `Depth32Float` depth, each cleared and not
/// stored; in each cell, under its scissor, its small rects, each an indexed (`uint16`) list of two
/// triangles at its own base vertex, but for the third, a strip of four vertices without indices.
/// Every color's write mask is none of its channels. The first run rewrites every tile the cells'
/// scissors reach and announces `unreached-tiles-rewritten`; a later run, once the capture forms
/// and pipelines are made, rewrites the tiles the rects reach alone, Metal's answer, and announces
/// nothing.
#[test]
fn an_atlas_pass_of_scissored_cells_rewrites_the_tiles_its_rects_reach() {
let (messages, _cache, lane) = lane_with(|options| {
options.announce_each = [UNREACHED_TILES].into_iter().collect();
});
let bitcode = llvm_assemble(&engine_dir().join("rch_vertex_math.ll")).unwrap();
let library = lane.device.new_library_with_air(&bitcode).unwrap();
let function = |name: &str| {
StageSource::Function(
library
.new_function_with_name(name)
.unwrap()
.function_descriptor(),
)
};
let pf = PixelFormat::RGB10A82PXR10;
let side = PixelFormat::RGBA16Float;
let mut state = RenderPipelineDescriptor::new(function("rch_vertex_math"));
state.fragment = Some(function("rch_vertex_math_color"));
for (index, format) in [pf, side, side].into_iter().enumerate() {
let mut none = ColorAttachmentDescriptor::new(format);
none.write_mask = ColorWriteMask::NONE;
state.color_attachments[index] = Some(none);
}
state.depth_format = Some(PixelFormat::Depth32Float);
let state = lane
.device
.new_render_pipeline_state(&state, &PipelineOptions::default())
.unwrap();
let uniforms = buffer_with(&lane.device, &identity()).unwrap();
let list: Vec<u8> = [0u16, 1, 2, 2, 1, 3]
.iter()
.flat_map(|i| i.to_le_bytes())
.collect();
let list = buffer_with(&lane.device, &list).unwrap();
for (width, cells) in [(256u64, 1usize), (384, 2)] {
let extent = [width, ATLAS_HEIGHT];
let at = |x: f32, y: f32| {
[
2.0 * x / width as f32 - 1.0,
1.0 - 2.0 * y / ATLAS_HEIGHT as f32,
0.5,
1.0,
]
};
let positions: Vec<u8> = RECTS[..cells]
.iter()
.flat_map(|rects| rects.iter())
.flat_map(|&[x0, y0, x1, y1]| [at(x0, y0), at(x1, y0), at(x0, y1), at(x1, y1)])
.flatten()
.flat_map(f32::to_le_bytes)
.collect();
let positions = buffer_with(&lane.device, &positions).unwrap();
let mut descriptor = TextureDescriptor::texture_2d(pf, width, ATLAS_HEIGHT, false);
descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ;
descriptor.resource_options = ResourceOptions::shared();
let target = lane.device.new_texture(&descriptor).unwrap();
let transient = |format: PixelFormat| {
let mut descriptor = TextureDescriptor::texture_2d(format, width, ATLAS_HEIGHT, false);
descriptor.usage = TextureUsage::RENDER_TARGET;
descriptor.resource_options = super::memoryless::memoryless_options();
lane.device.new_texture(&descriptor).unwrap()
};
let mut pass = RenderPassDescriptor::new();
let color = &mut pass.color_attachments[0];
color.texture = Some(target.clone());
color.load_action = LoadAction::Load;
color.store_action = StoreAction::Store;
for index in [1, 2] {
let color = &mut pass.color_attachments[index];
color.texture = Some(transient(side));
color.load_action = LoadAction::Clear;
color.store_action = StoreAction::DontCare;
}
pass.depth_attachment.texture = Some(transient(PixelFormat::Depth32Float));
pass.depth_attachment.load_action = LoadAction::Clear;
pass.depth_attachment.clear_depth = 1.0;
pass.depth_attachment.store_action = StoreAction::DontCare;
let filled = vec![0xffu8; (4 * width * ATLAS_HEIGHT) as usize];
// One run of the pass over words of every bit: the words it leaves, and whether it
// announced.
let run = || {
target
.replace_region(
Region::new_2d(0, 0, width, ATLAS_HEIGHT),
0,
0,
&filled,
4 * width,
0,
)
.unwrap();
lane.run(&pass, |_, e, _| {
e.set_render_pipeline_state(&state).unwrap();
e.set_vertex_buffer(Some(&positions), 0, 0).unwrap();
e.set_vertex_buffer(Some(&uniforms), 0, 1).unwrap();
let mut rect = 0u32;
for (cell, rects) in CELLS[..cells].iter().zip(RECTS) {
e.set_scissor_rect(*cell).unwrap();
for _ in rects {
match rect {
2 => e.draw_primitives(PrimitiveType::TriangleStrip, 4 * rect, 4, 1, 0),
_ => e.draw_indexed_primitives(
PrimitiveType::Triangle,
6,
IndexType::UInt16,
&list,
0,
1,
4 * rect as i32,
0,
),
}
.unwrap();
rect += 1;
}
}
})
.unwrap();
let words = lane.read(&target, (0, 0), 4, BlitOption::None);
let announced = counts(&messages.take_notices()).contains_key(&UNREACHED_TILES);
(words, announced)
};
// The host's reach: every tile the cells' scissors reach.
let last = (CELLS[cells - 1].x + CELLS[cells - 1].width - 1) / 32;
let scissored: Vec<(u64, u64)> = (0..=165 / 32)
.flat_map(|y| (0..=last).map(move |x| (x, y)))
.collect();
let reached: Vec<(u64, u64)> = RECT_TILES[..cells].concat();
// The first target's first run asks for the draws' capture forms; the second target's
// draws take the same ones, already made or being made.
let mut ran = run();
assert!(ran.1 || cells > 1, "{width}: the first run announces");
let began = Instant::now();
let exact = loop {
let (words, announced) = ran;
if !announced {
break words;
}
assert!(
words == two_plane_rewritten(extent, &scissored),
"{width}: an announced run rewrites the scissors' tiles"
);
assert!(
began.elapsed() < WAIT,
"{width}: no run's capture was ready within {WAIT:?}"
);
std::thread::sleep(Duration::from_millis(20));
ran = run();
};
assert!(
exact == two_plane_rewritten(extent, &reached),
"{width}: the captured run's tiles"
);
let tallied = lane.device.work_counts();
let (words, announced) = run();
assert!(!announced && words == exact, "{width}: the run after it");
// Its tally: the rects reach a few of the tiles the scissors reach.
let counted = (reached.len() as u64, scissored.len() as u64, 0, 1);
let after = lane.device.work_counts();
assert_eq!(tally(&tallied, &after), counted, "{width}");
}
quiet(lane, &messages);
}
@@ -165,7 +165,7 @@ use super::compressed_decode::BLOCK_DECODES;
use super::cross_class_reads::CROSS_CLASS;
use super::depth_denormals::{DEPTH_DENORMALS, SIGNED_DEPTH_TESTS};
use super::detach_textures::DETACHED_REACHES;
use super::extended_range_blends::{EXTENDED_RANGE_BITS, STORED_CODES, UNREACHED_TILES};
use super::extended_range_blends::{EXTENDED_RANGE_BITS, STORED_CODES};
use super::extended_range_resolve::XR_RESOLVE;
use super::extended_range_two_planes::HEAP_PLANES;
use super::first_use::FIRST_SPARSE;
@@ -534,7 +534,6 @@ fn every_kind_has_a_site_a_lane_test_takes() {
&HEAP_PLANES,
&TWO_PLANE_COPIES,
&EXTENDED_RANGE_BITS,
&UNREACHED_TILES,
&SNORM_MINIMUM,
&SHARED_EXPONENT,
&STORED_CODES,
@@ -13,10 +13,10 @@
//! 0 through a blit, a two-plane format's alpha bytes as `round(255 a)` of a `float` read. Where it
//! lies: a texture of the device's own, a placement heap's, and (the two-plane formats) one over
//! the planes of a `'b3a8'` surface, whose bytes are read where Metal keeps them. A pass that
//! announces `extended-range-bits-kept` (a heap's two-plane texture, a shadow of the heap's bytes
//! the load pass does not take) keeps the bits the codes leave unused in the texels its draws do
//! not write, where Metal's pass rewrites them: its bands are compared with those bits as Metal's
//! pass leaves them ([`as_metal_leaves`]), the codes exactly. A differing band is printed on an
//! announces `extended-range-bits-kept` (every pass that loads the target: the device's store)
//! keeps the bits the codes leave unused in the texels its draws do not write, where Metal's pass
//! rewrites them: its bands are compared with those bits as Metal's pass leaves them
//! ([`as_metal_leaves`]), the codes exactly. A differing band is printed on an
//! `XR-TABLE-DIFFERS` line.
//!
//! The table of the probe built without fast math (`xr_blends::safe_table`) is
@@ -796,12 +796,15 @@ fn a_memoryless_color_2_blends_as_a_stored_color_does() {
})
.unwrap();
let (stored_plane, stored_alpha) = bytes_of(&lane, (&stored, None), layout, &table);
// The pass loads color 0, so its texels the draws do not write keep their bytes, the device's
// store (`extended-range-bits-kept`): each band is compared with the bits its codes leave unused
// as Metal's pass leaves them, the codes exactly.
for (row, _) in &made {
let at = row.config * BAND;
let band = &stored_plane[4 * at..4 * (at + BAND)];
let band = as_metal_leaves(layout, &stored_plane[4 * at..4 * (at + BAND)]);
let alpha_band = &stored_alpha[at..at + BAND];
assert_eq!(
(xr_blends::fnv(band), xr_blends::fnv(alpha_band)),
(xr_blends::fnv(&band), xr_blends::fnv(alpha_band)),
(row.plane, row.alpha),
"cfg {}: the stored color 0 is not Metal's",
row.config
@@ -37,9 +37,9 @@ use metal2vulkan::metal::{
};
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
use metal2vulkan_runtime::{
BlitOption, Buffer, ClearColor, Degradation, Error, IndirectCommandBufferDescriptor,
LoadAction, PipelineOptions, Region, RenderPassDescriptor, ResourceOptions, StoreAction,
Texture, TextureDescriptor,
BlitOption, Buffer, ClearColor, DebugMessage, Degradation, Error,
IndirectCommandBufferDescriptor, LoadAction, PipelineOptions, Region, RenderPassDescriptor,
ResourceOptions, StoreAction, Texture, TextureDescriptor,
};
use std::collections::BTreeSet;
@@ -689,22 +689,17 @@ fn a_blend_of_a_computed_float4_into_extended_range_announces_its_source() {
assert_eq!(counts(&notices).get(&float_source), None, "{notices:?}");
}
/// The kind a draw in a pass that loads an extended-range color the load pass does not take
/// announces.
/// The kind a draw in a pass that loads an extended-range, padded or bfloat color announces.
pub(super) const EXTENDED_RANGE_BITS: [Degradation; 1] = [Degradation::ExtendedRangeBitsKept];
/// The kind a pass whose load pass rewrites every tile of its render area, where none of its
/// color attachments is cleared, announces.
pub(super) const UNREACHED_TILES: [Degradation; 1] = [Degradation::UnreachedTilesRewritten];
/// A draw into `BGR10_XR` holding the probe's random texels under a write mask of none of its
/// channels: every texel ends with its codes and its bits 30 and 31 ones, as Metal's pass leaves
/// each tile a draw reaches (on an Apple M4 and an Apple M3 Max; the full-screen
/// triangle reaches every tile), through the load pass (`render/unused_bits_load.rs`).
/// `extended-range-bits-kept` is not announced, and `unreached-tiles-rewritten` is, once (the pass
/// clears no color). A draw under every channel announces neither bits kind.
/// channels: every texel keeps its bytes, the device's store (`render/tile_store.rs`), where
/// Metal's pass leaves each tile a draw reaches with its bits 30 and 31 ones (on an Apple M4 and
/// an Apple M3 Max; the full-screen triangle reaches every tile); `extended-range-bits-kept` is
/// announced once. A draw under every channel, whose texels the draw writes, announces it no
/// more (once per device).
#[test]
fn a_draw_under_an_empty_mask_leaves_metals_unused_bits() {
fn a_draw_under_an_empty_mask_keeps_the_unused_bits_and_says_so() {
let (messages, _cache, lane) = lane();
let halves = halves();
let pf = PixelFormat::BGR10XR;
@@ -716,17 +711,21 @@ fn a_draw_under_an_empty_mask_leaves_metals_unused_bits() {
let first = made(&lane, &[draw_descriptor(&lane, none)]);
draw(&lane, &t, &halves, none).expect("no channel");
let got = lane.read(&t, (0, 0), 4, BlitOption::None);
let want: Vec<u8> = plane
let canonical = plane
.chunks(4)
.flat_map(|w| (u32::from_le_bytes([w[0], w[1], w[2], w[3]]) | 0xc000_0000).to_le_bytes())
.collect();
.filter(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]]) >> 30 != 3)
.count();
println!("EXTENDED-RANGE-BITS-KEPT {canonical} texels Metal's pass would rewrite");
assert!(
got == want,
"the texels differ from Metal's: {}",
canonical > 0,
"the probe's texels hold no bits Metal rewrites"
);
assert!(
got == plane,
"the texels differ from their bytes: {}",
first_texels(&got, 4)
);
let counts = assert_made_once(&messages, &UNREACHED_TILES, &first);
assert!(!counts.contains_key(&EXTENDED_RANGE_BITS[0]), "{counts:?}");
assert_made_once(&messages, &EXTENDED_RANGE_BITS, &first);
let t = filled(&lane, pf, (&plane, &alpha));
let every = ColorAttachmentDescriptor::new(pf);
let first = made(&lane, &[draw_descriptor(&lane, every)]);
@@ -736,11 +735,9 @@ fn a_draw_under_an_empty_mask_leaves_metals_unused_bits() {
quiet(lane, &messages);
}
/// A pass that loads a 4x multisampled `BGR10_XR` attachment, which the load pass does not take
/// (no copy reaches a multisampled image's samples, `render/unused_bits_load.rs`), and draws
/// announces `extended-range-bits-kept` once, naming color 0, and not
/// `unreached-tiles-rewritten`: the attachment keeps the bits its draws do not write, which
/// Metal's pass rewrites in each tile a draw reaches.
/// A pass that loads a 4x multisampled `BGR10_XR` attachment and draws announces
/// `extended-range-bits-kept` once, naming color 0: the attachment keeps the bits its draws do not
/// write, which Metal's pass rewrites in each tile a draw reaches.
#[test]
fn a_multisampled_extended_range_color_keeps_its_unused_bits_and_says_so() {
let (messages, _cache, lane) = lane();
@@ -775,8 +772,7 @@ fn a_multisampled_extended_range_color_keeps_its_unused_bits_and_says_so() {
descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(pf));
descriptor.raster_sample_count = 4;
messages.restore_notices(notices);
let counts = assert_made_once(&messages, &EXTENDED_RANGE_BITS, &made(&lane, &[descriptor]));
assert!(!counts.contains_key(&UNREACHED_TILES[0]), "{counts:?}");
assert_made_once(&messages, &EXTENDED_RANGE_BITS, &made(&lane, &[descriptor]));
quiet(lane, &messages);
}
@@ -784,16 +780,13 @@ fn a_multisampled_extended_range_color_keeps_its_unused_bits_and_says_so() {
/// buffers of words of all ones), every one loaded, of a state that writes white to color 0
/// under a write mask of none of its channels, on a device that asks for the kinds at every
/// occurrence (`DeviceOptions::announce_each`), with a draw and an indirect command buffer's
/// execution of a draw: the load pass (`render/unused_bits_load.rs`) takes every color, so
/// `extended-range-bits-kept` is not announced, and the padded
/// colors' words are Metal's, every one `0xffc0` (Metal rewrites a padded attachment's words in
/// a loading pass that draws, the colors its function does not write too). The pass clears no
/// color, so `unreached-tiles-rewritten` is announced, naming the three. A pass that clears and
/// stores the padded colors announces none of the kinds: Metal's pass then rewrites every tile. One
/// that draws nothing announces nothing.
/// execution of a draw: `extended-range-bits-kept` is announced, naming the three loaded colors,
/// and the padded colors, which the function does not write, keep their bytes, the device's store
/// (Metal's pass leaves each word `0xffc0`, its low six bits zeroed). A pass that clears and
/// stores the padded colors names color 0 alone; one that draws nothing announces nothing.
#[test]
fn a_pass_of_extended_range_and_padded_colors_names_unreached_tiles_unless_one_is_cleared() {
let kinds = [EXTENDED_RANGE_BITS[0], UNREACHED_TILES[0]];
fn a_pass_of_extended_range_and_padded_colors_names_each_loaded_color() {
let kinds = [EXTENDED_RANGE_BITS[0]];
let (messages, _cache, lane) =
lane_with(|options| options.announce_each = kinds.into_iter().collect());
let (w, h) = (WIDTH as u64, HEIGHT as u64);
@@ -879,36 +872,41 @@ fn a_pass_of_extended_range_and_padded_colors_names_unreached_tiles_unless_one_i
.unwrap();
messages.take_notices()
};
let notices = drawn(LoadAction::Load, true);
let announced = counts(&notices);
assert!(
!announced.contains_key(&EXTENDED_RANGE_BITS[0]),
"{announced:?}"
);
assert!(announced.contains_key(&UNREACHED_TILES[0]), "{announced:?}");
for message in &notices {
let notice = message.degradation.as_ref().unwrap();
if notice.degradation == UNREACHED_TILES[0] {
for color in ["color 0", "color 1", "color 2"] {
assert!(notice.object.contains(color), "{}", message.text);
// The colors each announcement names, of the passes' notices.
let named = |notices: &[DebugMessage]| -> Vec<bool> {
let colors = ["color 0", "color 1", "color 2"];
let mut named = vec![false; colors.len()];
for message in notices {
let notice = message.degradation.as_ref().unwrap();
if notice.degradation != EXTENDED_RANGE_BITS[0] {
continue;
}
for (seen, color) in named.iter_mut().zip(colors) {
*seen |= notice.object.contains(color);
}
}
}
named
};
let notices = drawn(LoadAction::Load, true);
assert!(
counts(&notices).contains_key(&EXTENDED_RANGE_BITS[0]),
"{:?}",
counts(&notices)
);
assert_eq!(named(&notices), [true, true, true]);
for (pf, buffer) in padded.iter().zip(&buffers) {
let row = 2 * u64::from(ExtendedRange::of(*pf).unwrap().raw_components()) * w;
let bytes = read_buffer(buffer, 0, bpr * h).unwrap();
for (y, line) in bytes.chunks(bpr as usize).enumerate() {
let (words, rest) = line.split_at(row as usize);
assert!(
words.chunks(2).all(|word| word == [0xc0, 0xff]),
line.iter().all(|&b| b == 0xff),
"{pf:?} row {y}: {:02x?}",
&words[..8]
&line[..8]
);
assert!(rest.iter().all(|&b| b == 0xff), "{pf:?} row {y}'s padding");
}
}
let announced = counts(&drawn(LoadAction::Clear, true));
assert!(announced.is_empty(), "{announced:?}");
let notices = drawn(LoadAction::Clear, true);
assert!(!notices.is_empty(), "a pass of a loaded BGR10_XR color");
assert_eq!(named(&notices), [true, false, false]);
let announced = counts(&drawn(LoadAction::Load, false));
assert!(announced.is_empty(), "{announced:?}");
quiet(lane, &messages);
@@ -982,8 +980,9 @@ fn tile_read(held: [f32; 4]) -> [f32; 4] {
/// to the source range and alpha to `[0, 1]` (`tile_read`; where the earlier model,
/// each draw reading the codes the one before stored, differed from Metal at 3, 558 of 4, 096
/// texels of the probe's own such pass), and the store writes the last `half`'s encode as a
/// kernel's write (`ExtendedRange::clear_texel`); colors 1 and 2 keep their texels, color 2's color
/// words' top two bits zeroed as Metal's pass leaves them. The pipeline is made on every device:
/// kernel's write (`ExtendedRange::clear_texel`); colors 1 and 2 keep their bytes, the device's
/// store, where Metal's pass zeroes color 2's color words' top two bits (`extended-range-bits-kept`
/// says so, `render/tile_store.rs`). The pipeline is made on every device:
/// one that fetches through the interlock writes the storage form and holds color 0's `half` shadow
/// from the second draw on (`render/extended_shadow.rs`), one with raster-order attachment access
/// reads an input attachment of the raw texels and writes the raw output, each draw reading the
@@ -1131,13 +1130,9 @@ fn a_fetched_two_plane_attachment_written_unblended_stores_metals_write() {
let count = (0..COUNT)
.filter(|&i| got_words[i] != want_words[i] || got_alpha[i] != want_alpha[i])
.count();
// Color 2, loaded and unwritten, keeps its codes and alpha bytes, its color words' top two
// bits zeroed as Metal's pass leaves each tile a draw reaches.
let canonical: Vec<u8> = other_plane
.chunks(4)
.flat_map(|w| (u32::from_le_bytes([w[0], w[1], w[2], w[3]]) & 0x3fff_ffff).to_le_bytes())
.collect();
let kept = lane.read(&other, (0, 0), 4, BlitOption::None) == canonical
// Color 2, loaded and unwritten, keeps its bytes, the device's store, where Metal's pass
// zeroes its color words' top two bits in each tile a draw reaches.
let kept = lane.read(&other, (0, 0), 4, BlitOption::None) == other_plane
&& alpha_of(&other) == other_alpha
&& lane.read(&covered, (0, 0), 4, BlitOption::None) == covered_texels;
println!(
@@ -20,21 +20,17 @@
//!
//! Metal's pass that loads such a texture and draws writes every word of its render area rounded
//! up to 32 texels back, the words no fragment writes and the channels the mask leaves out as
//! the write of their code's read (`ExtendedRange::load_code`: their code with its low six bits
//! zeroed, an `_sRGB` twin's through Metal's table). The runtime rewrites them so before the
//! pass (`render/unused_bits_load.rs`), so every case is Metal's, and none announces
//! `extended-range-bits-kept` (once `padded-bits-kept`). (The probes' passes also cleared and
//! stored a second color attachment, under which Metal's pass rewrites every tile of the render
//! area, the tiles no draw reaches too. The lane's draw of no vertices and its scissored draw have
//! it too, since without it the first reaches no tile and the pass keeps every word, and the second
//! only the tiles its scissor rectangle overlaps; the lane's other passes have none, and their
//! draws reach every tile alike.) The device's work counts show the path ran: one load pass per
//! case that draws, none for the case that does not, over the region's texels
//! (`WorkCounts::unused_bits_load_passes` and `unused_bits_load_texels`).
//! the write of their code's read (their code with its low six bits zeroed, an `_sRGB` twin's
//! through Metal's table). The device's store keeps those words (`render/tile_store.rs`), and
//! every pass that draws announces `extended-range-bits-kept`: a case whose draw writes every
//! word is Metal's, and in every other case each word the draw does not write keeps its bytes.
//! (The probes' passes also cleared and stored a second color attachment, under which Metal's
//! pass rewrites every tile of the render area, the tiles no draw reaches too. The lane's draw of
//! no vertices and its scissored draw have it too, as the probes' did.)
use super::degrade_notices::counts;
use super::extended_range_targets::digest;
use super::resolves::{lane, quiet, Lane};
use super::resolves::{lane_with, quiet, Lane};
use super::{buffer_with, read_buffer};
use crate::candidate::runtime_samples::{library, shape};
use metal2vulkan::metal::{
@@ -636,66 +632,82 @@ fn run(lane: &Lane, (pf, bits, pass): (PixelFormat, u64, Pass)) -> (Vec<u8>, boo
(words, padded)
}
/// The load passes case `pass` records and the texels they zero: none where it does not draw,
/// else one over its render area (the attachment's, or the smaller render target size) rounded
/// up to 32 texels a side, within the attachment.
fn loads(pass: Pass) -> (u64, u64) {
// The render area and the attachment's extent: a texture buffer's is its one row.
let ((w, h), within) = match pass {
Pass::Undrawn => return (0, 0),
Pass::TextureBuffer => ((WIDTH, 1), (WIDTH, 1)),
Pass::Sized(w, h) => ((w, h), (WIDTH, HEIGHT)),
_ => ((WIDTH, HEIGHT), (WIDTH, HEIGHT)),
/// Whether case `(bits, pass)`'s draw writes channel `c` of texel `(x, y)`: a channel its
/// write mask keeps (red 8, green 4), in a texel the draw covers (the whole texture, the scissor
/// rectangle, the smaller render target size, a texture buffer's one row; none for a draw of no
/// vertices or no draw).
fn writes((bits, pass): (u64, Pass), (x, y): (u64, u64), c: u64) -> bool {
let channel = [8, 4][c as usize];
let covered = match pass {
Pass::Whole | Pass::Executed | Pass::ArrayView | Pass::ArrayViewOfOne => true,
Pass::Scissored => (37..37 + 54).contains(&x) && (13..13 + 57).contains(&y),
Pass::Sized(w, h) => x < w && y < h,
Pass::TextureBuffer => y == 0,
Pass::NoVertices | Pass::Undrawn => false,
};
let region = |side: u64, within: u64| side.next_multiple_of(32).min(within);
(1, region(w, within.0) * region(h, within.1))
covered && bits & channel != 0
}
/// Every case's words are Metal's, the bytes between the rows stay, no case announces
/// `extended-range-bits-kept`, and each case that draws recorded one load pass over its region's texels
/// (the module docs).
/// Every case keeps the words its draw does not write and the bytes between the rows, a case
/// whose draw writes every word is Metal's, and every case that draws announces
/// `extended-range-bits-kept` (the module docs).
#[test]
fn a_loading_pass_that_draws_leaves_metals_padded_words() {
let (messages, _cache, lane) = lane();
fn a_loading_pass_that_draws_keeps_the_padded_words_it_does_not_write() {
let kept = Degradation::ExtendedRangeBitsKept;
let (messages, _cache, lane) =
lane_with(|options| options.announce_each = [kept].into_iter().collect());
let mut differ = Vec::new();
let (mut passes, mut texels) = (0, 0);
let (mut whole, mut kept_words) = (0, 0);
for case in METAL {
let (pf, bits, pass, metal) = case;
let before = lane.device.work_counts();
let (words, padded) = run(&lane, (pf, bits, pass));
let after = lane.device.work_counts();
let recorded = (
after.unused_bits_load_passes - before.unused_bits_load_passes,
after.unused_bits_load_texels - before.unused_bits_load_texels,
);
assert_eq!(
recorded,
loads(pass),
"{pf:?} {bits} {pass:?}: the load passes"
);
passes += recorded.0;
texels += recorded.1;
let channels = match pf {
PixelFormat::R10UnormX6 | PixelFormat::R10UnormX6SRGB => 1,
_ => 2,
};
let (got, padded) = run(&lane, (pf, bits, pass));
assert!(
padded,
"{pf:?} {bits} {pass:?}: the bytes between the rows changed"
);
let got = digest(&words);
if got != metal {
eprintln!("PADDED-LOADS-DIFFERS {pf:?} mask {bits} {pass:?}: {got}");
let input = words(channels);
let mut every = true;
let mut moved = 0;
for (i, (g, w)) in got.chunks(2).zip(input.chunks(2)).enumerate() {
let i = i as u64;
let (texel, c) = (i / channels, i % channels);
if writes((bits, pass), (texel % WIDTH, texel / WIDTH), c) {
continue;
}
every = false;
kept_words += 1;
moved += u64::from(g != w);
}
if moved > 0 {
eprintln!("PADDED-LOADS-DIFFERS {pf:?} mask {bits} {pass:?}: {moved} words moved");
differ.push(case);
}
if every {
whole += 1;
let got = digest(&got);
if got != metal {
eprintln!("PADDED-LOADS-DIFFERS {pf:?} mask {bits} {pass:?}: {got}");
differ.push(case);
}
}
let announced = counts(&messages.take_notices());
assert!(
!announced.contains_key(&Degradation::ExtendedRangeBitsKept),
assert_eq!(
announced.contains_key(&kept),
pass != Pass::Undrawn,
"{pf:?} {bits} {pass:?}: {announced:?}"
);
}
eprintln!(
"PADDED-LOADS {} cases, {} differ: {passes} load passes recorded, {texels} texels zeroed",
"PADDED-LOADS {} cases, {} differ: {whole} drawn whole against Metal's, {kept_words} \
words kept",
METAL.len(),
differ.len()
);
assert!(passes > 0 && texels > 0, "no load pass ran");
assert!(whole > 0 && kept_words > 0, "no case of either kind ran");
assert!(
differ.is_empty(),
"{} of {} cases differ: {differ:?}",
@@ -27,8 +27,9 @@
//! Metal stores `0x00000000` in each (`rgb10a2-srgb-stores-f` and `-h`).
//! - **Loads.** A 1024 x 4 target holding every color code in each channel and each alpha code,
//! loaded and stored by a pass whose draw writes another attachment alone: `load <i> <before>
//! <after>`. Each color code moves as `R10Unorm_X6_sRGB`'s does (`ExtendedRange::load_code`,
//! the runtime's load pass), alpha's stays.
//! <after>`. Each color code moves as `R10Unorm_X6_sRGB`'s does through Metal's table, alpha's
//! stays; the device's store keeps every code (`extended-range-bits-kept`), so the lane holds
//! it to the words loaded and prints Metal's digest beside it.
//!
//! The device's `isRGB10A2GammaSupported` answers as the texture's linear filter does. A
//! difference is printed on an `RGB10A2-SRGB-DIFFERS` line.
@@ -459,7 +460,7 @@ fn blit_words(lane: &Lane, target: &Texture, (width, height): (u64, u64)) -> Vec
words(&read_buffer(&back, 0, length).unwrap())
}
/// Clears, a draw's stores and a loading pass's rewrite of a 586 attachment are Metal's.
/// Clears and a draw's stores of a 586 attachment are Metal's; a loading pass keeps its words.
#[test]
fn passes_clear_store_and_load_rgb10a2_srgb_as_metal_does() {
let (messages, _cache, lane) = lane_with(|_| {});
@@ -653,8 +654,12 @@ fn passes_clear_store_and_load_rgb10a2_srgb_as_metal_does() {
writeln!(text, "load {i} {b:08x} {a:08x}").unwrap();
}
covers(&text, after.len(), "loads");
if digest(&text) != LOADS {
wrong.push(format!("loads {} (Metal's {LOADS})", digest(&text)));
println!("RGB10A2-SRGB-LOADS {}: Metal's {LOADS}", digest(&text));
if after != before {
let moved = before.iter().zip(&after).filter(|(b, a)| b != a).count();
wrong.push(format!(
"loads: {moved} words moved, where the device's store keeps them"
));
}
for line in &wrong {
println!("RGB10A2-SRGB-DIFFERS {}: {line}", lane.device.name());
@@ -13,7 +13,8 @@
//! every tile of a pass that draws (announced once, `RotatedLoadTiles`) and none of one that does
//! not, as Metal; a resolve lands as a store does; the bytes between the plane's rows stay. A
//! rotated texture of a padded 10-bit or extended-range format that such a pass loads keeps its
//! codes with the bits they leave unused as Metal's tile store makes them. CPU access and blits
//! codes and the bits they leave unused, the device's store, where Metal's tile store makes those
//! bits canonical (announced, `ExtendedRangeBitsKept`). CPU access and blits
//! address the plane as the texture's own extent at the plane's rows, turned or not, refused where
//! those rows run past the buffer; a fragment's `read()` sees the stored frame unturned. A view of the texture in another 8-bit RGBA format acts as the
//! texture does; other views are refused. The creators refuse what Metal asserts on, and the
@@ -564,16 +565,15 @@ fn loads_of_rotation_4_land_mirrored_and_passes_without_draws_keep_every_texel()
quiet(&messages);
}
/// A texel of the rotated attachments [`unused_bits_of_rotated_textures_are_metals`] loads: the
/// A texel of the rotated attachments [`unused_bits_of_rotated_textures_are_kept`] loads: the
/// format, its bytes, the write mask its draw takes, its bytes at the stored texel `(sx, sy)`
/// (codes naming the texel and channel, the bits they leave unused not Metal's), Metal's store
/// of those bytes, and its drawn texel's bytes, where the mask writes one.
/// (codes naming the texel and channel, the bits they leave unused not Metal's), and its drawn
/// texel's bytes, where the mask writes one.
struct UnusedBitsCase {
pf: PixelFormat,
texel: u64,
mask: ColorWriteMask,
named: fn((u64, u64)) -> Vec<u8>,
stored: fn(&[u8]) -> Vec<u8>,
drawn: Option<Vec<u8>>,
}
@@ -590,17 +590,9 @@ fn padded_named((sx, sy): (u64, u64), channels: u64) -> Vec<u8> {
.collect()
}
/// Metal's store of padded words: each word's low six bits zeroed.
fn padded_stored(bytes: &[u8]) -> Vec<u8> {
bytes
.chunks(2)
.flat_map(|w| (u16::from_le_bytes([w[0], w[1]]) & !0x3f).to_le_bytes())
.collect()
}
/// The cases: `R10Unorm_X6` and `RG10Unorm_X12` drawn in codes 341 and 682 (the color
/// `(1/3, 2/3, 0, 1)`, exactly), and `BGR10_XR` under an empty write mask, its bits 30 and 31
/// zero or one by texel (Metal's store sets them).
/// zero or one by texel (Metal's store would set them).
fn unused_bits_cases() -> [UnusedBitsCase; 3] {
[
UnusedBitsCase {
@@ -608,7 +600,6 @@ fn unused_bits_cases() -> [UnusedBitsCase; 3] {
texel: 2,
mask: ColorWriteMask::ALL,
named: |at| padded_named(at, 1),
stored: padded_stored,
drawn: Some((341u16 << 6).to_le_bytes().to_vec()),
},
UnusedBitsCase {
@@ -616,7 +607,6 @@ fn unused_bits_cases() -> [UnusedBitsCase; 3] {
texel: 4,
mask: ColorWriteMask::ALL,
named: |at| padded_named(at, 2),
stored: padded_stored,
drawn: Some(
[341u16 << 6, 682 << 6]
.iter()
@@ -633,10 +623,6 @@ fn unused_bits_cases() -> [UnusedBitsCase; 3] {
let top = (sx + 2 * sy) % 4;
((top << 30 | codes) as u32).to_le_bytes().to_vec()
},
stored: |bytes| {
let word = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
(word | 0xc000_0000).to_le_bytes().to_vec()
},
drawn: None,
},
]
@@ -645,28 +631,21 @@ fn unused_bits_cases() -> [UnusedBitsCase; 3] {
/// Rotated textures of `R10Unorm_X6`, `RG10Unorm_X12` and `BGR10_XR` ([`unused_bits_cases`]), of
/// every rotation, a frame of one 32x32 tile and one of two each way, over planes whose texels
/// name their stored position: a pass that loads the texture and draws its top-left 8x4 texels
/// stores the drawn texels where the mask writes them and leaves every other texel's codes where
/// a load and a store put them (at rotation 4 the mirror [`loaded_from`] gives), the bits they
/// leave unused as Metal's store makes them (a padded word's low six bits zeroed, `BGR10_XR`'s bits
/// 30 and 31 set), the bytes between rows kept. That is Metal's store in each tile the draw
/// reaches (on an M4 and the consumer's runs of them on an M3 Max; the
/// turns): the runtime rewrites the twin of the pass's frame after its copy in, so no pass
/// announces `extended-range-bits-kept`. In a frame of two tiles the one the draw does not reach is
/// rewritten as well, where Metal keeps its texels' bytes (`unreached-tiles-rewritten`, announced
/// by each such pass), but where capture replay found the draw's reach (a texture that is not a
/// rotated frame, once its capture form is made): that pass keeps it, Metal's answer, and announces
/// nothing.
/// stores the drawn texels where the mask writes them and leaves every other texel's bytes where
/// a load and a store put them (at rotation 4 the mirror [`loaded_from`] gives), the bits their
/// codes leave unused as they were, the bytes between rows kept: the device's store, where
/// Metal's makes those bits canonical in each tile the draw reaches (a padded word's low six bits
/// zeroed, `BGR10_XR`'s bits 30 and 31 set). Each pass announces `extended-range-bits-kept`.
#[test]
fn unused_bits_of_rotated_textures_are_metals() {
use super::extended_range_blends::{EXTENDED_RANGE_BITS, UNREACHED_TILES};
fn unused_bits_of_rotated_textures_are_kept() {
use super::extended_range_blends::EXTENDED_RANGE_BITS;
let cache = ScratchCache::new().unwrap();
let messages = Messages::default();
// Each pass's announcement says which reach it took (below).
let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| {
options.announce_each = UNREACHED_TILES.into_iter().collect();
options.announce_each = EXTENDED_RANGE_BITS.into_iter().collect();
})
.unwrap();
let mut announced = 0;
let lane = Lane::new(&device);
let color: Vec<u8> = [1.0f32 / 3.0, 2.0 / 3.0, 0.0, 1.0]
.iter()
@@ -695,7 +674,7 @@ fn unused_bits_of_rotated_textures_are_metals() {
for sx in 0..sw {
put(&mut before, (sx, sy), &(case.named)((sx, sy)));
let from = loaded_from(rotation, sw, (sx, sy));
put(&mut want, (sx, sy), &(case.stored)(&(case.named)(from)));
put(&mut want, (sx, sy), &(case.named)(from));
}
}
if let Some(drawn) = &case.drawn {
@@ -727,39 +706,19 @@ fn unused_bits_of_rotated_textures_are_metals() {
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
// A pass whose draws' reach capture replay found (a texture that is not a
// rotated frame, once its capture form is made: `render/capture.rs`) rewrites the
// tile the draw reaches alone and keeps every other texel's bytes, Metal's answer;
// one that announces rewrites every tile.
let counted = super::degrade_notices::counts(&messages.take_notices());
assert_eq!(
counted.get(&EXTENDED_RANGE_BITS[0]),
None,
Some(&1),
"{what}: {counted:?}"
);
let reached = |(x, y): (u64, u64)| x < 32 && y < 32;
if counted.contains_key(&UNREACHED_TILES[0]) {
announced += 1;
} else {
let mut exact = before.clone();
for y in 0..h {
for x in (0..w).filter(|&x| reached((x, y))) {
let (sx, sy) = stored_at(rotation, (w, h), (x, y));
let at = (sy * bpr + sx * case.texel) as usize;
let texel = at..at + case.texel as usize;
exact[texel.clone()].copy_from_slice(&want[texel]);
}
}
want = exact;
}
if let Some(at) = first_difference(&bytes_of(&plane), &want, bpr) {
panic!("{what}: {at} (texels counted as 4 bytes)");
}
eprintln!("ROTATED-UNUSED-BITS {what}: Metal's bytes");
eprintln!("ROTATED-UNUSED-BITS {what}: the kept bytes");
}
}
}
assert!(announced > 0, "a frame of two tiles announces");
quiet(&messages);
}
@@ -11,7 +11,7 @@
//!
//! The runtime keeps the device's load and store, so the texels keep their codes and words, and
//! a draw in such a pass announces `snorm-minimum-kept` or `shared-exponent-kept`, naming the
//! attachment, with no load pass. On a driver whose pass stores them as Metal's
//! attachment. On a driver whose pass stores them as Metal's
//! (`DriverFact::TileStoreIsMetals`: MoltenVK, whose pass is a Metal pass) the texels take Metal's
//! codes and words, and nothing is announced.
@@ -113,17 +113,11 @@ fn metals_store(lane: &Lane) -> bool {
.contains(&DriverFact::TileStoreIsMetals)
}
/// The load passes the lane's device recorded so far.
fn load_passes(lane: &Lane) -> u64 {
lane.device.work_counts().unused_bits_load_passes
}
/// A pass that loads a 4² target of each signed normalized format holding the minimum code in
/// every channel and draws under a write mask of none of its channels, recording no load pass:
/// where the device's store is Metal's, every texel takes the code above and nothing is
/// every channel and draws under a write mask of none of its channels: where the device's store is Metal's, every texel takes the code above and nothing is
/// announced; else every code stays and `snorm-minimum-kept` is announced once (the device asks
/// for it at each occurrence), naming color 0 and its format. A pass that loads the minimum codes
/// again and draws nothing keeps every one, records no load pass and announces nothing, as
/// again and draws nothing keeps every one and announces nothing, as
/// Metal's keeps every texel.
#[test]
fn a_drawing_pass_keeps_a_snorm_minimum_code_and_says_so() {
@@ -138,15 +132,12 @@ fn a_drawing_pass_keeps_a_snorm_minimum_code_and_says_so() {
.new_render_pipeline_state(&unwritten(&lane, pf), &PipelineOptions::default())
.unwrap();
let (t, bytes) = minimum_codes(&lane, pf, texel, code);
let before = load_passes(&lane);
lane.run(&pass(&t, LoadAction::Load), |l, e, h| {
l.draw(e, h, &pipeline, 0.5)
})
.unwrap();
let loads = load_passes(&lane) - before;
let got = lane.read(&t, (0, 0), texel, BlitOption::None);
let notices = messages.take_notices();
assert_eq!(loads, 0, "{pf:?}: load passes");
if metals {
let raised = filled(texel, above);
assert!(got == raised, "{pf:?}: not Metal's codes: {got:02x?}");
@@ -166,13 +157,7 @@ fn a_drawing_pass_keeps_a_snorm_minimum_code_and_says_so() {
assert!(named, "{pf:?}: the notice names no color 0");
}
upload(&t, texel, &bytes);
let before = load_passes(&lane);
lane.run(&pass(&t, LoadAction::Load), |_, _, _| {}).unwrap();
assert_eq!(
load_passes(&lane),
before,
"{pf:?}: a pass of no draw's load pass"
);
let got = lane.read(&t, (0, 0), texel, BlitOption::None);
assert!(
got == bytes,
@@ -189,7 +174,7 @@ fn a_drawing_pass_keeps_a_snorm_minimum_code_and_says_so() {
/// A pass that loads a 4² `RGB9E5Float` target whose every word is unnormalized (mantissas 1, 2
/// and 3 under the exponent 20: its largest mantissa below 256) and draws under a write mask of
/// none of its channels, recording no load pass: where the device's store is Metal's, every word
/// none of its channels: where the device's store is Metal's, every word
/// takes Metal's (mantissas 128, 256 and 384 under the exponent 13) and nothing is announced;
/// else every word stays and `shared-exponent-kept` is announced once (the device asks for it at
/// each occurrence), naming color 0 and its format. A pass that loads it and draws nothing
@@ -232,15 +217,12 @@ fn a_drawing_pass_keeps_an_unnormalized_shared_exponent_word_and_says_so() {
let bytes = word.to_le_bytes().repeat((SIZE * SIZE) as usize);
t.replace_region(Region::new_2d(0, 0, SIZE, SIZE), 0, 0, &bytes, 4 * SIZE, 0)
.unwrap();
let before = load_passes(&lane);
lane.run(&pass(&t, LoadAction::Load), |l, e, h| {
l.draw(e, h, &pipeline, 0.5)
})
.unwrap();
let loads = load_passes(&lane) - before;
let got = lane.read(&t, (0, 0), 4, BlitOption::None);
let notices = messages.take_notices();
assert_eq!(loads, 0, "{pf:?} on {name}: load passes");
if metals {
let normalized = metal.to_le_bytes().repeat((SIZE * SIZE) as usize);
assert!(
@@ -1,656 +0,0 @@
//! The tile reach kernel (`bind::tile_reach_module`) on the device the cfg selects, under the
//! validation layer. Each pass of the product's fixture
//! (`fixtures/public/tile_reach/device_passes.txt`: every measured case drawn, each in a slice of
//! its own, and seeded random passes, with the rule's answers; the product's
//! `bind::tile_reach::tests::device` checks it is the rule's, and the kernel's through the CPU
//! interpreter) is dispatched on the device's own `VkQueue` (`CommandQueue::with_vk_queue`), over
//! three of the runtime's `Shared` buffers: the primitives, the header and states, and the mask,
//! cleared. Its mask's set bits and the header's two counts are the rule's, bit for bit. A device
//! without `shaderInt64` is refused `Feature::TileReach`, printed.
//!
//! The kernel's cost on a large pass is measured and printed (`TILEREACH-TIME`), not judged: two
//! seeded passes over a 3840 by 2160 target, a mesh of 18,432 triangles tiling it and a scatter of
//! 16,384 triangles, lines and points of every size. Each pass first runs 64 times back to back in
//! one submission, so the GPU leaves its idle clocks, and then 21 times alone and 32 times back to
//! back, timed by GPU timestamps about the dispatches where the queue writes them and by the
//! host's time from the submission to its fence; a pass of no primitives gives the dispatch's own
//! cost.
use super::degrade_notices::on_device;
use super::{buffer_with, read_buffer};
use crate::candidate::LoaderWord;
use crate::gpu::wait::{self, SubmissionBackend};
use crate::gpu::TEST_DEVICE;
use ash::vk;
use metal2vulkan::bind::{tile_reach_module, TileReachModule as M};
use metal2vulkan::error::{Error as TranslateError, Feature};
use metal2vulkan_runtime::{Buffer, CommandQueue, Device};
use std::time::{Duration, Instant};
/// The product's fixture (the module docs).
const FIXTURE: &str = include_str!("../../fixtures/public/tile_reach/device_passes.txt");
/// One pass of the fixture: the header's fields, the states' and primitives' words, and the
/// rule's answer.
#[derive(Debug, Default)]
struct Case {
area: [u32; 2],
samples: u32,
layers: u32,
states: Vec<u32>,
primitives: Vec<u32>,
near_far: u32,
unmeasured: u32,
bits: Vec<u32>,
}
impl Case {
fn count(&self) -> u32 {
(self.primitives.len() / M::PRIMITIVE_WORDS as usize) as u32
}
/// The pass buffer's bytes: the header, then the states.
fn pass_bytes(&self) -> Vec<u8> {
let header = M::header(self.area, self.samples, self.layers, self.count());
let states = self.states.iter().flat_map(|w| w.to_le_bytes());
header.into_iter().chain(states).collect()
}
}
/// The fixture's passes, in order.
fn cases() -> Vec<Case> {
let mut cases: Vec<Case> = Vec::new();
let number = |s: &str| s.parse::<u32>().expect("a number");
let word = |s: &str| u32::from_str_radix(s, 16).expect("a hex word");
for line in FIXTURE.lines().filter(|l| !l.starts_with('#')) {
let mut fields = line.split_whitespace();
let tag = fields.next().expect("a tag");
let rest: Vec<&str> = fields.collect();
if tag == "pass" {
let [w, h, samples, layers] = [0, 1, 2, 3].map(|i| number(rest[i]));
cases.push(Case {
area: [w, h],
samples,
layers,
..Case::default()
});
continue;
}
let case = cases.last_mut().expect("a pass first");
match tag {
"state" => case.states.extend(rest.iter().map(|s| word(s))),
"primitive" => case.primitives.extend(rest.iter().map(|s| word(s))),
"expect" => [case.near_far, case.unmeasured] = [0, 1].map(|i| number(rest[i])),
"bits" => case.bits.extend(rest.iter().map(|s| number(s))),
other => panic!("an unknown line {other:?}"),
}
}
cases
}
/// The test's Vulkan objects on the runtime's device: the kernel's pipeline, a descriptor set of
/// its three storage buffers, a command buffer, a fence and two timestamp queries. Destroyed on
/// drop, after its last submission was waited for.
struct Kernel {
driver: ash::Device,
word: LoaderWord,
module: vk::ShaderModule,
set_layout: vk::DescriptorSetLayout,
layout: vk::PipelineLayout,
pipeline: vk::Pipeline,
descriptors: vk::DescriptorPool,
set: vk::DescriptorSet,
pool: vk::CommandPool,
buffer: vk::CommandBuffer,
fence: vk::Fence,
queries: vk::QueryPool,
/// The queue family's `timestampValidBits` (0: it writes none) and the device's
/// `timestampPeriod`, nanoseconds a tick.
stamp_bits: u32,
period: f64,
}
/// What one dispatch took: the host's time from its submission to its fence, and the GPU's
/// between the timestamps about it, where the queue writes them.
#[derive(Clone, Copy, Debug)]
struct Took {
wall: Duration,
gpu: Option<Duration>,
}
impl Kernel {
/// Made on `device` before it submitted anything, so the loader word is the device's own.
fn new(device: &Device, spirv: &[u32]) -> Kernel {
// SAFETY: read while the device lives; the objects are destroyed in `drop`, before it.
let raw = unsafe { device.raw() };
let driver = raw.device.clone();
// SAFETY: the handle is the live device's.
let word = unsafe { LoaderWord::of_device(driver.handle()) };
let info = vk::ShaderModuleCreateInfo::default().code(spirv);
// SAFETY: the device is live; `info` points at the module's words for the call.
let module = unsafe { driver.create_shader_module(&info, None) }.unwrap();
let bindings = [M::PRIMITIVES_BINDING, M::PASS_BINDING, M::TILES_BINDING].map(|binding| {
vk::DescriptorSetLayoutBinding::default()
.binding(binding)
.descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
.descriptor_count(1)
.stage_flags(vk::ShaderStageFlags::COMPUTE)
});
let info = vk::DescriptorSetLayoutCreateInfo::default().bindings(&bindings);
// SAFETY: the device is live.
let set_layout = unsafe { driver.create_descriptor_set_layout(&info, None) }.unwrap();
let set_layouts = [set_layout];
let info = vk::PipelineLayoutCreateInfo::default().set_layouts(&set_layouts);
// SAFETY: the device is live.
let layout = unsafe { driver.create_pipeline_layout(&info, None) }.unwrap();
let stage = vk::PipelineShaderStageCreateInfo::default()
.stage(vk::ShaderStageFlags::COMPUTE)
.module(module)
.name(c"main");
let info = vk::ComputePipelineCreateInfo::default()
.stage(stage)
.layout(layout);
// SAFETY: the device is live; every pointer in `info` outlives the call.
let pipeline =
unsafe { driver.create_compute_pipelines(vk::PipelineCache::null(), &[info], None) }
.map_err(|(_, error)| error)
.unwrap()[0];
let sizes = [vk::DescriptorPoolSize::default()
.ty(vk::DescriptorType::STORAGE_BUFFER)
.descriptor_count(3)];
let info = vk::DescriptorPoolCreateInfo::default()
.max_sets(1)
.pool_sizes(&sizes);
// SAFETY: the device is live.
let descriptors = unsafe { driver.create_descriptor_pool(&info, None) }.unwrap();
let info = vk::DescriptorSetAllocateInfo::default()
.descriptor_pool(descriptors)
.set_layouts(&set_layouts);
// SAFETY: the device is live; the pool holds one set of the layout's.
let set = unsafe { driver.allocate_descriptor_sets(&info) }.unwrap()[0];
let info = vk::CommandPoolCreateInfo::default()
.queue_family_index(raw.queue_family)
.flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER);
// SAFETY: the device is live; the pool is the test's own.
let pool = unsafe { driver.create_command_pool(&info, None) }.unwrap();
let allocation = vk::CommandBufferAllocateInfo::default()
.command_pool(pool)
.level(vk::CommandBufferLevel::PRIMARY)
.command_buffer_count(1);
// SAFETY: the device is live; the loader serves the call after the word is put back.
let buffer = unsafe {
word.restore();
#[expect(
clippy::disallowed_methods,
reason = "the runtime's device, after the loader word is put back"
)]
let buffer = driver.allocate_command_buffers(&allocation);
buffer
}
.unwrap()[0];
// SAFETY: the device is live.
let fence = unsafe { driver.create_fence(&vk::FenceCreateInfo::default(), None) }.unwrap();
let info = vk::QueryPoolCreateInfo::default()
.query_type(vk::QueryType::TIMESTAMP)
.query_count(2);
// SAFETY: the device is live.
let queries = unsafe { driver.create_query_pool(&info, None) }.unwrap();
// SAFETY: instance-level queries of the live device's physical device.
let (stamp_bits, period) = unsafe {
let families = raw
.instance
.get_physical_device_queue_family_properties(raw.physical_device);
let limits = raw
.instance
.get_physical_device_properties(raw.physical_device)
.limits;
(
families[raw.queue_family as usize].timestamp_valid_bits,
f64::from(limits.timestamp_period),
)
};
Kernel {
driver,
word,
module,
set_layout,
layout,
pipeline,
descriptors,
set,
pool,
buffer,
fence,
queries,
stamp_bits,
period,
}
}
/// Bind `buffers` (primitives, pass, mask), dispatch `groups` workgroups `times` times back
/// to back (a barrier between) on `queue`'s `VkQueue` and wait for them: the mask and the
/// counts are then the host's to read. The times taken are the whole submission's.
fn run(&self, queue: &CommandQueue, buffers: [&Buffer; 3], groups: u32, times: u32) -> Took {
let driver = &self.driver;
let infos = buffers.map(|b| {
// SAFETY: the buffer lives past the submission, which is waited for below.
let (handle, offset) = unsafe { b.vk_buffer() };
[vk::DescriptorBufferInfo::default()
.buffer(handle)
.offset(offset)
.range(b.length())]
});
let bindings = [M::PRIMITIVES_BINDING, M::PASS_BINDING, M::TILES_BINDING];
let writes: Vec<vk::WriteDescriptorSet<'_>> = (0..3)
.map(|i| {
vk::WriteDescriptorSet::default()
.dst_set(self.set)
.dst_binding(bindings[i])
.descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
.buffer_info(&infos[i])
})
.collect();
let after = vk::MemoryBarrier::default()
.src_access_mask(vk::AccessFlags::SHADER_WRITE)
.dst_access_mask(vk::AccessFlags::HOST_READ);
let begin = vk::CommandBufferBeginInfo::default()
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
// SAFETY: the set and the command buffer are the test's own and not in use (the last
// submission was waited for); the buffers are live and no work of the runtime's touches
// them (the host wrote them, which the submission makes visible).
unsafe {
driver.update_descriptor_sets(&writes, &[]);
driver.begin_command_buffer(self.buffer, &begin).unwrap();
driver.cmd_reset_query_pool(self.buffer, self.queries, 0, 2);
driver.cmd_bind_pipeline(self.buffer, vk::PipelineBindPoint::COMPUTE, self.pipeline);
driver.cmd_bind_descriptor_sets(
self.buffer,
vk::PipelineBindPoint::COMPUTE,
self.layout,
M::SET,
&[self.set],
&[],
);
let top = vk::PipelineStageFlags::TOP_OF_PIPE;
driver.cmd_write_timestamp(self.buffer, top, self.queries, 0);
for at in 0..times {
if at > 0 {
let between = vk::MemoryBarrier::default()
.src_access_mask(vk::AccessFlags::SHADER_WRITE)
.dst_access_mask(
vk::AccessFlags::SHADER_READ | vk::AccessFlags::SHADER_WRITE,
);
let compute = vk::PipelineStageFlags::COMPUTE_SHADER;
driver.cmd_pipeline_barrier(
self.buffer,
compute,
compute,
vk::DependencyFlags::empty(),
&[between],
&[],
&[],
);
}
driver.cmd_dispatch(self.buffer, groups, 1, 1);
}
let bottom = vk::PipelineStageFlags::BOTTOM_OF_PIPE;
driver.cmd_write_timestamp(self.buffer, bottom, self.queries, 1);
driver.cmd_pipeline_barrier(
self.buffer,
vk::PipelineStageFlags::COMPUTE_SHADER,
vk::PipelineStageFlags::HOST,
vk::DependencyFlags::empty(),
&[after],
&[],
&[],
);
driver.end_command_buffer(self.buffer).unwrap();
}
let buffers = [self.buffer];
let submit = vk::SubmitInfo::default().command_buffers(&buffers);
let submitted = Instant::now();
// SAFETY: the command buffer is executable and the fence unsignaled; the submission is
// made under the runtime's lock of its `VkQueue`, and the call waits for nothing.
unsafe {
queue.with_vk_queue(|raw, _| driver.queue_submit(raw, &[submit], self.fence).unwrap());
}
let backend = SubmissionBackend::vulkan(TEST_DEVICE);
let operation = "the tile reach kernel's dispatch";
wait::vulkan::wait_for_fence(driver, self.fence, backend, operation).unwrap();
let wall = submitted.elapsed();
let gpu = (self.stamp_bits > 0).then(|| {
let mut stamps = [0u64; 2];
// SAFETY: the submission that wrote both queries completed.
unsafe {
driver.get_query_pool_results(
self.queries,
0,
&mut stamps,
vk::QueryResultFlags::TYPE_64,
)
}
.unwrap();
let mask = match self.stamp_bits {
64.. => u64::MAX,
bits => (1 << bits) - 1,
};
let ticks = stamps[1].wrapping_sub(stamps[0]) & mask;
Duration::from_nanos((ticks as f64 * self.period).round() as u64)
});
// SAFETY: the submission completed: the fence and the command buffer are free.
unsafe {
driver.reset_fences(&[self.fence]).unwrap();
driver
.reset_command_buffer(self.buffer, vk::CommandBufferResetFlags::empty())
.unwrap();
}
Took { wall, gpu }
}
}
impl Drop for Kernel {
fn drop(&mut self) {
// SAFETY: nothing of the test's is pending (each submission was waited for).
unsafe {
self.word.restore();
self.driver.destroy_query_pool(self.queries, None);
self.driver.destroy_fence(self.fence, None);
self.driver.destroy_command_pool(self.pool, None);
self.driver.destroy_descriptor_pool(self.descriptors, None);
self.driver.destroy_pipeline(self.pipeline, None);
self.driver.destroy_pipeline_layout(self.layout, None);
self.driver
.destroy_descriptor_set_layout(self.set_layout, None);
self.driver.destroy_shader_module(self.module, None);
}
}
}
/// The set bits of little-endian mask words.
fn set_bits(bytes: &[u8]) -> Vec<u32> {
let mut bits = Vec::new();
for (i, w) in bytes.as_chunks::<4>().0.iter().enumerate() {
let w = u32::from_le_bytes(*w);
bits.extend(
(0..32)
.filter(|b| w >> b & 1 == 1)
.map(|b| 32 * i as u32 + b),
);
}
bits
}
/// Every pass of the fixture binned on the device: its mask's set bits and the header's near-far
/// and unmeasured counts are the rule's (the module docs).
#[test]
fn the_tile_reach_kernel_bins_the_fixture_as_the_rule_does() {
on_device(|device, _messages| {
let module = match tile_reach_module(device.compile_device()) {
Ok(module) => module,
Err(TranslateError::Unsupported(u)) if u.feature == Feature::TileReach => {
eprintln!("TILEREACH: refused on a device without shaderInt64: {u:?}");
return;
}
Err(error) => panic!("tile_reach_module: {error}"),
};
let kernel = Kernel::new(device, &module.spirv);
let queue = device.new_command_queue().unwrap();
let cases = cases();
let mut wrong = Vec::new();
let mut primitives = 0;
for (at, case) in cases.iter().enumerate() {
let prims: Vec<u8> = case
.primitives
.iter()
.flat_map(|w| w.to_le_bytes())
.collect();
let words = M::mask_words(case.area, case.samples, case.layers).max(1) as usize;
let prims = buffer_with(device, &prims).unwrap();
let pass = buffer_with(device, &case.pass_bytes()).unwrap();
let tiles = buffer_with(device, &vec![0; 4 * words]).unwrap();
let groups = case.count().div_ceil(M::LOCAL_SIZE).max(1);
kernel.run(&queue, [&prims, &pass, &tiles], groups, 1);
let header = read_buffer(&pass, 0, 4 * u64::from(M::HEADER_WORDS)).unwrap();
let count = |w: u32| {
let at = 4 * w as usize;
u32::from_le_bytes(header[at..at + 4].try_into().expect("a word"))
};
let mask = read_buffer(&tiles, 0, 4 * words as u64).unwrap();
let got = (
count(M::NEAR_FAR_WORD),
count(M::UNMEASURED_WORD),
set_bits(&mask),
);
let want = (case.near_far, case.unmeasured, case.bits.clone());
if got != want {
let differ: Vec<_> = got
.2
.iter()
.filter(|b| !want.2.contains(b))
.chain(want.2.iter().filter(|b| !got.2.contains(b)))
.take(16)
.collect();
wrong.push(format!(
"pass {at} ({:?}, {} samples): counts {:?}, the rule's {:?}; bits differing \
(first 16) {differ:?}",
case.area,
case.samples,
(got.0, got.1),
(want.0, want.1)
));
}
primitives += case.count();
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
eprintln!(
"TILEREACH: {} passes, {primitives} primitives: the rule's on {}",
cases.len(),
device.name()
);
});
}
/// The timed passes' target (the module docs).
const TARGET: [u32; 2] = [3840, 2160];
/// A seeded generator (splitmix64) of the timed passes.
struct Seeded(u64);
impl Seeded {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
}
/// A value in `[lo, hi)`.
fn within(&mut self, lo: f64, hi: f64) -> f64 {
lo + (hi - lo) * (self.next() >> 11) as f64 / (1u64 << 53) as f64
}
}
/// The clip-space position of the target's pixel `(x, y)` at `w` and depth `z / w` (the whole
/// target's viewport).
fn clip_at(x: f64, y: f64, z: f64, w: f64) -> [f32; 4] {
let [tw, th] = TARGET.map(f64::from);
let xn = 2.0 * x / tw - 1.0;
let yn = 1.0 - 2.0 * y / th;
[(xn * w) as f32, (yn * w) as f32, (z * w) as f32, w as f32]
}
/// A timed pass: its primitives' and its pass buffer's bytes, and its count.
struct Large {
what: &'static str,
prims: Vec<u8>,
count: u32,
}
impl Large {
/// The pass buffer: the header and the one state (the whole target, no culling, depth
/// clipped), of `count` primitives.
fn pass_bytes(&self, count: u32) -> Vec<u8> {
let [w, h] = TARGET;
let viewport = [0.0, 0.0, w as f32, h as f32];
let state = M::state(viewport, [0, 0, w, h], 0, 0, 0);
let header = M::header(TARGET, 1, 1, count);
header.into_iter().chain(state).collect()
}
}
/// A mesh of two triangles a cell of 30 by 30 pixels tiling the target, its depth `w` rising
/// from 1 to 4 across it.
fn mesh() -> Large {
let (cols, rows) = (TARGET[0] / 30, TARGET[1] / 30);
let corner = |c: u32, r: u32| {
let w = 1.0 + 3.0 * f64::from(c) / f64::from(cols);
clip_at(f64::from(30 * c), f64::from(30 * r), 0.5, w)
};
let mut prims = Vec::new();
for r in 0..rows {
for c in 0..cols {
let [a, b, d, e] = [
corner(c, r),
corner(c + 1, r),
corner(c, r + 1),
corner(c + 1, r + 1),
];
prims.extend(M::primitive(M::TRIANGLE, 0, 0, 0.0, [a, b, d]));
prims.extend(M::primitive(M::TRIANGLE, 0, 0, 0.0, [b, e, d]));
}
}
Large {
what: "mesh",
count: 2 * cols * rows,
prims,
}
}
/// 16,384 primitives about the target and past its edges: nine in ten triangles of sides from
/// one pixel to 400 (3% across the near plane), the rest lines and points, at depths `w` from
/// 0.5 to 8.
fn scatter() -> Large {
let mut rng = Seeded(0x7111_e7e5);
let count = 16_384;
let [tw, th] = TARGET.map(f64::from);
let mut prims = Vec::new();
for _ in 0..count {
let (cx, cy) = (rng.within(-64.0, tw + 64.0), rng.within(-64.0, th + 64.0));
let size = rng.within(0.0, 400f64.ln()).exp();
let w = rng.within(0.5, 8.0);
let kind = rng.within(0.0, 1.0);
let crossing = rng.within(0.0, 1.0) < 0.03;
let mut vertex = |z: f64| {
let x = cx + size * rng.within(-1.0, 1.0);
let y = cy + size * rng.within(-1.0, 1.0);
clip_at(x, y, z, w)
};
let prim = if kind < 0.9 {
let first = vertex(if crossing { -0.3 } else { 0.5 });
M::primitive(M::TRIANGLE, 0, 0, 0.0, [first, vertex(0.5), vertex(0.5)])
} else if kind < 0.95 {
let ends = [vertex(0.5), vertex(0.5)];
M::primitive(M::LINE, 0, 0, 0.0, [ends[0], ends[1], [0.0; 4]])
} else {
let at = vertex(0.5);
let size = rng.within(1.0, 64.0) as f32;
M::primitive(M::POINT, 0, 0, size, [at, [0.0; 4], [0.0; 4]])
};
prims.extend(prim);
}
Large {
what: "scatter",
count,
prims,
}
}
/// The median and the least of `durations`, in microseconds.
fn spread(mut durations: Vec<Duration>) -> (f64, f64) {
durations.sort();
let us = |d: Duration| d.as_secs_f64() * 1e6;
(us(durations[durations.len() / 2]), us(durations[0]))
}
/// The kernel's cost on the large passes (the module docs): printed, `TILEREACH-TIME`.
#[test]
fn the_tile_reach_kernel_times_a_large_pass() {
const WARM: u32 = 64;
const RUNS: usize = 21;
const BATCH: u32 = 32;
on_device(|device, _messages| {
let module = match tile_reach_module(device.compile_device()) {
Ok(module) => module,
Err(TranslateError::Unsupported(u)) if u.feature == Feature::TileReach => {
eprintln!("TILEREACH-TIME: refused on a device without shaderInt64: {u:?}");
return;
}
Err(error) => panic!("tile_reach_module: {error}"),
};
let kernel = Kernel::new(device, &module.spirv);
let queue = device.new_command_queue().unwrap();
let words = M::mask_words(TARGET, 1, 1) as usize;
let tiles = TARGET[0].div_ceil(32) * TARGET[1].div_ceil(32);
for large in [mesh(), scatter()] {
let prims = buffer_with(device, &large.prims).unwrap();
for (count, what) in [(0, "none"), (large.count, large.what)] {
let mut walls = Vec::with_capacity(RUNS);
let mut gpus = Vec::with_capacity(RUNS);
let mut reached = (0, 0, 0);
let groups = count.div_ceil(M::LOCAL_SIZE).max(1);
let mask = buffer_with(device, &vec![0; 4 * words]).unwrap();
let pass = buffer_with(device, &large.pass_bytes(count)).unwrap();
kernel.run(&queue, [&prims, &pass, &mask], groups, WARM);
let batch = kernel.run(&queue, [&prims, &pass, &mask], groups, BATCH);
for _ in 0..RUNS {
let pass = buffer_with(device, &large.pass_bytes(count)).unwrap();
let mask = buffer_with(device, &vec![0; 4 * words]).unwrap();
let took = kernel.run(&queue, [&prims, &pass, &mask], groups, 1);
walls.push(took.wall);
gpus.extend(took.gpu);
let header = read_buffer(&pass, 0, 4 * u64::from(M::HEADER_WORDS)).unwrap();
let word = |w: u32| {
let at = 4 * w as usize;
u32::from_le_bytes(header[at..at + 4].try_into().expect("a word"))
};
let bits = read_buffer(&mask, 0, 4 * words as u64).unwrap();
let set = set_bits(&bits).len();
reached = (set, word(M::NEAR_FAR_WORD), word(M::UNMEASURED_WORD));
}
if what == "mesh" {
assert_eq!(
reached.0, tiles as usize,
"a mesh tiling the target reaches it all"
);
}
let (wall, wall_least) = spread(walls);
let per = |d: Duration| d.as_secs_f64() * 1e6 / f64::from(BATCH);
let gpu = match (gpus.len(), batch.gpu) {
(0, _) | (_, None) => "no timestamps".to_string(),
(_, Some(back_to_back)) => {
let (median, least) = spread(gpus);
format!(
"GPU median {median:.1} us, least {least:.1} us, {:.1} us a \
dispatch back to back",
per(back_to_back)
)
}
};
eprintln!(
"TILEREACH-TIME: {what}: {count} primitives over {}x{} on {}: {gpu}; \
submission to fence median {wall:.1} us, least {wall_least:.1} us, \
{:.1} us a dispatch back to back ({RUNS} runs alone, {BATCH} back to \
back, after {WARM}); {} of {tiles} tiles, near-far {}, unmeasured {}",
TARGET[0],
TARGET[1],
device.name(),
per(batch.wall),
reached.0,
reached.1,
reached.2
);
}
}
});
}
@@ -14,19 +14,17 @@
//! (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.
//!
//! 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 device biases and converts every depth: the runtime records Metal's constant in the
//! device's own 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:
//! MoltenVK (1.4.1, an M4), which hands Metal its constant, takes both. RADV (Mesa 26.2.4, the
//! Radeon 780M) and ANV (Mesa 26.2.4) stored every unbiased code Metal's (the first). 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.
@@ -1,345 +0,0 @@
//! The tile reach primitives of a pass's capture draws: the step between capture replay and
//! [`tile_reach_module`](super::tile_reach_module).
//!
//! Capture replay draws each kept draw of a pass again before it, under the capture form of its
//! vertex function, which writes one record a vertex invocation. [`capture_assembly_module`]
//! assembles those records into the pass's primitives as Metal's input assembly does, one tile
//! reach [`primitive`](super::TileReachModule::primitive) record each, which
//! [`tile_reach_module`](super::tile_reach_module) then bins; [`capture_settle_module`] turns the
//! mask it binned into every tile where it counted a primitive near-far or unmeasured (the
//! announced fallback).
//!
//! **The assembly module** (one per device). One `GLCompute` entry `main` with local size
//! ([`CaptureAssemblyModule::LOCAL_SIZE`], 1, 1), no push constants, and three storage buffers of
//! 4-byte words in set 0:
//!
//! - [`RECORDS_BINDING`](CaptureAssemblyModule::RECORDS_BINDING): the capture records, each
//! [`RECORD_WORDS`](CaptureAssemblyModule::RECORD_WORDS) words
//! ([`record`](CaptureAssemblyModule::record)): the clip-space position (four `f32`s), the point
//! size (an `f32`), and a word that is not zero where the vertex's raw index restarts its strip
//! (an indexed draw's index of the index type's all-ones value), then two unused words. The
//! capture form writes vertex `p` of instance `n` (counted from the draw's first instance) of a
//! draw of `count` vertices or indices at the draw's first slot plus `p + n * count`.
//! - [`DRAWS_BINDING`](CaptureAssemblyModule::DRAWS_BINDING): a header of
//! [`HEADER_WORDS`](CaptureAssemblyModule::HEADER_WORDS) words
//! ([`header`](CaptureAssemblyModule::header)): the entries' count and the primitives' total;
//! then the entries, each [`DRAW_WORDS`](CaptureAssemblyModule::DRAW_WORDS) words
//! ([`draw`](CaptureAssemblyModule::draw)), one per instance of each draw, in order:
//!
//! | Word | Contents |
//! |---|---|
//! | 0 | the entry's first primitive: the primitives of the entries before it |
//! | 1 | its primitives ([`primitives`](CaptureAssemblyModule::primitives) of its topology and records) |
//! | 2 | its first record: the slot of the instance's vertex 0 |
//! | 3 | its records: the draw's vertex or index count |
//! | 4 | its topology: the raw `MTLPrimitiveType` ([`PrimitiveType`]) |
//! | 5 | 1 where it restarts: an indexed line or triangle strip (Metal restarts strips at a flagged record; lists and points draw every index), else 0 |
//! | 6 | 1 where it culls: its cull mode is front or back, else 0 |
//! | 7 | the index of the tile reach state it was drawn under |
//!
//! - [`PRIMITIVES_BINDING`](CaptureAssemblyModule::PRIMITIVES_BINDING): the pass's primitives,
//! [`PRIMITIVE_WORDS`](super::TileReachModule::PRIMITIVE_WORDS) words each, which the kernel
//! writes, the buffer [`tile_reach_module`](super::tile_reach_module) reads.
//!
//! **One entry per instance.** An entry covers one instance, so a primitive's place in its
//! entry is a subtraction: the kernel divides nothing (no integer division by a value it reads,
//! which [`tile_reach_module`](super::tile_reach_module)'s docs explain), and a draw of `n`
//! instances takes `n` entries. The host writes no entry of no primitives, so the entries never
//! outnumber the primitives: the draws' buffer holds at most half the primitives' bytes, plus
//! its header.
//!
//! **Invocation `i`** below the header's total (and the primitives the binding holds) finds its
//! entry by a binary search over the first primitives (the last entry whose first primitive is
//! at most `i`), takes `j = i` less that, and writes primitive `i` from the instance's records at
//! the entry's first record plus:
//!
//! - a point list: `j`, a [`POINT`](super::TileReachModule::POINT) of that record's point size;
//! - a line list: `2j`, `2j + 1`; a line strip: `j`, `j + 1` (each a
//! [`LINE`](super::TileReachModule::LINE));
//! - a triangle list: `3j`, `3j + 1`, `3j + 2`; a triangle strip: `j`, `j + 1`, `j + 2` where the
//! triangle's parity is even, `j`, `j + 2`, `j + 1` where it is odd (Vulkan's strip order, the
//! index rewrite's: every triangle keeps the strip's winding);
//!
//! with the entry's state, layer 0, and the first vertex's point size. A vertex unused by its
//! kind (a point's second and third, a line's third) is written as zeros.
//!
//! **Restart** (an entry that restarts, of a line or triangle strip). A primitive one of whose
//! records is flagged reaches nothing: it is written as a triangle of three equal finite vertices,
//! `(0, 0, 0, 1)`, of size 0. The rule has it reach no tile (zero area) and flags it nothing more
//! than its state flags every primitive drawn under it (inside both depth planes, before the
//! eye, at the viewport's centre; `tile_reach`'s test `assembly`, against the rule and the
//! kernel). A line strip's segment is written so too: a line of no length would count unmeasured.
//! A triangle strip's parity restarts after each flagged record (Metal's, measured,
//! `runtime/src/render/restart.rs`). Where the entry culls, a kept triangle's parity is that of
//! its distance from its piece's first record, the one after the last flagged record before `j`
//! (or the instance's vertex 0 where none is): the kernel scans back at most
//! [`SCAN_LIMIT`](CaptureAssemblyModule::SCAN_LIMIT) records before `j`. Where that passes no
//! flagged record and does not reach vertex 0, the parity is unknown, and the triangle is
//! written with three NaN vertices, which the rule counts unmeasured, so the pass falls back to
//! every tile (the settle module). Where the entry does not cull, a triangle reaches the same
//! tiles in either winding, and its parity is counted from vertex 0, with no scan.
//!
//! **Contained.** Every read and write lies inside its binding. An invocation past the
//! primitives the binding holds writes nothing. A primitive the entries do not describe (no
//! entry, `j` at or past the entry's primitives, a topology that is none) or whose records lie
//! past the entry's records or the records' binding is written as the triangle of NaN vertices:
//! counted unmeasured, never a guess.
//!
//! **The settle module** (one per device). One `GLCompute` entry `main` with local size
//! ([`CaptureSettleModule::LOCAL_SIZE`], 1, 1), no push constants, and three storage buffers in
//! set 0, numbered densely from 0 (as the runtime's owned kernels lay out their set):
//! [`STATUS_BINDING`](CaptureSettleModule::STATUS_BINDING), the command buffer's
//! [`ExecutionStatus`](super::ExecutionStatus) words;
//! [`PASS_BINDING`](CaptureSettleModule::PASS_BINDING), the pass's header and states, read; and
//! [`TILES_BINDING`](CaptureSettleModule::TILES_BINDING), the tile mask (the last two the
//! buffers [`tile_reach_module`](super::tile_reach_module) binds at the same numbers). Where the
//! header's [`NEAR_FAR_WORD`](super::TileReachModule::NEAR_FAR_WORD) or
//! [`UNMEASURED_WORD`](super::TileReachModule::UNMEASURED_WORD) is not zero, invocation `i`, one
//! a word of the mask ([`mask_words`](super::TileReachModule::mask_words) of the header's render
//! area, samples and layers), ORs into word `i` the bits of every tile of the pass it holds (a
//! bit past the pass's last tile is left as it is), and invocation 0 ORs
//! [`CAPTURED_REACH_UNMEASURED`](super::StatusBits::CAPTURED_REACH_UNMEASURED) into the status
//! word, which [`captured_reach_unmeasured`](super::StatusReport::captured_reach_unmeasured)
//! reads back so the runtime can announce the fallback. Where both counts are zero it changes
//! nothing. Dispatch at least one workgroup, so invocation 0 runs.
//!
//! **Arithmetic.** Both kernels copy `f32`s as their bits and hold no float instruction, and
//! compute in `u32` alone: they need nothing of a Vulkan 1.2 device past what every one has.
//!
//! **Synchronization** (consumer): the capture draws' record writes (`SHADER_WRITE` in
//! `VERTEX_SHADER`) and the draws' upload → `SHADER_STORAGE_READ` in `COMPUTE_SHADER` before the
//! assembly; its writes → [`tile_reach_module`](super::tile_reach_module)'s reads; the tile
//! reach dispatch's writes → `SHADER_STORAGE_READ` and `SHADER_STORAGE_WRITE` in `COMPUTE_SHADER`
//! before the settle; its writes → the mask's readers, and the status buffer's reader as every
//! writer of it (`bind::status`).
use std::sync::Arc;
use super::index_bounds::finished;
use crate::device::requirements::Requirements;
use crate::device::Device;
use crate::error::Error;
use crate::metal::PrimitiveType;
use crate::pipeline::sym::Symbol;
mod kernel;
/// The word positions within the assembly's records ([`CaptureAssemblyModule`]).
mod layout {
/// A capture record's: the position (four `f32`s), the point size, the restart word.
pub(super) const POSITION: u32 = 0;
pub(super) const POINT_SIZE: u32 = 4;
pub(super) const RESTART: u32 = 5;
/// The draws' header's: the entries' count and the primitives' total.
pub(super) const ENTRIES: u32 = 0;
pub(super) const TOTAL: u32 = 1;
/// An entry's (the module docs' table).
pub(super) const FIRST_PRIMITIVE: u32 = 0;
pub(super) const PRIMITIVES: u32 = 1;
pub(super) const FIRST_RECORD: u32 = 2;
pub(super) const RECORDS: u32 = 3;
pub(super) const TOPOLOGY: u32 = 4;
pub(super) const RESTARTS: u32 = 5;
pub(super) const CULLS: u32 = 6;
pub(super) const STATE: u32 = 7;
}
/// The clip-space vertex, as `f32` bits, of the triangle a primitive that reaches nothing is
/// written as (the module docs): `(0, 0, 0, 1)`.
pub(in crate::bind) const NOTHING: [u32; 4] = [0, 0, 0, 0x3f80_0000];
/// The clip-space vertex, as `f32` bits, of the triangle a primitive whose reach is unknown is
/// written as (the module docs): four quiet NaNs.
pub(in crate::bind) const UNKNOWN: [u32; 4] = [0x7fc0_0000; 4];
/// The crate-owned capture assembly module of one device (the module docs), validated like any
/// output.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CaptureAssemblyModule {
/// SPIR-V 1.5 words, entry point `main`, its bindings numbered as below in set 0.
pub spirv: Arc<[u32]>,
/// What the module needs from the device: within every Vulkan 1.2 device.
pub requirements: Requirements,
}
impl CaptureAssemblyModule {
/// Descriptor set of the bindings.
pub const SET: u32 = 0;
/// The capture records, a storage buffer the kernel reads.
pub const RECORDS_BINDING: u32 = 0;
/// The draws' header and entries, a storage buffer the kernel reads.
pub const DRAWS_BINDING: u32 = 1;
/// The pass's primitives, a storage buffer the kernel writes (the buffer tile reach binds at
/// [`PRIMITIVES_BINDING`](super::TileReachModule::PRIMITIVES_BINDING)).
pub const PRIMITIVES_BINDING: u32 = 2;
/// Invocations of one workgroup, along x: one primitive each.
pub const LOCAL_SIZE: u32 = 64;
/// A capture record's words ([`record`](Self::record)): 32 bytes.
pub const RECORD_WORDS: u32 = 8;
/// The draws' header's words ([`header`](Self::header)), before the entries.
pub const HEADER_WORDS: u32 = 2;
/// An entry's words ([`draw`](Self::draw)).
pub const DRAW_WORDS: u32 = 8;
/// The most records the kernel scans back from a kept triangle of a restarting triangle
/// strip that culls, for the last flagged record before it (the module docs).
pub const SCAN_LIMIT: u32 = 256;
/// A capture record's bytes, as the capture form writes them: the clip-space `position`
/// (`[[position]]`), the `point_size` (`[[point_size]]`; any value where the function writes
/// none), and whether the vertex's raw index restarts its strip (1 or 0), then two words of
/// zeros.
pub fn record(position: [f32; 4], point_size: f32, restart: bool) -> [u8; 32] {
let mut words = [0; Self::RECORD_WORDS as usize];
for (c, value) in position.iter().enumerate() {
words[layout::POSITION as usize + c] = value.to_bits();
}
words[layout::POINT_SIZE as usize] = point_size.to_bits();
words[layout::RESTART as usize] = u32::from(restart);
bytes_of(words)
}
/// The draws' header's bytes: the count of `entries` that follow it, and the `total` of their
/// primitives (the invocations that write one).
pub fn header(entries: u32, total: u32) -> [u8; 8] {
let mut words = [0; Self::HEADER_WORDS as usize];
words[layout::ENTRIES as usize] = entries;
words[layout::TOTAL as usize] = total;
bytes_of(words)
}
/// An entry's bytes, one instance of a draw: its `first_primitive` (the primitives of the
/// entries before it), the slot of its vertex 0 among the records (`first_record`), its
/// `records` (the draw's vertex or index count), its `topology`, whether it `restarts` (an
/// indexed strip, whose flagged records restart it; ignored for a list or points), whether
/// its cull mode `culls` (front or back), and the index of the tile reach `state` it was drawn
/// under. Its primitives are [`primitives`](Self::primitives) of its topology and records.
pub fn draw(
first_primitive: u32,
first_record: u32,
records: u32,
topology: PrimitiveType,
restarts: bool,
culls: bool,
state: u32,
) -> [u8; 32] {
let mut words = [0; Self::DRAW_WORDS as usize];
words[layout::FIRST_PRIMITIVE as usize] = first_primitive;
words[layout::PRIMITIVES as usize] = Self::primitives(topology, records);
words[layout::FIRST_RECORD as usize] = first_record;
words[layout::RECORDS as usize] = records;
words[layout::TOPOLOGY as usize] = topology.as_raw();
words[layout::RESTARTS as usize] = u32::from(restarts);
words[layout::CULLS as usize] = u32::from(culls);
words[layout::STATE as usize] = state;
bytes_of(words)
}
/// The primitives one instance of `records` vertices or indices of `topology` assembles
/// (with a strip's restarts among them: a primitive a restart drops is written as one that
/// reaches nothing).
pub fn primitives(topology: PrimitiveType, records: u32) -> u32 {
match topology {
PrimitiveType::Point => records,
PrimitiveType::Line => records / 2,
PrimitiveType::LineStrip => records.saturating_sub(1),
PrimitiveType::Triangle => records / 3,
PrimitiveType::TriangleStrip => records.saturating_sub(2),
}
}
}
/// The crate-owned capture settle module of one device (the module docs), validated like any
/// output.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CaptureSettleModule {
/// SPIR-V 1.5 words, entry point `main`, its bindings numbered as below in set 0.
pub spirv: Arc<[u32]>,
/// What the module needs from the device: within every Vulkan 1.2 device.
pub requirements: Requirements,
}
impl CaptureSettleModule {
/// Descriptor set of the bindings, numbered densely from 0.
pub const SET: u32 = 0;
/// The command buffer's [`ExecutionStatus`](super::ExecutionStatus) words, a storage buffer
/// the kernel ORs
/// [`CAPTURED_REACH_UNMEASURED`](super::StatusBits::CAPTURED_REACH_UNMEASURED) into.
pub const STATUS_BINDING: u32 = 0;
/// The pass's header and states, a storage buffer the kernel reads (the buffer tile reach
/// binds at [`PASS_BINDING`](super::TileReachModule::PASS_BINDING)).
pub const PASS_BINDING: u32 = 1;
/// The tile mask, a storage buffer the kernel ORs bits into (the buffer tile reach binds at
/// [`TILES_BINDING`](super::TileReachModule::TILES_BINDING)).
pub const TILES_BINDING: u32 = 2;
/// Invocations of one workgroup, along x: one mask word each.
pub const LOCAL_SIZE: u32 = 64;
}
/// The little-endian bytes of `N` words.
fn bytes_of<const N: usize, const B: usize>(words: [u32; N]) -> [u8; B] {
let mut bytes = [0; B];
for (at, w) in words.iter().enumerate() {
bytes[4 * at..4 * at + 4].copy_from_slice(&w.to_le_bytes());
}
bytes
}
/// The fixed binding numbers of the assembly's symbols.
fn assembly_binding_of(sym: &Symbol) -> Option<u32> {
match sym {
Symbol::DescriptorSet(_) => Some(CaptureAssemblyModule::SET),
Symbol::Binding(s) if *s == kernel::RECORDS => Some(CaptureAssemblyModule::RECORDS_BINDING),
Symbol::Binding(s) if *s == kernel::DRAWS => Some(CaptureAssemblyModule::DRAWS_BINDING),
Symbol::Binding(s) if *s == kernel::PRIMITIVES => {
Some(CaptureAssemblyModule::PRIMITIVES_BINDING)
}
_ => None,
}
}
/// The fixed binding numbers of the settle's symbols.
fn settle_binding_of(sym: &Symbol) -> Option<u32> {
match sym {
Symbol::DescriptorSet(_) => Some(CaptureSettleModule::SET),
Symbol::Binding(s) if *s == kernel::PASS => Some(CaptureSettleModule::PASS_BINDING),
Symbol::Binding(s) if *s == kernel::TILES => Some(CaptureSettleModule::TILES_BINDING),
Symbol::Binding(s) if *s == kernel::STATUS => Some(CaptureSettleModule::STATUS_BINDING),
_ => None,
}
}
/// The capture assembly module of `device`: built with the typed builder, checked by the owned
/// verifier against the device's profile (requirements included), serialized, and numbered with
/// the fixed bindings of [`CaptureAssemblyModule`].
pub fn capture_assembly_module(device: &Device) -> Result<CaptureAssemblyModule, Error> {
let (spirv, requirements) = finished(
device,
kernel::assembly_typed_module()?,
assembly_binding_of,
"the capture assembly",
)?;
Ok(CaptureAssemblyModule {
spirv,
requirements,
})
}
/// The capture settle module of `device`: built with the typed builder, checked by the owned
/// verifier against the device's profile (requirements included), serialized, and numbered with
/// the fixed bindings of [`CaptureSettleModule`].
pub fn capture_settle_module(device: &Device) -> Result<CaptureSettleModule, Error> {
let (spirv, requirements) = finished(
device,
kernel::settle_typed_module()?,
settle_binding_of,
"the capture settle",
)?;
Ok(CaptureSettleModule {
spirv,
requirements,
})
}
#[cfg(test)]
mod tests;
@@ -1,731 +0,0 @@
//! The capture assembly and settle kernels: [`assembly_typed_module`] and
//! [`settle_typed_module`], which [`capture_assembly_module`](super::capture_assembly_module) and
//! [`capture_settle_module`](super::capture_settle_module) serialize and the CPU interpreter
//! runs, by the module docs' rules, step for step as the tests' reference assembly states them
//! (`tests.rs`).
//!
//! **No division and no float.** Each kernel copies `f32`s as their bits and computes in `u32`.
//! The records, entries, primitives and mask words a binding holds come by shifts (each record's
//! words are a power of two), an invocation's entry by a binary search, its place in the entry by
//! a subtraction (an entry is one instance), and a triangle's parity by a scan of at most
//! [`SCAN_LIMIT`](A::SCAN_LIMIT) records: nothing divides by a value it reads, which the tile
//! reach kernel's docs explain the price of.
use crate::bind::status::{StatusBits, StatusWord};
use crate::bind::tile_reach::{layout as reach, TileReachModule as R, AREA_LIMIT};
use crate::metal::PrimitiveType;
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, SyntheticBinding};
use crate::spirv::builder::constructs::{ArmEnd, ArmFn, LoopFn, LoopSpec};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{FuncId, GlobalId, TypeId, Value};
use crate::spirv::ir::{
natural_layout, AtomicOp, BinOp, ExecMode, ExecModel, IoDir, LayoutRule, MemAccess, Scope,
Semantics, StorageClass, Type, TypedModule, UnOp,
};
use super::{layout, CaptureAssemblyModule as A, CaptureSettleModule as S, NOTHING, UNKNOWN};
/// The binding symbols of the assembly's records, draws and primitives in its typed module.
pub(super) const RECORDS: ResourceSlot = slot(0);
pub(super) const DRAWS: ResourceSlot = slot(1);
pub(super) const PRIMITIVES: ResourceSlot = slot(2);
/// The binding symbols of the settle's pass, tile mask and `ExecutionStatus` words in its typed
/// module.
pub(super) const PASS: ResourceSlot = slot(0);
pub(super) const TILES: ResourceSlot = slot(1);
pub(super) const STATUS: ResourceSlot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Synthetic(SyntheticBinding::ExecutionStatus),
index: 0,
};
const fn slot(index: u32) -> ResourceSlot {
ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Buffer,
index,
}
}
/// The raw topologies (`MTLPrimitiveType`).
const POINTS: u32 = PrimitiveType::Point.as_raw();
const LINES: u32 = PrimitiveType::Line.as_raw();
const LINE_STRIP: u32 = PrimitiveType::LineStrip.as_raw();
const TRIANGLES: u32 = PrimitiveType::Triangle.as_raw();
const TRIANGLE_STRIP: u32 = PrimitiveType::TriangleStrip.as_raw();
/// The shift that counts a binding's records of `words` words, a power of two.
const fn shift(words: u32) -> u32 {
assert!(words.is_power_of_two());
words.trailing_zeros()
}
const RECORD_SHIFT: u32 = shift(A::RECORD_WORDS);
const DRAW_SHIFT: u32 = shift(A::DRAW_WORDS);
const PRIMITIVE_SHIFT: u32 = shift(R::PRIMITIVE_WORDS);
fn k32(f: &mut FunctionBuilder<'_>, v: u32) -> BResult<Value> {
let c = f.u32_const(v)?;
f.module().const_value(c)
}
fn op(f: &mut FunctionBuilder<'_>, o: BinOp, a: Value, b: Value) -> BResult<Value> {
f.binary(o, a, b)
}
/// `a o v` for a `u32` constant `v`.
fn opk(f: &mut FunctionBuilder<'_>, o: BinOp, a: Value, v: u32) -> BResult<Value> {
let c = k32(f, v)?;
f.binary(o, a, c)
}
fn sel(f: &mut FunctionBuilder<'_>, c: Value, a: Value, b: Value) -> BResult<Value> {
f.select(c, a, b)
}
fn and(f: &mut FunctionBuilder<'_>, a: Value, b: Value) -> BResult<Value> {
f.binary(BinOp::LogicalAnd, a, b)
}
fn or(f: &mut FunctionBuilder<'_>, a: Value, b: Value) -> BResult<Value> {
f.binary(BinOp::LogicalOr, a, b)
}
fn not(f: &mut FunctionBuilder<'_>, a: Value) -> BResult<Value> {
f.unary(UnOp::LogicalNot, a)
}
/// The smaller of two `u32`s.
fn umin(f: &mut FunctionBuilder<'_>, a: Value, b: Value) -> BResult<Value> {
let less = op(f, BinOp::ULessThan, a, b)?;
sel(f, less, a, b)
}
/// Whether a `u32` is not zero.
fn nonzero(f: &mut FunctionBuilder<'_>, a: Value) -> BResult<Value> {
opk(f, BinOp::INotEqual, a, 0)
}
fn load(f: &mut FunctionBuilder<'_>, p: Value) -> BResult<Value> {
f.load(p, MemAccess::default())
}
fn store(f: &mut FunctionBuilder<'_>, p: Value, v: Value) -> BResult<()> {
f.store(p, v, MemAccess::default())
}
/// A `Function` `u32` holding `v`, as its pointer.
fn local(f: &mut FunctionBuilder<'_>, u32_: TypeId, v: Value) -> BResult<Value> {
let var = f.local_var(u32_, None)?;
let p = f.var_ptr(var)?;
store(f, p, v)?;
Ok(p)
}
/// Word `i` (a `u32`) of a buffer of words, as a pointer.
fn word_ptr(f: &mut FunctionBuilder<'_>, buffer: Value, i: Value) -> BResult<Value> {
let zero = k32(f, 0)?;
f.access_chain(buffer, &[zero, i])
}
/// Word `i` (a `u32`) of a buffer of words.
fn word(f: &mut FunctionBuilder<'_>, buffer: Value, i: Value) -> BResult<Value> {
let p = word_ptr(f, buffer, i)?;
load(f, p)
}
/// Word `base + at` of a buffer of words.
fn field(f: &mut FunctionBuilder<'_>, buffer: Value, base: Value, at: u32) -> BResult<Value> {
let i = opk(f, BinOp::IAdd, base, at)?;
word(f, buffer, i)
}
/// Run `body` where `c` holds.
fn when<'a>(
f: &mut FunctionBuilder<'_>,
c: Value,
body: impl FnOnce(&mut FunctionBuilder<'_>) -> BResult<()> + 'a,
) -> BResult<()> {
let arm: ArmFn<'_, ()> = Box::new(move |f, _| {
body(f)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), c, arm, None)?;
Ok(())
}
/// Run `then` where `c` holds and `other` where it does not.
fn either<'a>(
f: &mut FunctionBuilder<'_>,
c: Value,
then: impl FnOnce(&mut FunctionBuilder<'_>) -> BResult<()> + 'a,
other: impl FnOnce(&mut FunctionBuilder<'_>) -> BResult<()> + 'a,
) -> BResult<()> {
let yes: ArmFn<'_, ()> = Box::new(move |f, _| {
then(f)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
let no: ArmFn<'_, ()> = Box::new(move |f, _| {
other(f)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), c, yes, Some(no))?;
Ok(())
}
/// Loop: each pass, leave where `stop` (computed first, at the top) holds, else run `body`.
fn repeat<'a>(
f: &mut FunctionBuilder<'_>,
stop: impl FnOnce(&mut FunctionBuilder<'_>) -> BResult<Value> + 'a,
body: impl FnOnce(&mut FunctionBuilder<'_>) -> BResult<()> + 'a,
) -> BResult<()> {
let walk: LoopFn<'_, ()> = Box::new(move |f, _, lc| {
let done = stop(f)?;
let leave: ArmFn<'_, ()> = Box::new(|f, _| {
lc.break_(f)?;
Ok(ArmEnd::Exits)
});
f.if_(&mut (), done, leave, None)?;
body(f)
});
f.loop_(&mut (), LoopSpec::default(), walk)
}
/// A `Block { u32 words[]; }` storage buffer bound at `sym`.
fn words_buffer(b: &mut ModuleBuilder, sym: ResourceSlot, u32_: TypeId) -> BResult<GlobalId> {
let rta = b.ty(Type::RuntimeArray {
elem: u32_,
stride: Some(4),
})?;
let layout = natural_layout(b.types(), LayoutRule::Std430, true, &[rta])?;
let block = b.ty(Type::Struct {
members: [rta].into(),
layout: Some(layout),
})?;
b.resource(sym, StorageClass::StorageBuffer, block)
}
/// The `u32` type and the `uvec3` of an invocation's id.
fn types(b: &mut ModuleBuilder) -> BResult<(TypeId, TypeId)> {
let u32_ = b.ty(Type::Int {
width: 32,
signed: false,
})?;
let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?;
Ok((u32_, uvec3))
}
/// Make `id` the `GLCompute` entry point of local size (`x`, 1, 1).
fn entry(b: &mut ModuleBuilder, id: FuncId, x: u32) -> BResult<()> {
b.entry(
ExecModel::GLCompute,
id,
vec![ExecMode::LocalSize { x, y: 1, z: 1 }],
)?;
Ok(())
}
/// The assembly as a typed module, before serialization: the module
/// [`capture_assembly_module`](super::capture_assembly_module) serializes, which the CPU
/// interpreter runs. Its bindings are the symbols `RECORDS`, `DRAWS` and `PRIMITIVES`.
pub(super) fn assembly_typed_module() -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let (u32_, uvec3) = types(&mut b)?;
let records = words_buffer(&mut b, RECORDS, u32_)?;
let draws = words_buffer(&mut b, DRAWS, u32_)?;
let prims = words_buffer(&mut b, PRIMITIVES, u32_)?;
let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let records = f.module().global_value(records)?;
let draws = f.module().global_value(draws)?;
let prims = f.module().global_value(prims)?;
let invocation = f.module().global_value(invocation)?;
assembly_body(&mut f, u32_, [records, draws, prims], invocation)?;
f.ret(None)?;
let id = f.finish()?;
entry(&mut b, id, A::LOCAL_SIZE)?;
b.finalize()
}
/// The assembly's buffers, and the whole records its records' binding holds.
#[derive(Clone, Copy)]
struct G {
u32_: TypeId,
records: Value,
draws: Value,
prims: Value,
held: Value,
}
/// An entry's words (the module docs' table).
#[derive(Clone, Copy)]
struct Entry {
first: Value,
primitives: Value,
first_record: Value,
records: Value,
topology: Value,
restarts: Value,
culls: Value,
state: Value,
}
/// The entry's body: invocation `i` below the header's total and the primitives the binding
/// holds writes primitive `i`, from its entry where the header names one, else unknown.
fn assembly_body(
f: &mut FunctionBuilder<'_>,
u32_: TypeId,
[records, draws, prims]: [Value; 3],
invocation: Value,
) -> BResult<()> {
let gid = load(f, invocation)?;
let i = f.composite_extract(gid, &[0])?;
let len = f.array_length(records, 0)?;
let g = G {
u32_,
records,
draws,
prims,
held: opk(f, BinOp::ShiftRightLogical, len, RECORD_SHIFT)?,
};
let len = f.array_length(prims, 0)?;
let out = opk(f, BinOp::ShiftRightLogical, len, PRIMITIVE_SHIFT)?;
let words = f.array_length(draws, 0)?;
let header = opk(f, BinOp::UGreaterThanEqual, words, A::HEADER_WORDS)?;
when(f, header, move |f| {
let at = k32(f, layout::TOTAL)?;
let total = word(f, g.draws, at)?;
let at = k32(f, layout::ENTRIES)?;
let named = word(f, g.draws, at)?;
let after = opk(f, BinOp::ISub, words, A::HEADER_WORDS)?;
let entries = opk(f, BinOp::ShiftRightLogical, after, DRAW_SHIFT)?;
let count = umin(f, named, entries)?;
let below = op(f, BinOp::ULessThan, i, total)?;
let fits = op(f, BinOp::ULessThan, i, out)?;
let go = and(f, below, fits)?;
when(f, go, move |f| {
let some = opk(f, BinOp::UGreaterThan, count, 0)?;
either(
f,
some,
move |f| {
let e = search(f, g, i, count)?;
let e = read_entry(f, g, e)?;
primitive(f, g, i, e)
},
move |f| {
let zero = k32(f, 0)?;
placeholder(f, g, i, zero, UNKNOWN)
},
)
})
})
}
/// The index of the last of the `count` (at least one) entries whose first primitive is at most
/// `i`, by a binary search (the entries' first primitives do not decrease): entry 0 where none
/// is.
fn search(f: &mut FunctionBuilder<'_>, g: G, i: Value, count: Value) -> BResult<Value> {
let zero = k32(f, 0)?;
let lo = local(f, g.u32_, zero)?;
let hi = local(f, g.u32_, count)?;
repeat(
f,
move |f| {
let l = load(f, lo)?;
let h = load(f, hi)?;
let span = op(f, BinOp::ISub, h, l)?;
opk(f, BinOp::ULessThanEqual, span, 1)
},
move |f| {
let l = load(f, lo)?;
let h = load(f, hi)?;
// Below 2^29 entries each: the sum does not wrap.
let mid = op(f, BinOp::IAdd, l, h)?;
let mid = opk(f, BinOp::ShiftRightLogical, mid, 1)?;
let base = entry_base(f, mid)?;
let first = field(f, g.draws, base, layout::FIRST_PRIMITIVE)?;
let up = op(f, BinOp::ULessThanEqual, first, i)?;
let l = sel(f, up, mid, l)?;
let h = sel(f, up, h, mid)?;
store(f, lo, l)?;
store(f, hi, h)
},
)?;
load(f, lo)
}
/// The first word of entry `e`.
fn entry_base(f: &mut FunctionBuilder<'_>, e: Value) -> BResult<Value> {
let at = opk(f, BinOp::ShiftLeftLogical, e, DRAW_SHIFT)?;
opk(f, BinOp::IAdd, at, A::HEADER_WORDS)
}
/// Entry `e`'s words.
fn read_entry(f: &mut FunctionBuilder<'_>, g: G, e: Value) -> BResult<Entry> {
let base = entry_base(f, e)?;
let mut w = |at: u32| field(f, g.draws, base, at);
Ok(Entry {
first: w(layout::FIRST_PRIMITIVE)?,
primitives: w(layout::PRIMITIVES)?,
first_record: w(layout::FIRST_RECORD)?,
records: w(layout::RECORDS)?,
topology: w(layout::TOPOLOGY)?,
restarts: w(layout::RESTARTS)?,
culls: w(layout::CULLS)?,
state: w(layout::STATE)?,
})
}
/// Words `at` of record `v` (a `u32`) of the entry's instance, and whether it is there: `v`
/// below the entry's records and its slot below the binding's records. A record not there reads
/// as zeros, and nothing is read.
fn fetch<const N: usize>(
f: &mut FunctionBuilder<'_>,
g: G,
e: &Entry,
v: Value,
at: [u32; N],
) -> BResult<([Value; N], Value)> {
let within = op(f, BinOp::ULessThan, v, e.records)?;
let slot = op(f, BinOp::IAdd, e.first_record, v)?;
let held = op(f, BinOp::ULessThan, slot, g.held)?;
let there = and(f, within, held)?;
let zero = k32(f, 0)?;
let mut vars = [zero; N];
for p in &mut vars {
*p = local(f, g.u32_, zero)?;
}
when(f, there, move |f| {
let base = opk(f, BinOp::ShiftLeftLogical, slot, RECORD_SHIFT)?;
for (p, at) in vars.into_iter().zip(at) {
let w = field(f, g.records, base, at)?;
store(f, p, w)?;
}
Ok(())
})?;
let mut words = [zero; N];
for (w, p) in words.iter_mut().zip(vars) {
*w = load(f, p)?;
}
Ok((words, there))
}
/// A vertex the primitive reads: its position's four words, its point size, whether it
/// restarts (a `bool`), and whether it is there.
#[derive(Clone, Copy)]
struct Vertex {
position: [Value; 4],
size: Value,
restart: Value,
there: Value,
}
/// Record `v` of the entry's instance as a vertex.
fn vertex(f: &mut FunctionBuilder<'_>, g: G, e: &Entry, v: Value) -> BResult<Vertex> {
let p = layout::POSITION;
let at = [p, p + 1, p + 2, p + 3, layout::POINT_SIZE, layout::RESTART];
let (w, there) = fetch(f, g, e, v, at)?;
Ok(Vertex {
position: [w[0], w[1], w[2], w[3]],
size: w[4],
restart: nonzero(f, w[5])?,
there,
})
}
/// Write primitive `i` of entry `e` (the module docs): its records, a restart's placeholder, or
/// the unknown one.
fn primitive(f: &mut FunctionBuilder<'_>, g: G, i: Value, e: Entry) -> BResult<()> {
let j = op(f, BinOp::ISub, i, e.first)?;
let in_entry = op(f, BinOp::ULessThan, j, e.primitives)?;
let named = opk(f, BinOp::ULessThanEqual, e.topology, TRIANGLE_STRIP)?;
let is = |f: &mut FunctionBuilder<'_>, t: u32| opk(f, BinOp::IEqual, e.topology, t);
let lines = is(f, LINES)?;
let triangles = is(f, TRIANGLES)?;
let line_strip = is(f, LINE_STRIP)?;
let triangle_strip = is(f, TRIANGLE_STRIP)?;
let point = is(f, POINTS)?;
// The primitive's first record: `j` times its records in a list, `j` in a strip or points.
let (k1, k2, k3) = (k32(f, 1)?, k32(f, 2)?, k32(f, 3)?);
let step = sel(f, triangles, k3, k1)?;
let step = sel(f, lines, k2, step)?;
let a = op(f, BinOp::IMul, j, step)?;
let b = opk(f, BinOp::IAdd, a, 1)?;
let c = opk(f, BinOp::IAdd, a, 2)?;
let two = not(f, point)?;
let three = or(f, triangles, triangle_strip)?;
let va = vertex(f, g, &e, a)?;
let vb = vertex(f, g, &e, b)?;
let vc = vertex(f, g, &e, c)?;
// Each vertex its kind reads is there.
let no_b = not(f, two)?;
let has_b = or(f, no_b, vb.there)?;
let no_c = not(f, three)?;
let has_c = or(f, no_c, vc.there)?;
let there = and(f, va.there, has_b)?;
let there = and(f, there, has_c)?;
let ok = and(f, in_entry, named)?;
let ok = and(f, ok, there)?;
// A restarting strip's primitive one of whose records is flagged reaches nothing.
let strip = or(f, line_strip, triangle_strip)?;
let restarts = nonzero(f, e.restarts)?;
let restarting = and(f, strip, restarts)?;
let touched = or(f, va.restart, vb.restart)?;
let c_flag = and(f, three, vc.restart)?;
let touched = or(f, touched, c_flag)?;
let nothing = and(f, restarting, touched)?;
// A triangle strip's parity: from vertex 0, or, where it restarts and culls, from its piece's
// first record, unknown past the scan.
let parity = opk(f, BinOp::BitwiseAnd, j, 1)?;
let parity = local(f, g.u32_, parity)?;
let zero = k32(f, 0)?;
let lost = local(f, g.u32_, zero)?;
let culls = nonzero(f, e.culls)?;
let scan = and(f, triangle_strip, restarting)?;
let scan = and(f, scan, culls)?;
let kept = not(f, nothing)?;
let scan = and(f, scan, kept)?;
let scan = and(f, scan, ok)?;
when(f, scan, move |f| {
let (odd, known) = piece_parity(f, g, &e, j)?;
store(f, parity, odd)?;
let (k0, k1) = (k32(f, 0)?, k32(f, 1)?);
let unknown = sel(f, known, k0, k1)?;
store(f, lost, unknown)
})?;
let odd = load(f, parity)?;
let odd = nonzero(f, odd)?;
let lost = load(f, lost)?;
let lost = nonzero(f, lost)?;
let fine = not(f, lost)?;
let fine = and(f, ok, fine)?;
either(
f,
fine,
move |f| {
either(
f,
nothing,
move |f| placeholder(f, g, i, e.state, NOTHING),
move |f| {
// Vulkan's strip order: an odd triangle takes its records `j, j + 2, j + 1`.
let swap = and(f, triangle_strip, odd)?;
let zero = k32(f, 0)?;
let mut second = [zero; 4];
let mut third = [zero; 4];
let pairs = vb.position.into_iter().zip(vc.position);
for ((s, t), (b, c)) in second.iter_mut().zip(&mut third).zip(pairs) {
let to_second = sel(f, swap, c, b)?;
*s = sel(f, two, to_second, zero)?;
let to_third = sel(f, swap, b, c)?;
*t = sel(f, three, to_third, zero)?;
}
let (kp, kl, kt) = (k32(f, R::POINT)?, k32(f, R::LINE)?, k32(f, R::TRIANGLE)?);
let kind = sel(f, three, kt, kl)?;
let kind = sel(f, point, kp, kind)?;
let vertices = [va.position, second, third];
emit(f, g, i, [kind, e.state, va.size], vertices)
},
)
},
move |f| placeholder(f, g, i, e.state, UNKNOWN),
)
}
/// Primitive `j`'s parity in its piece (1 where odd) and whether it is known (a `bool`): the
/// last flagged record within [`SCAN_LIMIT`](A::SCAN_LIMIT) records before `j` starts its piece
/// after it; with none, the piece starts at vertex 0, known where the scan reached it.
fn piece_parity(f: &mut FunctionBuilder<'_>, g: G, e: &Entry, j: Value) -> BResult<(Value, Value)> {
let bound = k32(f, A::SCAN_LIMIT)?;
let limit = umin(f, j, bound)?;
let (zero, one) = (k32(f, 0)?, k32(f, 1)?);
let back = local(f, g.u32_, one)?;
let found = local(f, g.u32_, zero)?;
let start = local(f, g.u32_, zero)?;
let e = *e;
repeat(
f,
move |f| {
let d = load(f, back)?;
let past = op(f, BinOp::UGreaterThan, d, limit)?;
let got = load(f, found)?;
let got = nonzero(f, got)?;
or(f, past, got)
},
move |f| {
let d = load(f, back)?;
let q = op(f, BinOp::ISub, j, d)?;
let ([flag], _) = fetch(f, g, &e, q, [layout::RESTART])?;
let flagged = nonzero(f, flag)?;
when(f, flagged, move |f| {
let one = k32(f, 1)?;
store(f, found, one)?;
let after = opk(f, BinOp::IAdd, q, 1)?;
store(f, start, after)
})?;
let next = opk(f, BinOp::IAdd, d, 1)?;
store(f, back, next)
},
)?;
let got = load(f, found)?;
let got = nonzero(f, got)?;
let near = op(f, BinOp::ULessThanEqual, j, bound)?;
let known = or(f, got, near)?;
let first = load(f, start)?;
let into = op(f, BinOp::ISub, j, first)?;
let odd = opk(f, BinOp::BitwiseAnd, into, 1)?;
Ok((odd, known))
}
/// Write primitive `i` as a triangle of three `vertex`es (`NOTHING` or `UNKNOWN`) of size 0,
/// under `state`.
fn placeholder(
f: &mut FunctionBuilder<'_>,
g: G,
i: Value,
state: Value,
vertex: [u32; 4],
) -> BResult<()> {
let kind = k32(f, R::TRIANGLE)?;
let size = k32(f, 0)?;
let mut v = [size; 4];
for (w, bits) in v.iter_mut().zip(vertex) {
*w = k32(f, bits)?;
}
emit(f, g, i, [kind, state, size], [v; 3])
}
/// Write primitive `i`'s record: its kind, state and size, layer 0, and its vertices.
fn emit(
f: &mut FunctionBuilder<'_>,
g: G,
i: Value,
[kind, state, size]: [Value; 3],
vertices: [[Value; 4]; 3],
) -> BResult<()> {
let base = opk(f, BinOp::ShiftLeftLogical, i, PRIMITIVE_SHIFT)?;
let zero = k32(f, 0)?;
let mut words = vec![
(reach::KIND, kind),
(reach::STATE, state),
(reach::LAYER, zero),
(reach::SIZE, size),
];
for (v, vertex) in vertices.iter().enumerate() {
for (c, &w) in vertex.iter().enumerate() {
words.push((reach::VERTICES + 4 * v as u32 + c as u32, w));
}
}
for (at, w) in words {
let to = opk(f, BinOp::IAdd, base, at)?;
let p = word_ptr(f, g.prims, to)?;
store(f, p, w)?;
}
Ok(())
}
/// The settle as a typed module, before serialization: the module
/// [`capture_settle_module`](super::capture_settle_module) serializes, which the CPU interpreter
/// runs. Its bindings are the symbols `PASS`, `TILES` and `STATUS`.
pub(super) fn settle_typed_module() -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let (u32_, uvec3) = types(&mut b)?;
let pass = words_buffer(&mut b, PASS, u32_)?;
let tiles = words_buffer(&mut b, TILES, u32_)?;
let status = words_buffer(&mut b, STATUS, u32_)?;
let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let pass = f.module().global_value(pass)?;
let tiles = f.module().global_value(tiles)?;
let status = f.module().global_value(status)?;
let invocation = f.module().global_value(invocation)?;
settle_body(&mut f, [pass, tiles, status], invocation)?;
f.ret(None)?;
let id = f.finish()?;
entry(&mut b, id, S::LOCAL_SIZE)?;
b.finalize()
}
/// The settle's body: where the header counted a primitive near-far or unmeasured, invocation
/// `i` below the pass's mask words and the binding's words ORs the bits of the pass's tiles in
/// word `i` into it, and invocation 0 ORs `CAPTURED_REACH_UNMEASURED` into the status word.
fn settle_body(
f: &mut FunctionBuilder<'_>,
[pass, tiles, status]: [Value; 3],
invocation: Value,
) -> BResult<()> {
let gid = load(f, invocation)?;
let i = f.composite_extract(gid, &[0])?;
let len = f.array_length(pass, 0)?;
let header = opk(f, BinOp::UGreaterThanEqual, len, R::HEADER_WORDS)?;
let held = f.array_length(tiles, 0)?;
when(f, header, move |f| {
let at = |f: &mut FunctionBuilder<'_>, w: u32| {
let w = k32(f, w)?;
word(f, pass, w)
};
let near_far = at(f, R::NEAR_FAR_WORD)?;
let unmeasured = at(f, R::UNMEASURED_WORD)?;
let near_far = nonzero(f, near_far)?;
let unmeasured = nonzero(f, unmeasured)?;
let fell = or(f, near_far, unmeasured)?;
let first = opk(f, BinOp::IEqual, i, 0)?;
let report = and(f, fell, first)?;
when(f, report, move |f| {
let at = k32(f, StatusWord::Status.index())?;
let p = word_ptr(f, status, at)?;
let bit = k32(f, StatusBits::CAPTURED_REACH_UNMEASURED.0)?;
f.atomic(AtomicOp::Or, p, Scope::Device, Semantics::RELAXED, bit)?;
Ok(())
})?;
// The pass's tiles (`TileReachModule::mask_words`): its render area binned at most
// `AREA_LIMIT` a side, in tiles of 32 by 32 pixels, 32 by 16 at 4 samples.
let samples = at(f, reach::SAMPLES)?;
let four = opk(f, BinOp::IEqual, samples, 4)?;
let (k4, k5) = (k32(f, 4)?, k32(f, 5)?);
let log = sel(f, four, k4, k5)?;
let limit = k32(f, AREA_LIMIT)?;
let mut sides = [log; 2];
for (side, (w, log)) in sides
.iter_mut()
.zip([(reach::AREA_W, k5), (reach::AREA_H, log)])
{
let extent = at(f, w)?;
let extent = umin(f, extent, limit)?;
let one = k32(f, 1)?;
let size = op(f, BinOp::ShiftLeftLogical, one, log)?;
let up = op(f, BinOp::IAdd, extent, size)?;
let up = opk(f, BinOp::ISub, up, 1)?;
*side = op(f, BinOp::ShiftRightLogical, up, log)?;
}
let layers = at(f, reach::LAYERS)?;
let count = op(f, BinOp::IMul, sides[0], sides[1])?;
let count = op(f, BinOp::IMul, count, layers)?;
let words = opk(f, BinOp::IAdd, count, 31)?;
let words = opk(f, BinOp::ShiftRightLogical, words, 5)?;
let inside = op(f, BinOp::ULessThan, i, words)?;
let bound = op(f, BinOp::ULessThan, i, held)?;
let go = and(f, inside, bound)?;
let go = and(f, go, fell)?;
when(f, go, move |f| {
// The tiles from word `i`'s first on: all 32 bits, or the low `rest`.
let first = opk(f, BinOp::ShiftLeftLogical, i, 5)?;
let rest = op(f, BinOp::ISub, count, first)?;
let full = opk(f, BinOp::UGreaterThanEqual, rest, 32)?;
let zero = k32(f, 0)?;
let by = sel(f, full, zero, rest)?;
let one = k32(f, 1)?;
let part = op(f, BinOp::ShiftLeftLogical, one, by)?;
let part = opk(f, BinOp::ISub, part, 1)?;
let all = k32(f, u32::MAX)?;
let bits = sel(f, full, all, part)?;
let p = word_ptr(f, tiles, i)?;
let old = load(f, p)?;
let new = op(f, BinOp::BitwiseOr, old, bits)?;
store(f, p, new)
})
})
}
@@ -1,691 +0,0 @@
//! The capture assembly and settle kernels against plain Rust references, through the CPU
//! interpreter in both invocation orders: the records' and entries' bytes; random draws of every
//! topology, instance counts, restarting strips with flagged records, culling on and off; the
//! scan's bound; entries that describe no primitive; the settle's two cases; and both modules
//! built and valid on every committed device. (That the placeholders reach nothing under the tile
//! reach rule is `tile_reach`'s test `assembly`.)
use std::path::PathBuf;
use super::kernel::{
assembly_typed_module, settle_typed_module, DRAWS, PASS, PRIMITIVES, RECORDS, STATUS, TILES,
};
use super::{
capture_assembly_module, capture_settle_module, CaptureAssemblyModule as A,
CaptureSettleModule as S, NOTHING, UNKNOWN,
};
use crate::bind::status::{ExecutionStatus, StatusBits, StatusWord};
use crate::bind::tile_reach::TileReachModule as R;
use crate::device::{Device, DeviceDescription, DevicePolicy};
use crate::metal::PrimitiveType;
use crate::pipeline::sym::ResourceSlot;
use crate::spirv::interp::{run, Buffer, Config, Order, Resources};
use crate::spirv::ir::TypedModule;
use crate::spirv::testing::assert_valid;
/// A splitmix64 stream.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
}
fn word(&mut self) -> u32 {
self.next() as u32
}
/// A number in `[0, n)`.
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
/// True `k` times in `n`.
fn chance(&mut self, k: u64, n: u64) -> bool {
self.below(n) < k
}
fn pick<X: Copy>(&mut self, xs: &[X]) -> X {
xs[self.below(xs.len() as u64) as usize]
}
}
/// Little-endian bytes as words.
fn words(bytes: &[u8]) -> Vec<u32> {
bytes
.as_chunks::<4>()
.0
.iter()
.map(|w| u32::from_le_bytes(*w))
.collect()
}
fn bytes(words: &[u32]) -> Vec<u8> {
words.iter().flat_map(|w| w.to_le_bytes()).collect()
}
fn buffer(slot: ResourceSlot, words: &[u32]) -> Buffer {
Buffer {
slot: Some(slot),
address: None,
bytes: bytes(words),
}
}
/// The topologies, by raw value.
const TOPOLOGIES: [PrimitiveType; 5] = [
PrimitiveType::Point,
PrimitiveType::Line,
PrimitiveType::LineStrip,
PrimitiveType::Triangle,
PrimitiveType::TriangleStrip,
];
/// What the assembly reads: the records, the draws' header and entries (words), and the
/// primitives' binding's words before the run.
#[derive(Clone, Debug)]
struct Batch {
records: Vec<[u32; 8]>,
draws: Vec<u32>,
out: Vec<u32>,
}
impl Batch {
/// A batch of `entries` (each [`A::DRAW_WORDS`] words) after a header naming `named` of
/// them and `total` primitives, its primitives' binding `out` words of a fill pattern.
fn of(records: Vec<[u32; 8]>, named: u32, total: u32, entries: &[[u32; 8]], out: u32) -> Batch {
let mut draws = words(&A::header(named, total));
draws.extend(entries.iter().flatten());
Batch {
records,
draws,
out: (0..out).map(|w| 0xa5a5_0000 | w).collect(),
}
}
/// The primitives' binding after the kernel ran, through the interpreter in both orders
/// (alike).
fn kernel(&self, m: &TypedModule) -> Vec<u32> {
let records: Vec<u32> = self.records.iter().flatten().copied().collect();
let total = self.draws.get(1).copied().unwrap_or(0);
let mut outs = Vec::new();
for order in [Order::Forward, Order::Reverse] {
let res = Resources {
buffers: vec![
buffer(RECORDS, &records),
buffer(DRAWS, &self.draws),
buffer(PRIMITIVES, &self.out),
],
push: Vec::new(),
spec: Default::default(),
};
let cfg = Config {
order,
workgroups: [total.div_ceil(A::LOCAL_SIZE).max(1), 1, 1],
step_limit: 1 << 40,
..Config::default()
};
outs.push(run(m, &cfg, res).expect("run").buffers);
}
assert_eq!(outs[0], outs[1], "order independent");
words(&outs[0][2])
}
/// The primitives' binding after the reference assembly: each primitive below the header's
/// total and the binding's whole primitives written by [`reference`].
fn rule(&self) -> Vec<u32> {
let mut out = self.out.clone();
if self.draws.len() < A::HEADER_WORDS as usize {
return out;
}
let (named, total) = (self.draws[0], self.draws[1]);
let entries: Vec<[u32; 8]> = self.draws[A::HEADER_WORDS as usize..]
.as_chunks::<{ A::DRAW_WORDS as usize }>()
.0
.iter()
.copied()
.take(named as usize)
.collect();
let fits = out.len() as u32 / R::PRIMITIVE_WORDS;
for i in 0..total.min(fits) {
let at = (i * R::PRIMITIVE_WORDS) as usize;
out[at..at + 16].copy_from_slice(&reference(&self.records, &entries, i));
}
out
}
/// Where the kernel and the reference differ, primitive by primitive.
fn differences(&self, m: &TypedModule) -> Vec<String> {
let (kernel, rule) = (self.kernel(m), self.rule());
if kernel == rule {
return Vec::new();
}
let mut out = Vec::new();
for (i, (k, r)) in kernel.chunks(16).zip(rule.chunks(16)).enumerate() {
if k != r {
out.push(format!(
"primitive {i}: kernel {k:08x?}, reference {r:08x?}"
));
}
}
if out.is_empty() {
out.push("the binding differs past its whole primitives".to_string());
}
out
}
}
/// A primitive's 16 words: its kind, state, layer 0, size and vertices.
fn primitive(kind: u32, state: u32, size: u32, vertices: [[u32; 4]; 3]) -> [u32; 16] {
let mut w = [0; 16];
w[0] = kind;
w[1] = state;
w[3] = size;
for (v, vertex) in vertices.iter().enumerate() {
w[4 + 4 * v..8 + 4 * v].copy_from_slice(vertex);
}
w
}
/// The triangle of three `vertex`es, of size 0, under `state`.
fn placeholder(vertex: [u32; 4], state: u32) -> [u32; 16] {
primitive(R::TRIANGLE, state, 0, [vertex; 3])
}
/// Metal's assembly of primitive `i` of the pass (the module docs), in plain Rust: from the last
/// entry whose first primitive is at most `i` (entry 0 where none is), its `j`th primitive's
/// records, by its topology; a restarting strip's primitive touching a flagged record reaches
/// nothing; a triangle strip's triangle takes its parity from its piece's first record, found
/// over the whole instance, where the entry restarts and culls, and is unknown where the last
/// flagged record before it lies more than the scan's bound back (or, with none, where `j` does);
/// anything the entries do not describe is unknown.
fn reference(records: &[[u32; 8]], entries: &[[u32; 8]], i: u32) -> [u32; 16] {
let Some(e) = entries.iter().rev().find(|e| e[0] <= i).or(entries.first()) else {
return placeholder(UNKNOWN, 0);
};
let [first, primitives, first_record, count, topology, restarts, culls, state] = *e;
let unknown = placeholder(UNKNOWN, state);
let j = i.wrapping_sub(first);
let record = |v: u32| -> Option<[u32; 8]> {
if v >= count {
return None;
}
let slot = first_record.checked_add(v)?;
records.get(slot as usize).copied()
};
let (n, a) = match TOPOLOGIES.iter().find(|t| t.as_raw() == topology) {
Some(PrimitiveType::Point) => (1, j),
Some(PrimitiveType::Line) => (2, j.wrapping_mul(2)),
Some(PrimitiveType::LineStrip) => (2, j),
Some(PrimitiveType::Triangle) => (3, j.wrapping_mul(3)),
Some(PrimitiveType::TriangleStrip) => (3, j),
None => return unknown,
};
if j >= primitives {
return unknown;
}
let Some(vs) = (0..n)
.map(|k| record(a.wrapping_add(k)))
.collect::<Option<Vec<_>>>()
else {
return unknown;
};
let strip = topology == PrimitiveType::LineStrip.as_raw()
|| topology == PrimitiveType::TriangleStrip.as_raw();
let restarting = strip && restarts != 0;
if restarting && vs.iter().any(|r| r[5] != 0) {
return placeholder(NOTHING, state);
}
let triangle_strip = topology == PrimitiveType::TriangleStrip.as_raw();
let mut odd = j % 2 == 1;
if triangle_strip && restarting && culls != 0 {
let flagged = |q: u32| record(q).is_some_and(|r| r[5] != 0);
let last = (0..j).rev().find(|&q| flagged(q));
let known = match last {
Some(f) => j - f <= A::SCAN_LIMIT,
None => j <= A::SCAN_LIMIT,
};
if !known {
return unknown;
}
odd = (j - last.map_or(0, |f| f + 1)) % 2 == 1;
}
let order = match triangle_strip && odd {
true => [0, 2, 1],
false => [0, 1, 2],
};
let kind = match n {
1 => R::POINT,
2 => R::LINE,
_ => R::TRIANGLE,
};
let mut vertices = [[0; 4]; 3];
for (slot, &k) in vertices.iter_mut().zip(&order).take(n as usize) {
slot.copy_from_slice(&vs[k][..4]);
}
primitive(kind, state, vs[0][4], vertices)
}
/// A record of random position and size words (any bits, or finite values), restarting where
/// `flag` (its restart word 1, or another value not zero).
fn random_record(rng: &mut Rng, flag: bool) -> [u32; 8] {
let mut position = [0f32; 4].map(|_| (rng.below(4001) as f32 - 2000.0) / 1000.0);
position[3] = 1.0;
let mut r = A::record(position, rng.below(64) as f32 / 4.0, flag);
if rng.chance(1, 8) {
r[..16].copy_from_slice(&bytes(&[0; 4].map(|_| rng.word())));
}
let mut w: [u32; 8] = words(&r).try_into().expect("a record");
if flag && rng.chance(1, 4) {
w[5] = rng.pick(&[2, 7, u32::MAX]);
}
w
}
/// A seeded batch: up to six draws of random topologies, 1 to 3 instances each, of a few to a
/// few hundred records (some strips longer than the scan's bound), restarting strips with
/// flagged records at several densities, culling or not, under a few states; records of an
/// instance sometimes after a gap; an entry of no primitives sometimes kept.
fn random_batch(rng: &mut Rng) -> Batch {
let mut records = Vec::new();
let mut entries = Vec::new();
let mut total = 0;
for _ in 0..1 + rng.below(6) {
let topology = rng.pick(&TOPOLOGIES);
let strip = matches!(
topology,
PrimitiveType::LineStrip | PrimitiveType::TriangleStrip
);
let long = match topology {
PrimitiveType::TriangleStrip => rng.chance(1, 3),
_ => rng.chance(1, 10),
};
let count = match long {
true => 240 + rng.below(160),
false => {
let below = rng.pick(&[4, 16, 16, 64, 64]);
rng.below(below)
}
} as u32;
let restarts = rng.chance(3, 4);
let culls = rng.chance(1, 2);
let density = rng.pick(&[0, 0, 2, 8, 40, 200]);
let state = rng.below(4) as u32;
for _ in 0..1 + rng.below(3) {
if rng.chance(1, 4) {
for _ in 0..rng.below(5) {
records.push(random_record(rng, false));
}
}
let first_record = records.len() as u32;
for _ in 0..count {
let flag = density != 0 && rng.chance(density, 1000);
records.push(random_record(rng, flag));
}
let primitives = A::primitives(topology, count);
if primitives == 0 && rng.chance(1, 2) {
continue;
}
let restarts = restarts && (strip || rng.chance(1, 2));
let e = A::draw(total, first_record, count, topology, restarts, culls, state);
entries.push(words(&e).try_into().expect("an entry"));
total += primitives;
}
}
let out = total * R::PRIMITIVE_WORDS + rng.below(20) as u32;
Batch::of(records, entries.len() as u32, total, &entries, out)
}
/// A capture record's bytes, the draws' header's and an entry's are the documented words, and an
/// instance's primitives are its topology's.
#[test]
fn the_records_and_entries_are_the_documented_words() {
let r = A::record([1.5, -2.0, 0.25, 1.0], 3.0, true);
assert_eq!(
words(&r),
[
1.5f32.to_bits(),
(-2.0f32).to_bits(),
0.25f32.to_bits(),
1.0f32.to_bits(),
3.0f32.to_bits(),
1,
0,
0
]
);
assert_eq!(words(&A::record([0.0; 4], 0.0, false))[5], 0);
assert_eq!(r.len(), 4 * A::RECORD_WORDS as usize);
assert_eq!(words(&A::header(7, 300)), [7, 300]);
let e = A::draw(40, 12, 9, PrimitiveType::TriangleStrip, true, false, 3);
assert_eq!(words(&e), [40, 7, 12, 9, 4, 1, 0, 3]);
let e = A::draw(0, 0, 9, PrimitiveType::Line, false, true, 0);
assert_eq!(words(&e), [0, 4, 0, 9, 1, 0, 1, 0]);
assert_eq!(e.len(), 4 * A::DRAW_WORDS as usize);
let primitives = |t: PrimitiveType| [0, 1, 2, 3, 7].map(|n| A::primitives(t, n));
assert_eq!(primitives(PrimitiveType::Point), [0, 1, 2, 3, 7]);
assert_eq!(primitives(PrimitiveType::Line), [0, 0, 1, 1, 3]);
assert_eq!(primitives(PrimitiveType::LineStrip), [0, 0, 1, 2, 6]);
assert_eq!(primitives(PrimitiveType::Triangle), [0, 0, 0, 1, 2]);
assert_eq!(primitives(PrimitiveType::TriangleStrip), [0, 0, 0, 1, 5]);
assert_eq!(NOTHING.map(f32::from_bits), [0.0, 0.0, 0.0, 1.0]);
assert!(UNKNOWN.iter().all(|&w| f32::from_bits(w).is_nan()));
}
/// On 48 seeded batches (every topology; 1 to 3 instances; restarting strips with flagged records
/// at several densities, culling or not; strips past the scan's bound; gaps between instances'
/// records; entries of no primitives), the kernel writes the reference's primitives.
#[test]
fn the_kernel_assembles_what_the_reference_does_on_random_draws() {
let m = assembly_typed_module().expect("module");
let mut rng = Rng(0xca97_0a55);
let mut wrong = Vec::new();
let (mut unknown, mut nothing) = (0, 0);
for _ in 0..48 {
let batch = random_batch(&mut rng);
let rule = batch.rule();
for p in rule.as_chunks::<16>().0.iter() {
unknown += usize::from(p[4..8] == UNKNOWN);
nothing += usize::from(p[4..8] == NOTHING && p[0] == R::TRIANGLE && p[3] == 0);
}
wrong.extend(batch.differences(&m));
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
assert!(
unknown > 0 && nothing > 0,
"{unknown} unknown, {nothing} nothing"
);
}
/// A restarting triangle strip that culls, of 1000 records flagged at 100 and 700, then an
/// instance flagged nowhere: each triangle touching a flag reaches nothing; a piece's triangles
/// take their parity from its first record (101: even, 102: odd); a triangle is known up to
/// [`A::SCAN_LIMIT`] records past the last flag (356 and 956) and unknown beyond (357, 957),
/// and, with no flag, up to that many past vertex 0. The same strip that does not cull has no
/// unknown triangle and counts parity from vertex 0; one that does not restart ignores the flags.
#[test]
fn a_culling_strip_s_parity_is_its_piece_s_within_the_scan() {
let m = assembly_typed_module().expect("module");
let mut rng = Rng(0x5ca7_1e55);
let count = 1000;
let mut records: Vec<[u32; 8]> = (0..count)
.map(|p| random_record(&mut rng, p == 100 || p == 700))
.collect();
records.extend((0..count).map(|_| random_record(&mut rng, false)));
let per = A::primitives(PrimitiveType::TriangleStrip, count);
for (restarts, culls) in [(true, true), (true, false), (false, true)] {
let entries: Vec<[u32; 8]> = (0..2)
.map(|n| {
let e = A::draw(
n * per,
n * count,
count,
PrimitiveType::TriangleStrip,
restarts,
culls,
5,
);
words(&e).try_into().expect("an entry")
})
.collect();
let batch = Batch::of(records.clone(), 2, 2 * per, &entries, 2 * per * 16);
let out = batch.kernel(&m);
assert_eq!(out, batch.rule(), "restarts {restarts}, culls {culls}");
let at = |i: u32| &out[16 * i as usize..16 * i as usize + 16];
let is = |i: u32, v: [u32; 4]| at(i)[4..8] == v;
let order = |i: u32| -> Vec<u32> {
(0..3)
.map(|v| {
let w = &at(i)[4 + 4 * v..8 + 4 * v];
(0..count)
.find(|&q| records[q as usize][..4] == *w)
.expect("a record's position")
})
.collect()
};
let unknown: Vec<u32> = (0..2 * per).filter(|&i| is(i, UNKNOWN)).collect();
let nothing: Vec<u32> = (0..2 * per).filter(|&i| is(i, NOTHING)).collect();
match (restarts, culls) {
(true, true) => {
assert_eq!(nothing, [98, 99, 100, 698, 699, 700]);
assert_eq!(order(101), [101, 102, 103]);
assert_eq!(order(102), [102, 104, 103]);
assert_eq!(order(97), [97, 99, 98]);
assert!(!is(356, UNKNOWN) && is(357, UNKNOWN));
assert!(!is(956, UNKNOWN) && is(957, UNKNOWN));
let unflagged = (per + 257..2 * per).count();
let expect = (357..698).count() + (957..per).count() + unflagged;
assert_eq!(unknown.len(), expect);
assert!(!is(per + 256, UNKNOWN) && is(per + 257, UNKNOWN));
}
(true, false) => {
assert_eq!(nothing, [98, 99, 100, 698, 699, 700]);
assert!(unknown.is_empty());
assert_eq!(order(101), [101, 103, 102]);
}
(false, _) => {
assert!(nothing.is_empty() && unknown.is_empty());
assert_eq!(order(101), [101, 103, 102]);
}
}
}
}
/// Entries that describe no primitive, and bindings that hold less than the header names: the
/// kernel writes the unknown triangle (no entry, a topology that is none, primitives past the
/// entry's records or the records' binding) and nothing past the primitives' binding or without
/// a header, as the reference does.
#[test]
fn what_the_entries_do_not_describe_is_unknown() {
let m = assembly_typed_module().expect("module");
let mut rng = Rng(0x0dd5_e575);
let records: Vec<[u32; 8]> = (0..12).map(|_| random_record(&mut rng, false)).collect();
let raw = |first, primitives, first_record, count, topology, state| {
[
first,
primitives,
first_record,
count,
topology,
0,
0,
state,
]
};
let triangles = PrimitiveType::Triangle.as_raw();
// Each case, the unknown primitives it writes, and the batch.
let cases: Vec<(&str, usize, Batch)> = vec![
("no entry", 3, Batch::of(records.clone(), 0, 3, &[], 48)),
(
"topologies that are none",
3,
Batch::of(
records.clone(),
3,
3,
&[
raw(0, 1, 0, 3, 5, 1),
raw(1, 1, 0, 3, 7, 2),
raw(2, 1, 0, 3, u32::MAX, 3),
],
48,
),
),
(
"primitives past the entry's records",
2,
Batch::of(records.clone(), 1, 4, &[raw(0, 4, 0, 6, triangles, 1)], 64),
),
(
"records past the binding",
1,
Batch::of(records.clone(), 1, 3, &[raw(0, 3, 6, 9, triangles, 2)], 48),
),
(
"a first primitive past the invocation's",
2,
Batch::of(records.clone(), 1, 3, &[raw(2, 3, 0, 9, triangles, 4)], 48),
),
(
"more entries named than held",
0,
Batch::of(records.clone(), 9, 3, &[raw(0, 3, 0, 9, triangles, 4)], 48),
),
(
"a total past the primitives' binding",
0,
Batch::of(records.clone(), 1, 4, &[raw(0, 4, 0, 12, triangles, 4)], 40),
),
];
let mut wrong = Vec::new();
for (what, unknown, batch) in cases {
let rule = batch.rule();
let written = rule
.as_chunks::<16>()
.0
.iter()
.filter(|p| p[4..8] == UNKNOWN)
.count();
if written != unknown {
wrong.push(format!(
"{what}: the reference writes {written} unknown, not {unknown}"
));
}
wrong.extend(
batch
.differences(&m)
.into_iter()
.map(|d| format!("{what}: {d}")),
);
}
let mut short = Batch::of(records, 1, 3, &[raw(0, 3, 0, 9, triangles, 4)], 48);
short.draws.truncate(1);
assert_eq!(short.kernel(&m), short.out, "no header: nothing written");
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
}
/// The settle on passes of render areas past and within the bound, 1, 2 and 4 samples and
/// several layers: where neither count is set the mask and the status are unchanged; where the
/// near-far or the unmeasured count is, every tile's bit of the pass is set, the last word's to
/// its last tile, the words past the pass's mask are unchanged, and the status reports
/// `captured_reach_unmeasured` beside the bits it held.
#[test]
fn the_settle_sets_every_tile_where_a_count_is_set() {
let m = settle_typed_module().expect("module");
let mut rng = Rng(0x5e77_1e00);
let passes = [
([100, 70], 1, 1),
([300, 300], 4, 3),
([20000, 100], 1, 1),
([33, 31], 2, 5),
([1, 1], 4, 1),
([4096, 2048], 1, 2),
];
for (area, samples, layers) in passes {
let rows = if samples == 4 { 16 } else { 32 };
let [w, h] = area.map(|a: u32| a.min(16384));
let tiles = w.div_ceil(32) * h.div_ceil(rows) * layers;
let mask = R::mask_words(area, samples, layers);
assert_eq!(mask, tiles.div_ceil(32));
for (near_far, unmeasured) in [(0, 0), (3, 0), (0, 1), (2, 5)] {
let mut pass = words(&R::header(area, samples, layers, 9));
pass[R::NEAR_FAR_WORD as usize] = near_far;
pass[R::UNMEASURED_WORD as usize] = unmeasured;
pass.extend(words(&R::state([0.0; 4], [0; 4], 0, 0, 0)));
let before: Vec<u32> = (0..mask + 3).map(|_| rng.word() & rng.word()).collect();
// Another writer's bit, kept.
let mut status = words(&ExecutionStatus::initial());
status[StatusWord::Status.index() as usize] = StatusBits::OVERFLOW.0;
let mut outs = Vec::new();
for order in [Order::Forward, Order::Reverse] {
let res = Resources {
buffers: vec![
buffer(PASS, &pass),
buffer(TILES, &before),
buffer(STATUS, &status),
],
push: Vec::new(),
spec: Default::default(),
};
let cfg = Config {
order,
workgroups: [(mask + 3).div_ceil(S::LOCAL_SIZE), 1, 1],
step_limit: 1 << 32,
..Config::default()
};
outs.push(run(&m, &cfg, res).expect("run").buffers);
}
assert_eq!(outs[0], outs[1], "order independent");
let after = words(&outs[0][1]);
let fell = near_far != 0 || unmeasured != 0;
let expect: Vec<u32> = before
.iter()
.enumerate()
.map(|(i, &old)| {
let first = 32 * i as u32;
let bits = match tiles.saturating_sub(first) {
0 => 0,
rest if rest >= 32 => u32::MAX,
rest => (1 << rest) - 1,
};
match fell {
true => old | bits,
false => old,
}
})
.collect();
let case = format!("{area:?} {samples} {layers} {near_far} {unmeasured}");
assert_eq!(after, expect, "{case}");
let report: [u8; ExecutionStatus::BYTES] = outs[0][2].clone().try_into().expect("32");
let report = ExecutionStatus::decode(&report);
assert_eq!(report.captured_reach_unmeasured, fell, "{case}");
assert!(report.overflow, "{case}");
}
}
}
/// Every committed device (`validation/profiles/*.json`), derived with the default policy, by
/// file stem.
fn committed_devices() -> Vec<(String, Device)> {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-validation/profiles");
let mut out = Vec::new();
for entry in std::fs::read_dir(&dir).expect("profiles") {
let path = entry.expect("entry").path();
if path.extension().is_none_or(|x| x != "json") {
continue;
}
let stem = path
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let text = std::fs::read_to_string(&path).expect("read");
let desc = DeviceDescription::from_khronos_json(&text, None).expect("description");
let device = Device::new(desc, DevicePolicy::default()).expect("device");
out.push((stem, device));
}
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
/// On every committed device (those the tile reach module's device tests derive) both modules are
/// built, valid and within the profile: they need nothing past Vulkan 1.2.
#[test]
fn both_modules_are_valid_on_every_committed_device() {
let devices = committed_devices();
assert!(!devices.is_empty());
for (name, device) in devices {
let profile = device.profile();
let assembly = capture_assembly_module(&device).unwrap_or_else(|e| panic!("{name}: {e}"));
assert!(!assembly.spirv.is_empty(), "{name}");
assert!(profile.check(&assembly.requirements).is_ok(), "{name}");
assert_valid(assembly_typed_module().expect("module"), profile);
let settle = capture_settle_module(&device).unwrap_or_else(|e| panic!("{name}: {e}"));
assert!(!settle.spirv.is_empty(), "{name}");
assert!(profile.check(&settle.requirements).is_ok(), "{name}");
assert_valid(settle_typed_module().expect("module"), profile);
}
}
+97 -197
View File
@@ -118,7 +118,7 @@
//! sample, no depth or stencil attachment, no rasterizer discard, no memory the vertex or
//! fragment function writes, no attachment in the storage form or input attachment, no
//! imageblock, tile memory, shader-side stencil or tests, no interlocked or shadowed colors, no
//! capture form, no tessellation or mesh stages, and no amplified or layered draw. Every other
//! tessellation or mesh stages, and no amplified or layered draw. Every other
//! slot the shape names is left out, and the plan's `variant.snapshot_textures` says which it
//! kept. Its plan binds each slot's snapshot (`WriteSource::SnapshotTexels`) and leaves which of
//! the two draws runs to the consumer (`PushHole::SnapshotPhase`, zero in the plan's bytes);
@@ -157,20 +157,6 @@
//! without the early-tests variant, runs the variant whose function runs both,
//! `VariantKey::shader_stencil`, in a pass with a depth and a stencil attachment; a pass with a
//! stencil attachment alone is `NotImplemented(FramebufferFetch)` at it.)
//! - **Capture form**. A pipeline compiled under `VariantKey::captured_positions`
//! (`RuntimeFact::CapturedPositions`), which a consumer asks for and no bind shape does, plans
//! its own variant. Its draws leave `PushHole::CaptureAddress` to the consumer (the first
//! record's address) and write `PushField::CaptureLayout` from the draw. A direct draw
//! without an index buffer is the vertices form's: its first vertex, vertex count, first
//! instance and 0. A direct indexed draw is the indexed form's: it runs without indices as
//! `index count` vertices from 0 with its instances, its layout `[restarts, index count, base
//! instance, base vertex]` (`restarts` 1 for a line or triangle strip, from
//! `BindState::primitive_type`; `MissingPrimitiveType` without one), leaves
//! `PushHole::CaptureIndexAddress` to the consumer (its first index's address), and reads its
//! indices in the vertex stage as storage (`DrawCommands::uses`).
//! A draw of the other form is `NeedsVariant` with that form; an indexed draw whose indices run
//! past its buffer or whose index offset is not a multiple of the index size, an indirect draw,
//! and an amplified one are `NotImplemented(TileReach)`.
//! - **Draws.** A Metal draw maps to the Vulkan draw of the same arguments; an indirect draw is
//! GPU-side unless a stage reads `BaseVertexInstance` from push constants or the plan is
//! multiview, in which case `indirect_needs_arguments` asks for the CPU read.
@@ -179,9 +165,10 @@
//! primitive (`BindState::primitive_type`; `MissingPrimitiveType` without one), a direct or
//! indirect draw's alike. An indexed draw of such a pipeline, whose vertices primitives share,
//! runs its de-indexed variant of the draw's index type (`BindShape::primitive_id_indices`,
//! `VariantKey::primitive_id_indices`) as the indexed capture form's draw: `index count`
//! vertices from 0, layout `[0, index count, base instance, base vertex]`, its indices read in
//! the vertex stage at `PushHole::CaptureIndexAddress`; any other draw of that variant is
//! `VariantKey::primitive_id_indices`): `index count` vertices from 0 with its instances,
//! layout `[0, index count, base instance, base vertex]` (`PushField::CaptureLayout`), leaving
//! `PushHole::CaptureIndexAddress` to the consumer (its first index's address), and reading its
//! indices in the vertex stage as storage (`DrawCommands::uses`); any other draw of that variant is
//! `NeedsVariant` without it. A strip, an indirect indexed draw, indices past their buffer and
//! an indexed draw of a plan without the form are `NotImplemented(PrimitiveId)`. A draw of one
//! of Metal's private primitive types in the private list form (`BindShape::private_list`,
@@ -354,7 +341,7 @@ use crate::pipeline::sym::{
Axis, DispatchKeys, PushField, SlotClass, SlotRef, SpecKey, Stage, SyntheticBinding,
};
use crate::pipeline::vertex::{VertexAttribute, VertexStride};
use crate::pipeline::{AmplificationDraws, CaptureForm, ViewportCompensation};
use crate::pipeline::{AmplificationDraws, ViewportCompensation};
use crate::vk;
/// A Metal draw call.
@@ -486,7 +473,7 @@ pub struct DrawCommands {
/// dynamic strides makes static pipeline state.
pub vertex_strides: Vec<(u32, u32)>,
/// The draw's own resources beyond the plan's `uses`: its index buffer and indirect
/// arguments. A capture variant's indexed draw reads its indices in the vertex stage as storage
/// arguments. A de-indexed draw reads its indices in the vertex stage as storage
/// (`VERTEX_SHADER`, from the index offset over its indices), by address, and binds no index
/// buffer.
pub uses: Vec<ResourceUse>,
@@ -1116,15 +1103,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
.iter()
.any(|f| f.field == PushField::AmplificationLayerOffset)
});
// A capture variant's record slots name a vertex and an instance, not a view or an
// amplification: an amplified draw would write each record once per amplification.
let captured_positions = p.dependencies.iter().find_map(|d| match d.fact {
RuntimeFact::CapturedPositions { form } => Some(form),
_ => None,
});
if captured_positions.is_some() && shape.vertex_amplification.count > 1 {
return Err(not_implemented(Feature::TileReach));
}
// A pipeline whose vertex function writes the primitive ID's varying runs an indexed draw
// in its de-indexed form, of the draw's index type.
let writes_primitive_ids = p.interface.push.iter().any(|pl| {
@@ -1357,7 +1335,7 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
// nothing else either draw writes, tests, or orders: one sample, no depth or stencil, no
// memory either function writes, no attachment, imageblock, tile memory, stencil shadow or
// stand-in of the storage form or an input attachment, and no other interlock. A tessellation
// or mesh pipeline's, a capture variant's, and an amplified or layered draw's are not built.
// or mesh pipeline's, and an amplified or layered draw's are not built.
// The device makes the variant's pipeline: its feedback loop flag and dynamic write masks
// need `attachmentFeedbackLoopLayout` and `extendedDynamicState3ColorWriteMask`.
// Every other slot the shape names is left out, and the consumer reads it as it would without
@@ -1382,7 +1360,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
&& tile_memory.is_none()
&& records.is_none()
&& !mesh
&& captured_positions.is_none()
&& interlocked_colors.is_empty()
&& extended_shadows.is_empty()
&& shape.vertex_amplification.count <= 1
@@ -1682,7 +1659,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
field.field,
PushField::RootTableAddress
| PushField::ExecutionStatusAddress
| PushField::CaptureAddress
| PushField::CaptureIndexAddress
| PushField::MergedDrawAddress
| PushField::SnapshotPhase
@@ -1691,12 +1667,9 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
match field.field {
PushField::RootTableAddress => reads_root_table = true,
PushField::ExecutionStatusAddress => {}
// A capture variant's records, its draw's indices, and its draw's layout: the
// addresses are the consumer's holes, the layout instantiation writes from the
// draw.
PushField::CaptureAddress
| PushField::CaptureIndexAddress
| PushField::CaptureLayout
// A de-indexed or private list draw's indices, and its draw's layout: the address
// is the consumer's hole, the layout instantiation writes from the draw.
PushField::CaptureIndexAddress | PushField::CaptureLayout
if stage == Stage::Vertex => {}
PushField::BaseVertexInstance if stage == Stage::Vertex => {}
// A merged draw replay's header: the consumer's hole.
@@ -2536,9 +2509,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
variant.shader_tests = shader_tests;
variant.shader_stencil = shader_stencil;
variant.window_depth_varying = window_depth_varying;
// A pipeline compiled in the capture form states its variant: a consumer asks for it, and no
// bind shape does.
variant.captured_positions = captured_positions;
variant.primitive_id_indices = primitive_id_indices;
variant.quad_primitive_ids = quad_primitive_ids;
variant.private_list = private_list;
@@ -2611,7 +2581,6 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
.shader_tests
.is_some()
.then_some(ShaderTestsTemplate),
capture: captured_positions,
deindexed: primitive_id_indices,
private_list,
storage_kept: storage_kept(p)?,
@@ -2793,11 +2762,8 @@ impl BindingPlan {
}
// An indexed draw of a pipeline that writes the primitive ID runs on its de-indexed
// variant of the draw's index type, and every other draw on the variant without it.
if t.capture.is_none() && t.deindexed.is_some() {
let asked = match *draw {
DrawCall::Indexed { .. } => capture_form(draw)?.index_type(),
_ => None,
};
if t.deindexed.is_some() {
let asked = draw_index_type(draw);
if asked != t.deindexed {
return Err(BindError::NeedsVariant {
variant: Box::new(VariantKey {
@@ -2807,18 +2773,6 @@ impl BindingPlan {
});
}
}
// A draw of the other capture form runs on that form's variant.
if let Some(form) = t.capture {
let asked = capture_form(draw)?;
if asked != form {
return Err(BindError::NeedsVariant {
variant: Box::new(VariantKey {
captured_positions: Some(asked),
..self.variant.clone()
}),
});
}
}
instantiate(t, state, draw, commands)
}
}
@@ -4099,111 +4053,29 @@ fn multiview_instances(limit: Option<u32>, draw: &DrawCall) -> Result<(), BindEr
)))
}
/// The capture form `draw` runs on: a direct draw without an index buffer the vertices form, a
/// direct indexed draw the indexed form of its index type. An indirect draw's counts are the
/// GPU's, and a patch or mesh draw has no vertex function's vertices: each is not implemented
/// (`Feature::TileReach`).
fn capture_form(draw: &DrawCall) -> Result<CaptureForm, BindError> {
/// The index type of `draw`, a direct indexed draw of one of Metal's index types; `None` for any
/// other draw.
fn draw_index_type(draw: &DrawCall) -> Option<metal::IndexType> {
match *draw {
DrawCall::Primitives { .. } => Ok(CaptureForm::Vertices),
DrawCall::Indexed { index_type, .. } if index_type == vk::IndexType::UINT16 => {
Ok(CaptureForm::Indexed(metal::IndexType::UInt16))
Some(metal::IndexType::UInt16)
}
DrawCall::Indexed { index_type, .. } if index_type == vk::IndexType::UINT32 => {
Ok(CaptureForm::Indexed(metal::IndexType::UInt32))
Some(metal::IndexType::UInt32)
}
_ => Err(not_implemented(Feature::TileReach)),
_ => None,
}
}
/// How a draw of a capture variant runs: `PushField::CaptureLayout`'s words, from which each
/// vertex's record slot follows, and for the indexed form the Vulkan draw it runs as and its index
/// read.
struct CaptureDraw {
/// How an indexed draw runs on the primitive ID's de-indexed variant
/// ([`deindexed_draw`]): `PushField::CaptureLayout`'s words, the Vulkan draw it runs as and its
/// index read.
struct DeindexedDraw {
layout: [u32; 4],
/// The indexed form's draw: without indices, `index count` vertices from 0, with the draw's
/// instances.
command: Option<vk::DrawCommand>,
/// The indexed form's read of its indices, from the index offset, as storage in the vertex
/// stage.
indices: Option<ResourceUse>,
}
/// How `draw` (whose `overrun` is [`index_overrun`]'s, of primitive type `primitive`) runs on a
/// capture variant of `form`: a draw of the vertices form as it is, with layout `[vertex start,
/// vertex count, base instance, 0]`; one of the indexed form as `index count` vertices from 0,
/// with layout `[restarts, index count, base instance, base vertex]`, `restarts` 1 for a line or
/// triangle strip, which Metal restarts at the all-ones index (`MissingPrimitiveType` without a
/// primitive type). An indexed draw whose indices run past its buffer, or whose index offset is
/// not a multiple of the index size, is not implemented (`feature`, the form's). A draw of
/// another form never reaches here (`instantiate_draw` asks for its variant).
fn capture_draw(
form: CaptureForm,
draw: &DrawCall,
overrun: Option<IndexOverrun>,
primitive: Option<metal::PrimitiveType>,
feature: Feature,
) -> Result<CaptureDraw, BindError> {
match (capture_form(draw)?, *draw) {
(
asked @ CaptureForm::Vertices,
DrawCall::Primitives {
vertex_start,
vertex_count,
base_instance,
..
},
) if asked == form => Ok(CaptureDraw {
layout: [vertex_start, vertex_count, base_instance, 0],
command: None,
indices: None,
}),
(
asked @ CaptureForm::Indexed(_),
DrawCall::Indexed {
index_type,
index_count,
index_offset,
instance_count,
base_vertex,
base_instance,
..
},
) if asked == form => {
let size = index_bytes(index_type)
.ok_or_else(|| internal("an indexed capture draw without an index size"))?;
if overrun.is_some() || !index_offset.is_multiple_of(size) {
return Err(not_implemented(feature));
}
let restarts = match primitive.ok_or(BindError::MissingPrimitiveType)? {
metal::PrimitiveType::LineStrip | metal::PrimitiveType::TriangleStrip => 1,
metal::PrimitiveType::Point
| metal::PrimitiveType::Line
| metal::PrimitiveType::Triangle => 0,
};
Ok(CaptureDraw {
// The base vertex's two's-complement bits: the function adds it wrapping.
layout: [restarts, index_count, base_instance, base_vertex as u32],
command: Some(vk::DrawCommand::Draw {
vertex_count: index_count,
instance_count,
first_vertex: 0,
first_instance: base_instance,
}),
indices: Some(ResourceUse {
resource: UseTarget::IndexBuffer,
access: AccessSet::READ,
class: AccessClass::Storage,
stages: vk::PipelineStageFlags2::VERTEX_SHADER,
range: Some(ByteRange {
offset: 0,
len: u64::from(index_count) * size,
}),
}),
})
}
_ => Err(internal("a draw of another capture form than its plan's")),
}
/// Without indices, `index count` vertices from 0, with the draw's instances.
command: vk::DrawCommand,
/// Its read of its indices, from the index offset, as storage in the vertex stage.
indices: ResourceUse,
}
/// `PushField::VerticesPerPrimitive` for `draw` of primitive type `primitive`
@@ -4211,7 +4083,7 @@ fn capture_draw(
/// strip or points. The vertex function reads the draw's first vertex as its base vertex, an
/// indirect draw's from its arguments as the GPU draws it. An indexed draw shares a vertex among
/// primitives, whose flat inputs read it alike: it runs `from_zero`, its indices drawn as
/// vertices from 0 (the de-indexed or the indexed capture form, [`capture_draw`]), and is
/// vertices from 0 (the de-indexed form, [`deindexed_draw`]), and is
/// otherwise `NotImplemented(PrimitiveId)`. A draw in the private list form (`listed`) is the
/// consumer's list, run without indices whatever its call: twice that where it lists Metal's
/// quads or quad strip as two triangles a quad (`quads`), whose primitive Metal counts once.
@@ -4237,33 +4109,70 @@ fn vertices_per_primitive(
}
/// How an indexed draw runs on the primitive ID's de-indexed variant of index type `ty`
/// (`VariantKey::primitive_id_indices`): as the indexed capture form's draw ([`capture_draw`]),
/// `index count` vertices from 0 without indices, with layout `[0, index count, base instance,
/// base vertex]`, its indices read in the vertex stage. A line or triangle strip, which Metal
/// restarts at the all-ones index, an indexed draw whose indices run past its buffer or whose
/// index offset is not a multiple of the index size, and any other draw are
/// `NotImplemented(PrimitiveId)` (`MissingPrimitiveType` without a primitive type).
/// (`VariantKey::primitive_id_indices`): `index count` vertices from 0 without indices, with the
/// draw's instances, its layout `[0, index count, base instance, base vertex]`, its indices read
/// in the vertex stage. A line or triangle strip, which Metal restarts at the all-ones index, an
/// indexed draw whose indices run past its buffer or whose index offset is not a multiple of the
/// index size, and any other draw are `NotImplemented(PrimitiveId)` (`MissingPrimitiveType`
/// without a primitive type). A draw of another index type never reaches here
/// (`instantiate_draw` asks for its variant).
fn deindexed_draw(
ty: metal::IndexType,
draw: &DrawCall,
overrun: Option<IndexOverrun>,
primitive: Option<metal::PrimitiveType>,
) -> Result<CaptureDraw, BindError> {
match (primitive.ok_or(BindError::MissingPrimitiveType)?, draw) {
(
metal::PrimitiveType::Point
| metal::PrimitiveType::Line
| metal::PrimitiveType::Triangle,
DrawCall::Indexed { .. },
) => capture_draw(
CaptureForm::Indexed(ty),
draw,
overrun,
primitive,
Feature::PrimitiveId,
),
_ => Err(not_implemented(Feature::PrimitiveId)),
) -> Result<DeindexedDraw, BindError> {
let listed = match primitive.ok_or(BindError::MissingPrimitiveType)? {
metal::PrimitiveType::Point
| metal::PrimitiveType::Line
| metal::PrimitiveType::Triangle => true,
metal::PrimitiveType::LineStrip | metal::PrimitiveType::TriangleStrip => false,
};
let DrawCall::Indexed {
index_type,
index_count,
index_offset,
instance_count,
base_vertex,
base_instance,
..
} = *draw
else {
return Err(not_implemented(Feature::PrimitiveId));
};
if !listed {
return Err(not_implemented(Feature::PrimitiveId));
}
if draw_index_type(draw) != Some(ty) {
return Err(internal(
"a de-indexed draw of another index type than its plan's",
));
}
let size = index_bytes(index_type)
.ok_or_else(|| internal("a de-indexed draw without an index size"))?;
if overrun.is_some() || !index_offset.is_multiple_of(size) {
return Err(not_implemented(Feature::PrimitiveId));
}
Ok(DeindexedDraw {
// The base vertex's two's-complement bits: the function adds it wrapping.
layout: [0, index_count, base_instance, base_vertex as u32],
command: vk::DrawCommand::Draw {
vertex_count: index_count,
instance_count,
first_vertex: 0,
first_instance: base_instance,
},
indices: ResourceUse {
resource: UseTarget::IndexBuffer,
access: AccessSet::READ,
class: AccessClass::Storage,
stages: vk::PipelineStageFlags2::VERTEX_SHADER,
range: Some(ByteRange {
offset: 0,
len: u64::from(index_count) * size,
}),
},
})
}
/// The commands of `draw` of `state`, written over `out` (`BindingPlan::instantiate_draw_into`):
@@ -4299,18 +4208,11 @@ fn instantiate(
} = out;
let overrun = index_overrun(t.robust_index_fetch, draw);
let (command, base) = vk_draw(draw, overrun);
let capture = match (t.capture, t.deindexed) {
(Some(form), _) => Some(capture_draw(
form,
draw,
overrun,
state.primitive_type,
Feature::TileReach,
)?),
(None, Some(ty)) => Some(deindexed_draw(ty, draw, overrun, state.primitive_type)?),
(None, None) => None,
let deindexed = match t.deindexed {
Some(ty) => Some(deindexed_draw(ty, draw, overrun, state.primitive_type)?),
None => None,
};
let command = capture.as_ref().and_then(|c| c.command).unwrap_or(command);
let command = deindexed.as_ref().map_or(command, |d| d.command);
// A mesh render pipeline makes mesh draws, and only it does.
let mesh = match (&t.mesh, mesh_threads(draw)) {
(Some(m), Some(_)) => Some(mesh_draw(m, draw, command)?),
@@ -4388,7 +4290,6 @@ fn instantiate(
let bytes: FieldBytes = match f.field {
PushField::RootTableAddress
| PushField::ExecutionStatusAddress
| PushField::CaptureAddress
| PushField::CaptureIndexAddress
| PushField::MergedDrawAddress
| PushField::SnapshotPhase
@@ -4404,7 +4305,6 @@ fn instantiate(
PushField::ExecutionStatusAddress => {
PushHole::ExecutionStatusAddress { stages, offset }
}
PushField::CaptureAddress => PushHole::CaptureAddress { stages, offset },
PushField::SnapshotPhase => PushHole::SnapshotPhase { stages, offset },
PushField::MergedDrawAddress => {
PushHole::MergedDrawAddress { stages, offset }
@@ -4416,9 +4316,9 @@ fn instantiate(
});
continue;
}
PushField::CaptureLayout => match &capture {
Some(c) => FieldBytes::words(c.layout.iter().copied()),
None => return Err(internal("a capture layout without its capture form")),
PushField::CaptureLayout => match &deindexed {
Some(d) => FieldBytes::words(d.layout.iter().copied()),
None => return Err(internal("a draw layout without its de-indexed form")),
},
PushField::ShadowStencilState => {
let Some(shadow) = &t.shadow_stencil else {
@@ -4509,7 +4409,7 @@ fn instantiate(
FieldBytes::words(base)
}
PushField::VerticesPerPrimitive => {
let from_zero = capture.as_ref().is_some_and(|c| c.command.is_some());
let from_zero = deindexed.is_some();
let form = (from_zero, t.private_list, state.quad_primitive_ids);
FieldBytes::of(
&vertices_per_primitive(draw, state.primitive_type, form)?.to_le_bytes(),
@@ -4716,10 +4616,10 @@ fn instantiate(
Some(m) => (m.dispatch, Some(m.specialization)),
None => (None, None),
};
// The indexed capture form reads its indices in the vertex stage, by address, and binds no
// index buffer.
// The de-indexed form reads its indices in the vertex stage, by address, and binds no index
// buffer.
uses.clear();
match capture.as_ref().and_then(|c| c.indices) {
match deindexed.as_ref().map(|d| d.indices) {
Some(indices) => uses.push(indices),
None => draw_uses(uses, draw, overrun, t.tessellation.as_ref()),
}
@@ -604,7 +604,6 @@ fn instantiation_bounds_a_draw_by_its_index_buffer() {
shadow_stencil: None,
mesh: None,
shader_tests: None,
capture: None,
deindexed: None,
private_list: false,
storage_kept: 0,
@@ -653,7 +652,6 @@ fn a_draw_of_no_index_binds_inside_the_buffer() {
shadow_stencil: None,
mesh: None,
shader_tests: None,
capture: None,
deindexed: None,
private_list: false,
storage_kept: 0,
@@ -737,7 +735,6 @@ fn an_unbounded_indexed_indirect_draw_reads_its_arguments() {
shadow_stencil: None,
mesh: None,
shader_tests: None,
capture: None,
deindexed: None,
private_list: false,
storage_kept: 0,
@@ -795,7 +792,6 @@ fn draws_bind_vertex_buffers_at_aligned_offsets_with_their_windows() {
shadow_stencil: None,
mesh: None,
shader_tests: None,
capture: None,
deindexed: None,
private_list: false,
storage_kept: 0,
@@ -886,7 +882,6 @@ fn inline_vertex_bytes_bind_the_strides_a_dynamic_layout_reads() {
shadow_stencil: None,
mesh: None,
shader_tests: None,
capture: None,
deindexed: None,
private_list: false,
storage_kept: 0,
@@ -1521,7 +1516,6 @@ fn mesh_template(flat: bool, multiples: Vec<u32>) -> GraphicsTemplate {
records: None,
}),
shader_tests: None,
capture: None,
deindexed: None,
private_list: false,
storage_kept: 0,
+8 -22
View File
@@ -82,28 +82,14 @@ pub enum PushHole {
stages: vk::ShaderStageFlags,
offset: u32,
},
/// The device address of the draw's first capture record, as a `u64` at `offset` of a
/// capture variant's vertex push bytes (`VariantKey::captured_positions`): a multiple of 16,
/// in a buffer of `SHADER_DEVICE_ADDRESS` usage that the draw's vertex stage writes
/// (`VERTEX_SHADER`, `SHADER_WRITE`), holding 32 bytes for each vertex of each instance the
/// draw runs (each index of an indexed draw). The record of the draw's vertex `v` (from its
/// first; an indexed draw's index position) in instance `i` (from its first) is at
/// `32 (v + i · vertex count)`: its clip position's four `f32`s at byte 0, as the vertex
/// function returned them (before any viewport compensation), its point size's `f32` at byte
/// 16 (1.0 where the function writes none), a `u32` at byte 20 that is 1 where an indexed
/// draw's index there is its type's all-ones value (Metal's strip restart index) and 0
/// otherwise, and two words the draw leaves as they were.
CaptureAddress {
stages: vk::ShaderStageFlags,
offset: u32,
},
/// The device address of an indexed capture draw's first index (`CaptureForm::Indexed`), as
/// a `u64` at `offset` of the capture variant's vertex push bytes: the draw's index buffer's
/// The device address of a de-indexed draw's first index (`VariantKey::primitive_id_indices`),
/// as a `u64` at `offset` of the variant's vertex push bytes: the draw's index buffer's
/// address plus its index offset, which the binder requires to be a multiple of the index
/// size, in a buffer of `SHADER_DEVICE_ADDRESS` usage whose address is a multiple of 4. The
/// draw reads its indices there in the vertex stage (`DrawCommands::uses`, as storage); a
/// `u16` index is read in the aligned 4-byte word that holds it, which lies inside the
/// `VkBuffer` an `IndexBufferRef` describes.
/// size, in a buffer of `SHADER_DEVICE_ADDRESS` usage whose address is a multiple of 4; or a
/// private list form draw's list (`VariantKey::private_list`). The draw reads its indices
/// there in the vertex stage (`DrawCommands::uses`, as storage); a `u16` index is read in the
/// aligned 4-byte word that holds it, which lies inside the `VkBuffer` an `IndexBufferRef`
/// describes.
CaptureIndexAddress {
stages: vk::ShaderStageFlags,
offset: u32,
@@ -697,7 +683,7 @@ pub(crate) fn bind_buffers(
/// The bytes of one push field ([`put`]): held in place up to [`FieldBytes::INLINE`] bytes, as
/// every field of a few words is, so writing a draw's or a dispatch's fields allocates nothing;
/// a longer one (a capture's layout) on the heap.
/// a longer one on the heap.
pub(crate) enum FieldBytes {
/// The first `len` bytes of `bytes`.
Inline {
+1 -15
View File
@@ -95,13 +95,7 @@
//! [`two_plane_texels_module`]; a blit into such a texture of a heap writes the heap's bytes at
//! Metal's rows through [`plane_bytes_copy_module`]. A heap texture over host pages keeps its
//! elements in the heap's bytes in Metal's tiled layout, moved between its image and those bytes
//! through [`tiled_texels_module`]. A render pass that loads an extended-range, padded 10-bit or
//! bfloat color attachment and draws first rewrites the bits its codes leave unused through
//! [`unused_bits_module`] of its format, in the 32 x 32 tiles a mask names, as Metal's tile store
//! does. The tiles a pass's draws reach, which Metal's tile store writes back, are the mask one
//! dispatch of [`tile_reach_module`] bins its captured primitives into: [`capture_assembly_module`]
//! assembles them from a pass's capture draws' records, and [`capture_settle_module`] widens the
//! mask to every tile where the binning counted a primitive it cannot answer. An ASTC LDR texture
//! through [`tiled_texels_module`]. An ASTC LDR texture
//! on a device without its block is read through a twin of Metal's decode of its blocks
//! ([`AstcDecode`], in the texels [`AstcTexels`] names), which [`astc_decode_module`] writes from
//! the blocks each write left, each decode module of [`BlockDecodeModule`]'s shape; a
@@ -132,7 +126,6 @@ pub(crate) mod acceleration;
pub(crate) mod argument_buffer;
pub(crate) mod astc_decode;
pub(crate) mod block_decode;
pub(crate) mod capture_assembly;
pub(crate) mod chroma_decode;
pub(crate) mod color_resolve;
pub(crate) mod depth_stencil_copy;
@@ -173,10 +166,8 @@ pub(crate) mod status;
pub(crate) mod table;
pub(crate) mod tessellation_scan;
pub(crate) mod tile_map;
pub(crate) mod tile_reach;
pub(crate) mod tiled_texels;
pub(crate) mod two_plane_texels;
pub(crate) mod unused_bits;
pub(crate) mod visibility_combine;
pub(crate) mod visibility_resolve;
pub(crate) mod ycbcr_convert;
@@ -195,9 +186,6 @@ pub use argument_buffer::{
};
pub use astc_decode::{astc_decode_module, AstcDecode, AstcTexels};
pub use block_decode::BlockDecodeModule;
pub use capture_assembly::{
capture_assembly_module, capture_settle_module, CaptureAssemblyModule, CaptureSettleModule,
};
pub use chroma_decode::{chroma_decode_module, ChromaDecode};
pub use color_resolve::{
color_resolve_modules, ColorResolveFormat, ColorResolveModules, ResolveChannel, ResolveRule,
@@ -327,10 +315,8 @@ pub use tessellation_scan::{
tessellation_scan_module, TessellationScanKernel, TessellationScanModule,
};
pub use tile_map::{SparseTileMap, TileMapError, TileMapping};
pub use tile_reach::{tile_reach_module, TileReachModule};
pub use tiled_texels::{tiled_texels_module, TiledLevelMove, TiledTexelsModule};
pub use two_plane_texels::{two_plane_texels_module, PlaneLayout, TwoPlaneTexelsModule};
pub use unused_bits::{unused_bits_module, TexelWords, UnusedBitsModule};
pub use visibility_combine::{
visibility_combine_module, ContinuedResult, VisibilityCombine, VisibilityCombineModule,
};
+1 -5
View File
@@ -216,13 +216,9 @@ pub struct GraphicsTemplate {
/// encoder's stencil state and references as `PushField::ShaderStencilState`.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) shader_tests: Option<ShaderTestsTemplate>,
/// A pipeline compiled in a capture form (`VariantKey::captured_positions`): its draws write
/// `PushField::CaptureLayout`, and an indexed form's run without indices.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) capture: Option<crate::pipeline::CaptureForm>,
/// A pipeline compiled in the primitive ID's de-indexed form of this index type
/// (`VariantKey::primitive_id_indices`): its indexed draws write `PushField::CaptureLayout`
/// and run without indices, as the indexed capture form's do.
/// and run without indices.
#[cfg_attr(feature = "serde", serde(default))]
pub(crate) deindexed: Option<crate::metal::IndexType>,
/// A pipeline compiled in the private list form (`VariantKey::private_list`): its draws are
+1 -3
View File
@@ -307,9 +307,7 @@ fn run_preprocess(
PushHole::ExecutionStatusAddress { offset, .. } => (offset, STATUS),
PushHole::CommandRecordsAddress { offset, .. } => (offset, RECORDS),
PushHole::ReplayRegionAddress { .. } => panic!("the preprocess reads no region"),
PushHole::CaptureAddress { .. } | PushHole::CaptureIndexAddress { .. } => {
panic!("the preprocess captures no vertex")
}
PushHole::CaptureIndexAddress { .. } => panic!("the preprocess reads no index"),
PushHole::SnapshotPhase { .. } => panic!("the preprocess draws no snapshot"),
PushHole::MergedDrawAddress { .. } => panic!("the preprocess draws no merged draw"),
};
+6 -8
View File
@@ -91,14 +91,12 @@ pub struct BindState {
#[cfg_attr(feature = "serde", serde(default))]
pub depth_stencil: metal::state::DepthStencilDescriptor,
/// The draw's primitive type (`drawPrimitives:`'s or `drawIndexedPrimitives:`'s
/// `primitiveType`), which two draws read: one of an indexed capture variant
/// (`CaptureForm::Indexed`), as Metal restarts a line or triangle strip at the index type's
/// all-ones index and shades no vertex there, and draws every index of a list or of points;
/// and one of a pipeline whose vertex function writes the primitive ID
/// (`LoweringInputs::primitive_id_varying`), whose `PushField::VerticesPerPrimitive` holds
/// the type's vertices per primitive. `None` where the consumer does not say; such a draw is
/// `BindError::MissingPrimitiveType`. Only a draw's bytes depend on it, so it is not part of
/// the shape.
/// `primitiveType`), which a draw of a pipeline whose vertex function writes the primitive ID
/// reads (`LoweringInputs::primitive_id_varying`): its `PushField::VerticesPerPrimitive` holds
/// the type's vertices per primitive, and an indexed strip, which Metal restarts at the index
/// type's all-ones index, does not run de-indexed. `None` where the consumer does not say;
/// such a draw is `BindError::MissingPrimitiveType`. Only a draw's bytes depend on it, so it
/// is not part of the shape.
#[cfg_attr(feature = "serde", serde(default))]
pub primitive_type: Option<metal::PrimitiveType>,
/// The index type of a direct indexed draw of a pipeline whose vertex function writes the
+2 -20
View File
@@ -5,7 +5,7 @@
//! [`ExecutionStatus::decode`] after the last one (a `SHADER_WRITE -> HOST_READ` barrier first);
//! the resident-set miss counter, the indirect clamp, the device replay's preprocess, the index
//! bounds pass, an absent argument's read, the mesh and tessellation scans, a sample through a
//! cubic argument sampler, the capture settle, and a sequentially consistent fence write the words
//! cubic argument sampler, and a sequentially consistent fence write the words
//! named here.
/// The `ExecutionStatus` buffer.
@@ -26,9 +26,7 @@ impl ExecutionStatus {
/// What the buffer's bytes report after the command buffer ran. The consumer maps `overflow`, a
/// replay fault, an index pool overflow, an absent argument read, a mesh records fault, a mesh
/// grid Metal's GPU discards or the device cannot launch, and a cubic argument sampler's sample
/// to a command-buffer execution error, treats resident-set
/// misses by its own policy, and announces a captured reach the rule does not answer as its
/// pass's fallback to every tile.
/// to a command-buffer execution error, and treats resident-set misses by its own policy.
pub fn decode(bytes: &[u8; ExecutionStatus::BYTES]) -> StatusReport {
let word = |w: StatusWord| {
let at = w.byte_offset() as usize;
@@ -46,7 +44,6 @@ impl ExecutionStatus {
index_pool_overflow: bits.contains(StatusBits::INDEX_POOL_OVERFLOW),
absent_argument_read: bits.contains(StatusBits::ABSENT_ARGUMENT_READ),
cubic_argument_sampler: bits.contains(StatusBits::CUBIC_ARGUMENT_SAMPLER),
captured_reach_unmeasured: bits.contains(StatusBits::CAPTURED_REACH_UNMEASURED),
mesh_grid_discarded: bits.contains(StatusBits::MESH_GRID_DISCARDED),
mesh_grid_past_limits: bits.contains(StatusBits::MESH_GRID_PAST_LIMITS),
mesh_records_overflow: (bits.contains(StatusBits::MESH_RECORDS_OVERFLOW)).then(|| {
@@ -115,11 +112,6 @@ pub struct StatusReport {
/// `Cubic`, whose bicubic filter it does not emulate there
/// (`RuntimeFact::CubicArgumentSampler`): no result of the command buffer is then Metal's.
pub cubic_argument_sampler: bool,
/// A pass's captured primitives held one whose tiles the tile reach rule does not answer (one
/// across the near or far plane under depth clipping, or one past what was measured), so the
/// capture settle took every tile of the pass's mask (`bind::CaptureSettleModule`): the
/// pass's reach is the announced fallback, not its draws' tiles.
pub captured_reach_unmeasured: bool,
/// An indirect mesh draw's arguments pass (or an emulated one's object arguments pass) met an
/// object grid that Metal's GPU discards (`StatusBits::MESH_GRID_DISCARDED`): that draw drew
/// nothing, and the command buffer fails as Metal's does (`MTLCommandBufferErrorInternal`).
@@ -244,10 +236,6 @@ impl StatusBits {
/// (`RuntimeFact::CubicArgumentSampler`): its result is the device's through a nearest
/// placeholder, not Metal's.
pub const CUBIC_ARGUMENT_SAMPLER: StatusBits = StatusBits(1 << 6);
/// A capture settle found its pass's tile reach header counting a primitive near-far or
/// unmeasured, and set every tile of the pass's mask (`bind::CaptureSettleModule`): the pass
/// takes the announced fallback.
pub const CAPTURED_REACH_UNMEASURED: StatusBits = StatusBits(1 << 7);
/// A tessellation scan found no room in the command buffer's records pool for an emulated
/// tessellation draw's records, or the draw's records passed a `u32`, and the draw drew
/// nothing (`bind::TessellationScanModule`); the fault words name the command buffer's first
@@ -363,7 +351,6 @@ mod tests {
StatusBits::ABSENT_ARGUMENT_READ,
StatusBits::MESH_RECORDS_OVERFLOW,
StatusBits::CUBIC_ARGUMENT_SAMPLER,
StatusBits::CAPTURED_REACH_UNMEASURED,
];
let mut all = 0u32;
for b in bits {
@@ -420,11 +407,6 @@ mod tests {
cubic[0..4].copy_from_slice(&StatusBits::CUBIC_ARGUMENT_SAMPLER.0.to_le_bytes());
let c = ExecutionStatus::decode(&cubic);
assert!(c.cubic_argument_sampler && !c.absent_argument_read && !c.overflow);
assert!(!c.captured_reach_unmeasured && !r.captured_reach_unmeasured);
let mut reach = [0u8; 32];
reach[0..4].copy_from_slice(&StatusBits::CAPTURED_REACH_UNMEASURED.0.to_le_bytes());
let u = ExecutionStatus::decode(&reach);
assert!(u.captured_reach_unmeasured && !u.cubic_argument_sampler && !u.overflow);
assert!(r.absent_argument_read && !r.index_pool_overflow && !r.overflow);
assert_eq!(r.mesh_records_overflow, None);
bytes = [0u8; 32];
-290
View File
@@ -1,290 +0,0 @@
//! Which tiles of a render pass Metal's tile store writes back: the tiles its draws' primitives
//! reach.
//!
//! An Apple GPU bins a pass's primitives into tiles and loads and stores only the tiles a
//! primitive reaches, which decides what a `DontCare` load clears (`clear_reach`), which tiles a
//! rotated texture's frame turns, and which tiles an extended-range or padded 10-bit attachment's
//! store makes canonical ([`unused_bits_module`](super::unused_bits_module)). Measured on an Apple
//! M4 under macOS 27.0.1 (111 cases, each in a process of its own; alike in every case on an Apple
//! M3 Max under macOS 26.7, the kit `share-reach`; 168 cases on the small-primitive cull; and our
//! probes on a point's square):
//!
//! - **Tiles** are 32 by 32 pixels from the render area's origin at 1 and 2 samples, 32 by 16 at
//! 4, whatever the attachments' formats and count (up to eight `RGBA32Float`); each is
//! half-open, `[32i, 32i + 32)` along x.
//! - **Vertices** snap to 1/256 of a pixel, to the nearest: a right edge at `32 - 1/512` reaches
//! the next tile, one at `32 - 1/256` does not. Coordinates of 1e5 pixels snap exactly.
//! - **A triangle** reaches every tile its closed area meets, clipped by the viewport, the
//! scissor and the render area, each a half-open rectangle (a viewport over `[32, 64)` reaches
//! tile 1 alone): its area, not its bounding box, and an edge on `x = 32` reaches the tile
//! right of it. It reaches none where it is culled: by the cull mode and winding, at zero area
//! (through pixel centres too), wholly past the near or far plane (but under depth clamp), or by
//! the small-primitive cull: where its closed box, in window coordinates snapped to 1/256 (the
//! viewport's, before the scissor and the render area clip it), holds at most 12 pixel centres
//! (any shape, 1 by 12 to 12 by 1) and its closed area none of them (a sample on an edge
//! counts, though the fill rule that shades is top-left). A box of 13 or more is kept, holding
//! a sample or not. At 2 samples a box of up to 12 of their positions is tested too, at 4 one
//! of up to 24 (Metal's default positions, Vulkan's standard ones), in every slope measured. A
//! fragment that discards or fails a test still reaches. A triangle across the near plane
//! reaches by the clipped polygon.
//! - **A point** reaches what a closed square about its snapped centre meets (a size of 0 or 0.25
//! too, a centre past the viewport too; no sample cull): from half its size back, rounded half
//! up to 1/256 of a pixel (its left and top edges reach a tile only from more than half a unit
//! past it), over its size rounded to the nearest 1/16 of a pixel (its right and bottom edges
//! follow from the left and top ones, up to four units past the exact square); a size past 511
//! draws as 511.
//! - **A line** reaches what a parallelogram meets: half a pixel each way across its major axis,
//! extended half a pixel past each end along it, a 45-degree line taken as y-major; no sample
//! cull.
//! - **A draw** reaches the same directly or indirectly; one of no instances, one by a pipeline
//! that does not rasterize, and a pass without a draw call reach nothing. A layered pass's
//! draw reaches the tiles of the slice it renders alone.
//! - **A clear.** In a pass with a draw call (of no instances too), an attachment loaded `Clear`
//! and stored, color, depth or stencil, makes every tile of the render area reached; one whose
//! store is `DontCare` does not.
//!
//! The rule is checked here as a plain function the tests hold, against every measured case.
//! [`tile_reach_module`] bins a pass's captured primitives on the device by it; its consumers in
//! the runtime follow (the later steps).
//!
//! **The module** (one per device). One `GLCompute` entry `main` with local size
//! ([`TileReachModule::LOCAL_SIZE`], 1, 1), no push constants, and three storage buffers of 4-byte
//! words in set 0:
//!
//! - [`PRIMITIVES_BINDING`](TileReachModule::PRIMITIVES_BINDING): the pass's primitives, each
//! [`PRIMITIVE_WORDS`](TileReachModule::PRIMITIVE_WORDS) words
//! ([`primitive`](TileReachModule::primitive)): its kind, its state, its layer, a point's size,
//! and three clip-space vertices (a point's first, a line's first two);
//! - [`PASS_BINDING`](TileReachModule::PASS_BINDING): the header
//! ([`header`](TileReachModule::header)), [`HEADER_WORDS`](TileReachModule::HEADER_WORDS)
//! words: the render area, the samples, the layers, the primitives' count, and the two counts the
//! kernel adds to, then the states, each [`STATE_WORDS`](TileReachModule::STATE_WORDS) words
//! ([`state`](TileReachModule::state)): the viewport, the scissor, the cull mode, the winding and
//! the depth clip mode a primitive was drawn under;
//! - [`TILES_BINDING`](TileReachModule::TILES_BINDING): the tile mask, one bit a tile of the
//! pass (32 by 32 pixels, 32 by 16 at 4 samples; bit `t % 32` of word `t / 32`), tile `t =
//! (layer * tile_rows + y) * tiles_per_row + x`, which the kernel ORs bits into.
//!
//! Invocation `i` below the count bins primitive `i` into its slice's tiles (a layer past the
//! pass's into the first), and adds one to the header's word
//! [`NEAR_FAR_WORD`](TileReachModule::NEAR_FAR_WORD) where the primitive crossed the near or far
//! plane under depth clipping (its reach is its clipped polygon's, whose new vertices Apple's
//! clipper may place otherwise) and to [`UNMEASURED_WORD`](TileReachModule::UNMEASURED_WORD) where
//! its reach is past what was measured (a vertex not finite, with a subnormal component, at or
//! behind the eye or snapped past 2^21 pixels; a viewport edge past that; a line of no length; a
//! point past the depth range, or of a size negative, not a number or subnormal; a state past the
//! header's or a kind not one of [`POINT`](TileReachModule::POINT),
//! [`LINE`](TileReachModule::LINE) and [`TRIANGLE`](TileReachModule::TRIANGLE)). The kernel's
//! arithmetic is exact on every device (`kernel.rs`): the reach of each primitive is the rule's.
//!
//! **Synchronization** (consumer): the writes of the primitives, the pass and the cleared mask
//! (`TRANSFER_WRITE` or `SHADER_WRITE`) → `SHADER_STORAGE_READ` and `SHADER_STORAGE_WRITE` in
//! `COMPUTE_SHADER` before the dispatch; its writes → the mask's and the counts' readers.
use std::sync::Arc;
use crate::budget::{Budget, Meter};
use crate::device::requirements::{Requirements, VkFeature};
use crate::device::Device;
use crate::error::{Capability, Error, Feature, InternalError, InternalKind, Unsupported};
use crate::pipeline::sym::Symbol;
mod kernel;
/// The word positions within the kernel's records ([`TileReachModule`]); the capture assembly
/// writes primitives and the capture settle reads the header by them (`capture_assembly.rs`).
pub(super) mod layout {
/// The header's: the render area's width and height, the samples, the layers, the count.
pub(in crate::bind) const AREA_W: u32 = 0;
pub(in crate::bind) const AREA_H: u32 = 1;
pub(in crate::bind) const SAMPLES: u32 = 2;
pub(in crate::bind) const LAYERS: u32 = 3;
pub(super) const COUNT: u32 = 4;
/// A state's, from its first word: the viewport (four `f32`s), the scissor (four words), the
/// cull mode, the winding and the depth clip mode.
pub(super) const VIEWPORT: u32 = 0;
pub(super) const SCISSOR: u32 = 4;
pub(super) const CULL: u32 = 8;
pub(super) const WINDING: u32 = 9;
pub(super) const DEPTH_CLIP: u32 = 10;
/// A primitive's: its kind, state, layer, size (an `f32`) and vertices (twelve `f32`s).
pub(in crate::bind) const KIND: u32 = 0;
pub(in crate::bind) const STATE: u32 = 1;
pub(in crate::bind) const LAYER: u32 = 2;
pub(in crate::bind) const SIZE: u32 = 3;
pub(in crate::bind) const VERTICES: u32 = 4;
}
/// The crate-owned tile reach module of one device (the module docs), validated like any output.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TileReachModule {
/// SPIR-V 1.5 words, entry point `main`, its bindings numbered as below in set 0.
pub spirv: Arc<[u32]>,
/// What the module needs from the device: within every Vulkan 1.2 device with
/// `shaderInt64`.
pub requirements: Requirements,
}
impl TileReachModule {
/// Descriptor set of the bindings.
pub const SET: u32 = 0;
/// The primitives, a storage buffer the kernel reads.
pub const PRIMITIVES_BINDING: u32 = 0;
/// The header and the states, a storage buffer the kernel reads and counts into.
pub const PASS_BINDING: u32 = 1;
/// The tile mask, a storage buffer the kernel ORs bits into.
pub const TILES_BINDING: u32 = 2;
/// Invocations of one workgroup, along x: one primitive each.
pub const LOCAL_SIZE: u32 = 64;
/// A primitive's words ([`primitive`](Self::primitive)).
pub const PRIMITIVE_WORDS: u32 = 16;
/// The header's words ([`header`](Self::header)), before the states.
pub const HEADER_WORDS: u32 = 8;
/// A state's words ([`state`](Self::state)).
pub const STATE_WORDS: u32 = 12;
/// The header's word the kernel adds one to for each primitive that crossed the near or far
/// plane under depth clipping.
pub const NEAR_FAR_WORD: u32 = 5;
/// The header's word the kernel adds one to for each primitive whose reach is past what was
/// measured (the module docs).
pub const UNMEASURED_WORD: u32 = 6;
/// The kind of a point (`MTLPrimitiveTypePoint`'s primitives).
pub const POINT: u32 = 0;
/// The kind of a line (`MTLPrimitiveTypeLine` and `LineStrip`'s).
pub const LINE: u32 = 1;
/// The kind of a triangle (`MTLPrimitiveTypeTriangle` and `TriangleStrip`'s).
pub const TRIANGLE: u32 = 2;
/// The header's bytes: the render area's width and height in pixels (at most 16384 each, a
/// larger side binned as 16384), its samples (1, 2 or 4; another count bins as 1), its layers
/// (1 for a pass that is not layered), and the count of primitives; the two counts zero.
pub fn header(area: [u32; 2], samples: u32, layers: u32, count: u32) -> [u8; 32] {
let mut words = [0; Self::HEADER_WORDS as usize];
words[layout::AREA_W as usize] = area[0];
words[layout::AREA_H as usize] = area[1];
words[layout::SAMPLES as usize] = samples;
words[layout::LAYERS as usize] = layers;
words[layout::COUNT as usize] = count;
bytes_of(words)
}
/// A state's bytes: the viewport (`MTLViewport`'s `originX`, `originY`, `width` and `height`
/// as the rasterizer takes them, in `f32`), the scissor rectangle (`MTLScissorRect`'s `x`,
/// `y`, `width` and `height`), and the raw values of the `MTLCullMode`, the `MTLWinding` and
/// the `MTLDepthClipMode` a primitive was drawn under.
pub fn state(
viewport: [f32; 4],
scissor: [u32; 4],
cull: u32,
winding: u32,
depth_clip: u32,
) -> [u8; 48] {
let mut words = [0; Self::STATE_WORDS as usize];
for i in 0..4 {
words[layout::VIEWPORT as usize + i] = viewport[i].to_bits();
words[layout::SCISSOR as usize + i] = scissor[i];
}
words[layout::CULL as usize] = cull;
words[layout::WINDING as usize] = winding;
words[layout::DEPTH_CLIP as usize] = depth_clip;
bytes_of(words)
}
/// A primitive's bytes: its `kind` ([`POINT`](Self::POINT), [`LINE`](Self::LINE) or
/// [`TRIANGLE`](Self::TRIANGLE)), the index of the `state` it was drawn under among the
/// pass's, the `layer` it renders (`[[render_target_array_index]]`; 0 where none), a point's
/// `size` in pixels (`[[point_size]]`), and its clip-space `vertices` (`[[position]]`): a
/// point's first, a line's first two, a triangle's three, in the order the draw assembled
/// them.
pub fn primitive(
kind: u32,
state: u32,
layer: u32,
size: f32,
vertices: [[f32; 4]; 3],
) -> [u8; 64] {
let mut words = [0; Self::PRIMITIVE_WORDS as usize];
words[layout::KIND as usize] = kind;
words[layout::STATE as usize] = state;
words[layout::LAYER as usize] = layer;
words[layout::SIZE as usize] = size.to_bits();
for (v, vertex) in vertices.iter().enumerate() {
for (c, value) in vertex.iter().enumerate() {
words[layout::VERTICES as usize + 4 * v + c] = value.to_bits();
}
}
bytes_of(words)
}
/// The tile mask's words of a pass of render area `area`, `samples` and `layers` (the
/// header's): one bit a tile of each slice.
pub fn mask_words(area: [u32; 2], samples: u32, layers: u32) -> u32 {
let tile_rows = match samples {
4 => 16,
_ => 32,
};
let [w, h] = area.map(|a| a.min(AREA_LIMIT));
let tiles = w.div_ceil(32) * h.div_ceil(tile_rows) * layers;
tiles.div_ceil(32)
}
}
/// The largest render area side the kernel bins, in pixels (Metal's): a larger side is binned as
/// this one, which keeps every product of the kernel's integer tests within an `i64`.
pub(super) const AREA_LIMIT: u32 = 16384;
/// The little-endian bytes of `N` words.
fn bytes_of<const N: usize, const B: usize>(words: [u32; N]) -> [u8; B] {
let mut bytes = [0; B];
for (at, w) in words.iter().enumerate() {
bytes[4 * at..4 * at + 4].copy_from_slice(&w.to_le_bytes());
}
bytes
}
/// The fixed binding numbers of the module's symbols.
fn binding_of(sym: &Symbol) -> Option<u32> {
match sym {
Symbol::DescriptorSet(_) => Some(TileReachModule::SET),
Symbol::Binding(s) if *s == kernel::PRIMITIVES => Some(TileReachModule::PRIMITIVES_BINDING),
Symbol::Binding(s) if *s == kernel::PASS => Some(TileReachModule::PASS_BINDING),
Symbol::Binding(s) if *s == kernel::TILES => Some(TileReachModule::TILES_BINDING),
_ => None,
}
}
/// The tile reach module of `device`: built with the typed builder, checked by the owned verifier
/// against the device's profile (requirements included), serialized, and numbered with the fixed
/// bindings of [`TileReachModule`]. A device without `shaderInt64`, which the kernel's exact
/// arithmetic needs, is [`Feature::TileReach`] needing it.
pub fn tile_reach_module(device: &Device) -> Result<TileReachModule, Error> {
let profile = device.profile();
if !profile
.fields()
.enabled
.features
.contains(&VkFeature::ShaderInt64)
{
let int64 = Capability::Feature(VkFeature::ShaderInt64);
return Err(Unsupported::needs_any_of(Feature::TileReach, vec![vec![int64]]).into());
}
let m = kernel::typed_module()?;
let mut meter = Meter::new(&Budget::default());
crate::spirv::verify::verify(&m, profile, &mut meter)?;
let r = crate::spirv::serialize::serialize(m)?;
profile.check(&r.requirements).map_err(|c| {
Error::Internal(InternalError::new(
InternalKind::RequirementsExceedProfile,
format!("the tile reach kernel needs {c:?}"),
))
})?;
let words = crate::spirv::serialize::relocate(&r, &binding_of)?;
Ok(TileReachModule {
spirv: words.into(),
requirements: r.requirements,
})
}
#[cfg(test)]
mod tests;
File diff suppressed because it is too large. Load diff
@@ -1,381 +0,0 @@
mod assembly;
mod device;
mod kernel;
mod measured;
mod points;
mod reference;
use reference::{every_tile, reach, Cull, Flags, Primitive, Raster, Winding};
use std::collections::BTreeSet;
/// The probes' attachment side, in pixels.
const FRAME: u32 = 128;
/// The clip-space vertex the probes drew at pixel `(x, y)` of the frame (y down) at depth 0.5.
fn clip(x: f64, y: f64) -> [f32; 4] {
clip_z(x, y, 0.5)
}
/// The clip-space vertex at pixel `(x, y)` and depth `z`, as the probes made it: each
/// coordinate in `f64`, then rounded to `f32`.
fn clip_z(x: f64, y: f64, z: f64) -> [f32; 4] {
clip_in([FRAME; 2], x, y, z)
}
/// The clip-space vertex at pixel `(x, y)` and depth `z` of a frame of `frame` pixels, as the
/// probes made it.
fn clip_in(frame: [u32; 2], x: f64, y: f64, z: f64) -> [f32; 4] {
let [w, h] = frame.map(f64::from);
[
(2.0 * x / w - 1.0) as f32,
(1.0 - 2.0 * y / h) as f32,
z as f32,
1.0,
]
}
/// The two triangles of the rectangle `[x0, x1] x [y0, y1]`, at depth 0.5.
fn quad(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec<[f32; 4]> {
quad_z(x0, y0, x1, y1, 0.5)
}
/// The two triangles of the rectangle `[x0, x1] x [y0, y1]` at depth `z`.
fn quad_z(x0: f64, y0: f64, x1: f64, y1: f64, z: f64) -> Vec<[f32; 4]> {
[(x0, y0), (x1, y0), (x0, y1), (x1, y0), (x1, y1), (x0, y1)]
.into_iter()
.map(|(x, y)| clip_z(x, y, z))
.collect()
}
/// The probes' triangle over the whole frame.
fn full() -> Vec<[f32; 4]> {
vec![
clip(-128.0, -128.0),
clip(384.0, -128.0),
clip(-128.0, 384.0),
]
}
/// What a probe's draw assembled its vertices into.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Topology {
/// A triangle list.
Triangles,
/// A line list.
Lines,
/// A point list.
Points,
}
/// A probe's draw call.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Draw {
/// Drawn directly.
Direct,
/// Drawn from an indirect buffer's arguments.
Indirect,
/// Drawn with no instances.
NoInstances,
/// By a pipeline that does not rasterize.
Unrasterized,
/// No draw call.
None,
}
/// Another attachment of a probe's pass.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Other {
/// None.
None,
/// A color attachment loaded `Clear` and stored.
ColorClearStore,
/// A color attachment loaded `Clear`, its store `DontCare`.
ColorClearDontCare,
/// A depth attachment loaded `Clear` and stored.
DepthClearStore,
/// A stencil attachment loaded `Clear` and stored.
StencilClearStore,
}
/// A measured case: its pass and draw, and the tiles the M4 reached.
struct Row {
probe: &'static str,
name: &'static str,
topology: Topology,
vertices: Vec<[f32; 4]>,
size: f32,
raster: Raster,
draw: Draw,
other: Other,
slices: u32,
layer: u32,
reached: Vec<String>,
}
/// A case of `probe` drawing `drawn` over the whole frame.
fn row(probe: &'static str, name: &'static str, drawn: (Topology, Vec<[f32; 4]>)) -> Row {
Row {
probe,
name,
topology: drawn.0,
vertices: drawn.1,
size: 1.0,
raster: Raster::over([FRAME; 2]),
draw: Draw::Direct,
other: Other::None,
slices: 1,
layer: 0,
reached: Vec::new(),
}
}
fn tris(v: Vec<[f32; 4]>) -> (Topology, Vec<[f32; 4]>) {
(Topology::Triangles, v)
}
fn lines(v: Vec<[f32; 4]>) -> (Topology, Vec<[f32; 4]>) {
(Topology::Lines, v)
}
fn points(v: Vec<[f32; 4]>) -> (Topology, Vec<[f32; 4]>) {
(Topology::Points, v)
}
impl Row {
fn size(mut self, size: f64) -> Row {
self.size = size as f32;
self
}
fn cull(mut self, cull: Cull) -> Row {
self.raster.cull = cull;
self
}
fn scissor(mut self, scissor: [u32; 4]) -> Row {
self.raster.scissor = scissor;
self
}
fn viewport(mut self, viewport: [f64; 4]) -> Row {
self.raster.viewport = viewport.map(|c| c as f32);
self
}
fn clamp(mut self) -> Row {
self.raster.clamp = true;
self
}
fn samples(mut self, samples: u32) -> Row {
self.raster.samples = samples;
self
}
/// A render area (the descriptor's target size) of `side` over the frame: the default
/// viewport and scissor follow it.
fn area(mut self, side: u32) -> Row {
let samples = self.raster.samples;
self.raster = Raster::over([side; 2]);
self.raster.samples = samples;
self
}
fn slices(mut self, slices: u32) -> Row {
self.slices = slices;
self
}
fn layer(mut self, layer: u32) -> Row {
self.layer = layer;
self
}
fn unrasterized(mut self) -> Row {
self.draw = Draw::Unrasterized;
self
}
fn draw(mut self, draw: Draw) -> Row {
self.draw = draw;
self
}
fn other(mut self, other: Other) -> Row {
self.other = other;
self
}
/// A fragment function that discards: the reach does not follow it.
fn discards(self) -> Row {
self
}
fn reaches(mut self, reached: &[&str]) -> Row {
self.reached = reached.iter().map(|s| s.to_string()).collect();
self
}
/// The primitives the draw assembled.
fn primitives(&self) -> Vec<Primitive> {
let v = &self.vertices;
match self.topology {
Topology::Triangles => v
.as_chunks::<3>()
.0
.iter()
.map(|t| Primitive::Triangle([t[0], t[1], t[2]]))
.collect(),
Topology::Lines => v
.as_chunks::<2>()
.0
.iter()
.map(|l| Primitive::Line([l[0], l[1]]))
.collect(),
Topology::Points => v.iter().map(|&p| Primitive::Point(p, self.size)).collect(),
}
}
/// The tiles the rule reaches, slice by slice: every tile of each where another attachment
/// is cleared and stored in a pass with a draw call, else the tiles of the slice the draw
/// renders (a layer past the pass's renders its first) its primitives reach.
fn answer(&self) -> (Vec<BTreeSet<[u32; 2]>>, Flags) {
let mut flags = Flags::default();
let called = self.draw != Draw::None;
let cleared = matches!(
self.other,
Other::ColorClearStore | Other::DepthClearStore | Other::StencilClearStore
);
let drawn = matches!(self.draw, Draw::Direct | Draw::Indirect);
let slice = if self.layer < self.slices {
self.layer
} else {
0
};
let slices = (0..self.slices)
.map(|s| {
if cleared && called {
return every_tile(&self.raster);
}
let mut tiles = BTreeSet::new();
if drawn && s == slice {
for prim in self.primitives() {
tiles.extend(reach(&self.raster, &prim, &mut flags));
}
}
tiles
})
.collect();
(slices, flags)
}
/// The tiles the M4 reached, slice by slice.
fn measured(&self) -> Vec<BTreeSet<[u32; 2]>> {
self.reached
.iter()
.map(|slice| {
let mut tiles = BTreeSet::new();
for (y, line) in slice.split(' ').enumerate() {
for (x, c) in line.chars().enumerate() {
if c == 'R' {
tiles.insert([x as u32, y as u32]);
}
}
}
tiles
})
.collect()
}
}
/// Every measured case reaches the tiles the M4 reached, and only the case across the near plane is
/// flagged (its reach that of the clipped polygon).
#[test]
fn the_rule_reaches_every_measured_answer() {
let mut rows = measured::rows();
assert_eq!(rows.len(), 111, "the probes' cases");
rows.extend(measured::later_rows());
rows.extend(points::rows());
let mut wrong = Vec::new();
for row in &rows {
let (answer, flags) = row.answer();
let near_far = row.name == "near_cross";
let expected_flags = Flags {
near_far,
unmeasured: false,
};
if answer != row.measured() || flags != expected_flags {
wrong.push(format!(
"{}/{}: reached {:?} ({flags:?}), measured {:?}",
row.probe,
row.name,
answer,
row.measured()
));
}
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
}
/// Winding and the cull mode: a clockwise triangle (y down) faces front by default, and the
/// other winding turns it.
#[test]
fn the_cull_follows_the_winding() {
let t = Primitive::Triangle([clip(40.0, 40.0), clip(50.0, 40.0), clip(40.0, 50.0)]);
let mut raster = Raster::over([FRAME; 2]);
let reached = |raster: &Raster| !reach(raster, &t, &mut Flags::default()).is_empty();
for (cull, winding, drawn) in [
(Cull::Back, Winding::Clockwise, true),
(Cull::Front, Winding::Clockwise, false),
(Cull::Back, Winding::CounterClockwise, false),
(Cull::Front, Winding::CounterClockwise, true),
(Cull::None, Winding::CounterClockwise, true),
] {
raster.cull = cull;
raster.winding = winding;
assert_eq!(reached(&raster), drawn, "{cull:?} {winding:?}");
}
}
/// A vertex past the coordinates measured, a line of no length, and a point past the depth range
/// are flagged unmeasured; a triangle across the far plane is flagged near-far.
#[test]
fn unmeasured_cases_are_flagged() {
let raster = Raster::over([FRAME; 2]);
let flags = |prim: Primitive| {
let mut flags = Flags::default();
reach(&raster, &prim, &mut flags);
flags
};
let unmeasured = Flags {
near_far: false,
unmeasured: true,
};
assert_eq!(
flags(Primitive::Triangle([
clip(-1e7, 40.0),
clip(1e7, 40.0),
clip(0.0, 1e7)
])),
unmeasured
);
assert_eq!(
flags(Primitive::Line([clip(40.0, 40.0), clip(40.0, 40.0)])),
unmeasured
);
assert_eq!(
flags(Primitive::Point(clip_z(40.0, 40.0, 1.5), 1.0)),
unmeasured
);
assert_eq!(
flags(Primitive::Triangle([
clip(40.0, 40.0),
clip(40.0, 60.0),
clip_z(80.0, 50.0, 1.5)
])),
Flags {
near_far: true,
unmeasured: false
}
);
}
@@ -1,77 +0,0 @@
//! The capture assembly's two placeholders (`bind::capture_assembly`'s module docs) under the
//! rule and the kernel: the triangle of three `(0, 0, 0, 1)` vertices, which a restart writes,
//! reaches no tile and is flagged only where its state's viewport flags every primitive drawn
//! under it; the triangle of three NaN vertices, which an unknown parity writes, reaches no tile
//! and is counted unmeasured.
use std::collections::BTreeMap;
use super::kernel::{random_pass, Drawn, Pass, Rng};
use super::reference::{reach, snap_clamped, Flags, Primitive, Raster};
use super::{measured, points};
use crate::bind::capture_assembly::{NOTHING, UNKNOWN};
use crate::bind::tile_reach::kernel::typed_module;
/// Under every measured case's state and the states of 64 seeded random passes (viewports,
/// scissors, culls, windings, depth clipped and clamped, 1, 2, 4 and other sample counts), the
/// rule reaches no tile with either placeholder and flags them as the module docs say, and the
/// kernel bins them as the rule does.
#[test]
fn the_capture_assembly_s_placeholders_reach_nothing() {
let nothing = Primitive::Triangle([NOTHING.map(f32::from_bits); 3]);
let unknown = Primitive::Triangle([UNKNOWN.map(f32::from_bits); 3]);
let mut rows = measured::rows();
rows.extend(measured::later_rows());
rows.extend(points::rows());
let mut states: Vec<Raster> = rows.iter().map(|r| r.raster).collect();
let mut rng = Rng(0xa55e_b1e0);
let areas = [[128, 128], [96, 64], [33, 31], [1, 1], [16384, 200]];
for _ in 0..64 {
let area = rng.pick(&areas);
let samples = rng.pick(&[1, 2, 4, 3]);
let pass = random_pass(&mut rng, area, samples, 1);
states.extend(pass.states.into_iter().map(|mut s| {
s.area = area;
s.samples = samples;
s
}));
}
let mut wrong = Vec::new();
// The kernel's passes: one per render area and samples, both placeholders under each state.
let mut passes: BTreeMap<([u32; 2], u32), Pass> = BTreeMap::new();
for state in &states {
let [ox, oy, w, h] = state.viewport;
let viewport = [ox, ox + w, oy, oy + h]
.into_iter()
.all(|c| snap_clamped(c).1);
for (prim, unmeasured) in [(nothing, !viewport), (unknown, true)] {
let mut flags = Flags::default();
let tiles = reach(state, &prim, &mut flags);
let expected = Flags {
near_far: false,
unmeasured,
};
if !tiles.is_empty() || flags != expected {
wrong.push(format!("{prim:?} under {state:?}: {tiles:?}, {flags:?}"));
}
}
let pass = passes
.entry((state.area, state.samples))
.or_insert_with(|| Pass {
area: state.area,
samples: state.samples,
layers: 1,
states: Vec::new(),
drawn: Vec::new(),
});
let at = pass.states.len() as u32;
pass.states.push(*state);
pass.drawn.push(Drawn::of(nothing, at, 0));
pass.drawn.push(Drawn::of(unknown, at, 0));
}
let m = typed_module().expect("module");
for pass in passes.values() {
wrong.extend(pass.differences(&m));
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
}
@@ -1,159 +0,0 @@
//! The kernel on a device: the fixture of passes and the rule's answers
//! (`validation/fixtures/public/tile_reach/device_passes.txt`) that the validation crate's lane
//! `runtime_lane::tile_reach_kernel` dispatches on the device its cfg selects and compares bit for
//! bit. The passes hold every measured case drawn (directly or indirectly), each case under a
//! state of its own and in a slice of its own, grouped by render area and samples, and seeded
//! random passes ([`random_pass`]). Here the committed fixture is checked to be the rule's
//! answers for them, and the kernel's through the interpreter.
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::PathBuf;
use super::kernel::{cull, random_pass, winding, Drawn, Pass, Rng};
use super::{measured, points, Draw};
use crate::bind::tile_reach::kernel::typed_module;
use crate::bind::tile_reach::TileReachModule as M;
/// The fixture, from this crate's directory.
const FIXTURE: &str = "../metal2vulkan-validation/fixtures/public/tile_reach/device_passes.txt";
/// The command that prints the fixture between [`BEGIN`] and [`END`].
const PRINT: &str = "cargo nextest run -p metal2vulkan --all-features --lib --run-ignored \
ignored-only --no-capture -E 'test(/print_the_device_passes/)'";
const BEGIN: &str = "----- device_passes.txt begins -----";
const END: &str = "----- device_passes.txt ends -----";
/// The random passes beside the measured cases.
const RANDOM_PASSES: usize = 16;
/// The passes: the measured cases drawn, one pass per render area and samples (each case's
/// primitives in a slice of their own, under its state; slice 0 holds none), then
/// [`RANDOM_PASSES`] seeded random passes of 32 primitives.
fn device_passes() -> Vec<Pass> {
let mut rows = measured::rows();
rows.extend(measured::later_rows());
rows.extend(points::rows());
let mut groups: BTreeMap<([u32; 2], u32), Pass> = BTreeMap::new();
for row in rows
.iter()
.filter(|r| matches!(r.draw, Draw::Direct | Draw::Indirect))
{
let (area, samples) = (row.raster.area, row.raster.samples);
let pass = groups.entry((area, samples)).or_insert_with(|| Pass {
area,
samples,
layers: 1,
states: Vec::new(),
drawn: Vec::new(),
});
let state = pass.states.len() as u32;
pass.states.push(row.raster);
let layer = pass.layers;
pass.layers += 1;
let drawn = row.primitives().into_iter();
pass.drawn
.extend(drawn.map(|prim| Drawn::of(prim, state, layer)));
}
let mut passes: Vec<Pass> = groups.into_values().collect();
let mut rng = Rng(0xde71_ce5e);
let areas = [
[128, 128],
[96, 64],
[200, 72],
[33, 31],
[256, 40],
[160, 96],
];
for _ in 0..RANDOM_PASSES {
let area = rng.pick(&areas);
let samples = rng.pick(&[1, 2, 4, 3]);
passes.push(random_pass(&mut rng, area, samples, 32));
}
passes
}
/// Little-endian bytes as words, in hex.
fn hex(bytes: &[u8]) -> String {
let words: Vec<String> = bytes
.as_chunks::<4>()
.0
.iter()
.map(|w| format!("{:08x}", u32::from_le_bytes(*w)))
.collect();
words.join(" ")
}
/// The fixture's text for `passes` (its header states the format).
fn fixture(passes: &[Pass]) -> String {
let mut out = String::new();
out.push_str(
"# The tile reach kernel on a device: passes and the\n\
# rule's answers, generated by bind::tile_reach::tests::device from the measured cases\n\
# and seeded random passes. Our own synthetic data. Print it again with\n",
);
let _ = writeln!(out, "# {PRINT}");
out.push_str(
"# Per pass: `pass <width> <height> <samples> <layers>`; each state, `state` and its 12\n\
# words (TileReachModule::state); each primitive, `primitive` and its 16 words\n\
# (TileReachModule::primitive), words in hex; `expect <near-far> <unmeasured>`, the\n\
# header's two counts; and the tile mask's set bits, `bits` and up to 16 indices a line.\n",
);
for pass in passes {
let [w, h] = pass.area;
let _ = writeln!(out, "pass {w} {h} {} {}", pass.samples, pass.layers);
for s in &pass.states {
let words = M::state(
s.viewport,
s.scissor,
cull(s.cull),
winding(s.winding),
u32::from(s.clamp),
);
let _ = writeln!(out, "state {}", hex(&words));
}
for d in &pass.drawn {
let _ = writeln!(out, "primitive {}", hex(&d.record()));
}
let rule = pass.rule();
let _ = writeln!(out, "expect {} {}", rule.near_far, rule.unmeasured);
let [gx, gy] = pass.grid();
let mut bits = Vec::new();
for (slice, tiles) in rule.slices.iter().enumerate() {
for [x, y] in tiles {
bits.push((slice as u32 * gy + y) * gx + x);
}
}
bits.sort_unstable();
for line in bits.chunks(16) {
let line: Vec<String> = line.iter().map(u32::to_string).collect();
let _ = writeln!(out, "bits {}", line.join(" "));
}
}
out
}
/// The committed fixture is the rule's answers for the passes, and the kernel bins each pass as
/// the rule does through the interpreter (both invocation orders).
#[test]
fn the_device_passes_are_the_rules_answers_and_the_kernels() {
let passes = device_passes();
let m = typed_module().expect("module");
let wrong: Vec<String> = passes.iter().flat_map(|p| p.differences(&m)).collect();
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(FIXTURE);
let committed = std::fs::read_to_string(&path).unwrap_or_default();
assert!(
committed == fixture(&passes),
"{FIXTURE} is not the rule's answers: print it with\n {PRINT}\nand write the lines \
between `{BEGIN}` and `{END}` to it"
);
}
/// Print the fixture between [`BEGIN`] and [`END`] (the module docs).
#[test]
#[ignore = "prints the device fixture"]
fn print_the_device_passes() {
println!("{BEGIN}\n{}{END}", fixture(&device_passes()));
}
@@ -1,831 +0,0 @@
//! The kernel against the reference function, through the CPU interpreter: built and valid
//! where a device has `shaderInt64` and refused where it does not; its arithmetic Rust's (the
//! division, the snap and a point's extent); and its mask and counts the rule's on every measured
//! case (the M4's tiles themselves where the case's answer is its primitives' reach) and on
//! seeded random passes.
use std::collections::BTreeSet;
use std::path::PathBuf;
use super::reference::{
clip, point_extent, reach, snap_clamped, Cull, Flags, Primitive, Raster, Winding,
POINT_SIZE_LIMIT,
};
use super::{clip_in, measured, points, Draw, Other, Row};
use crate::bind::tile_reach::kernel::{
arithmetic_module, clip_module, typed_module, ARITHMETIC_WORDS, CLIP_WORDS, PASS, POLYGON,
PRIMITIVES, TILES,
};
use crate::bind::tile_reach::{tile_reach_module, TileReachModule as M};
use crate::device::requirements::VkFeature;
use crate::device::{Device, DeviceDescription, DevicePolicy};
use crate::error::{Capability, Error, Feature, Needs};
use crate::pipeline::sym::ResourceSlot;
use crate::spirv::interp::{run, Buffer, Config, Order, Resources};
use crate::spirv::ir::TypedModule;
use crate::spirv::testing::assert_valid;
/// Every committed device (`validation/profiles/*.json`), derived with the default policy, by
/// file stem.
fn committed_devices() -> Vec<(String, Device)> {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-validation/profiles");
let mut out = Vec::new();
for entry in std::fs::read_dir(&dir).expect("profiles") {
let path = entry.expect("entry").path();
if path.extension().is_none_or(|x| x != "json") {
continue;
}
let stem = path
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let text = std::fs::read_to_string(&path).expect("read");
let desc = DeviceDescription::from_khronos_json(&text, None).expect("description");
let device = Device::new(desc, DevicePolicy::default()).expect("device");
out.push((stem, device));
}
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
/// On every committed device the module is built, valid and within the profile where the device
/// has `shaderInt64`, and refused as `Feature::TileReach` needing it where it does not.
#[test]
fn the_module_is_valid_with_int64_and_refused_without() {
let (mut built, mut refused) = (0, 0);
for (name, device) in committed_devices() {
let profile = device.profile();
let int64 = profile
.fields()
.enabled
.features
.contains(&VkFeature::ShaderInt64);
match tile_reach_module(&device) {
Ok(m) => {
assert!(int64, "{name}");
assert!(!m.spirv.is_empty(), "{name}");
assert!(profile.check(&m.requirements).is_ok(), "{name}");
assert_valid(typed_module().expect("module"), profile);
built += 1;
}
Err(Error::Unsupported(u)) => {
assert!(!int64, "{name}");
assert_eq!(u.feature, Feature::TileReach, "{name}");
let needs = vec![vec![Capability::Feature(VkFeature::ShaderInt64)]];
assert_eq!(u.needs, Needs::AnyOf(needs), "{name}");
refused += 1;
}
Err(other) => panic!("{name}: {other}"),
}
}
assert!(built > 0 && refused > 0, "{built} built, {refused} refused");
}
/// A splitmix64 stream.
pub(super) struct Rng(pub(super) u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
}
fn word(&mut self) -> u32 {
self.next() as u32
}
/// A number in `[0, n)`.
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
/// True `k` times in `n`.
fn chance(&mut self, k: u64, n: u64) -> bool {
self.below(n) < k
}
pub(super) fn pick<X: Copy>(&mut self, xs: &[X]) -> X {
xs[self.below(xs.len() as u64) as usize]
}
/// A number in `[lo, hi)` on a grid of `1 / steps`.
fn grid(&mut self, lo: f64, hi: f64, steps: f64) -> f64 {
let n = ((hi - lo) * steps).max(1.0) as u64;
lo + self.below(n) as f64 / steps
}
}
/// Bits the arithmetic meets at its edges: zeros, subnormals, normals' bounds, the snap's limit
/// and its whole-number threshold, infinities and a NaN.
const EDGE_BITS: [u32; 20] = [
0x0000_0000,
0x8000_0000,
0x0000_0001,
0x8000_0001,
0x0040_0000,
0x007f_ffff,
0x0080_0000,
0x0080_0001,
0x3f00_0000,
0x3f80_0000,
0xbf80_0000,
0x3fc0_0000,
0x4a00_0000,
0x49ff_ffff,
0x4e00_0000,
0x4dff_ffff,
0x7f7f_ffff,
0x7f80_0000,
0xff80_0000,
0x7fc0_0000,
];
/// A point size in `[0, 511]` the extent's rounding meets: on its ties (an odd number of units,
/// an odd number of 1/32 pixels), beside them, or anywhere.
fn size_bits(rng: &mut Rng) -> u32 {
let size = match rng.below(5) {
0 => (2 * rng.below(256 * 255) + 1) as f32 / 256.0,
1 => (2 * rng.below(16 * 511) + 1) as f32 / 32.0,
2 => {
let tie = (2 * rng.below(16 * 511) + 1) as f32 / 32.0;
let s = f32::from_bits(tie.to_bits().wrapping_add(rng.pick(&[1, u32::MAX])));
s.clamp(0.0, POINT_SIZE_LIMIT)
}
3 => f32::from_bits(rng.word() & 0x43ff_ffff).min(POINT_SIZE_LIMIT),
_ => rng.grid(0.0, 511.0, 4096.0) as f32,
};
size.to_bits()
}
/// The kernel's division, multiplication and addition give Rust's `/`, `*` and `+` (a NaN for a
/// NaN), and its snap and point extent the reference's, bit for bit, on edge operands (zeros,
/// subnormals, the largest finite values, infinities, a NaN) and on 6000 random ones (any bits;
/// near-equal exponents, where a sum cancels; coordinates on and beside the snap's ties).
#[test]
fn the_kernels_arithmetic_is_the_references() {
let mut rng = Rng(0x7ea1_0d71);
let mut records: Vec<[u32; 3]> = Vec::new();
for x in EDGE_BITS {
for y in EDGE_BITS {
records.push([x, y, size_bits(&mut rng)]);
}
}
for _ in 0..6000 {
let x = match rng.below(4) {
0 => rng.word(),
// A coordinate on a tie of the snap (k + 1/2 units), or one bit beside one.
1 => {
let tie = (rng.below(1 << 22) as f64 * 2.0 + 1.0) / 512.0;
let tie = tie as f32 * rng.pick(&[1.0, -1.0]);
tie.to_bits().wrapping_add(rng.pick(&[0, 1, u32::MAX]))
}
// Exponents about the snap's thresholds.
2 => ((rng.below(40) as u32 + 115) << 23) | (rng.word() & 0x807f_ffff),
_ => (rng.grid(-1e5, 1e5, 65536.0) as f32).to_bits(),
};
let y = match rng.below(3) {
0 => rng.word(),
1 => (x & 0xff80_0000) ^ (rng.word() & 0x807f_ffff),
_ => (rng.grid(0.01, 16.0, 1024.0) as f32).to_bits(),
};
records.push([x, y, size_bits(&mut rng)]);
}
let words = ARITHMETIC_WORDS as usize;
let mut bytes = Vec::with_capacity(records.len() * words * 4);
for r in &records {
for w in 0..words {
bytes.extend(r.get(w).copied().unwrap_or(0).to_le_bytes());
}
}
let m = arithmetic_module().expect("module");
let cfg = Config {
workgroups: [(records.len() as u32).div_ceil(M::LOCAL_SIZE), 1, 1],
step_limit: 1 << 40,
..Config::default()
};
let res = Resources {
buffers: vec![buffer(PRIMITIVES, bytes)],
push: Vec::new(),
spec: Default::default(),
};
let out = run(&m, &cfg, res).expect("run").buffers.swap_remove(0);
let mut wrong = Vec::new();
for (i, r) in records.iter().enumerate() {
let w = |k: usize| word(&out, i * words + k);
let (x, y, size) = (
f32::from_bits(r[0]),
f32::from_bits(r[1]),
f32::from_bits(r[2]),
);
for (what, at, want) in [("/", 3, x / y), ("*", 4, x * y), ("+", 5, x + y)] {
let got = f32::from_bits(w(at));
if !(want.to_bits() == got.to_bits() || (want.is_nan() && got.is_nan())) {
wrong.push(format!(
"{x:e} {what} {y:e} ({:#x} {what} {:#x}): {got:e} ({:#x}), not {want:e} \
({:#x})",
r[0],
r[1],
w(at),
want.to_bits()
));
}
}
let snapped = (i64::from(w(7)) << 32) | i64::from(w(6));
let measured = w(8) == 1;
if (snapped, measured) != snap_clamped(x) {
let want = snap_clamped(x);
wrong.push(format!("snap {x:e}: {snapped} {measured}, not {want:?}"));
}
let extent = (i64::from(w(9)), i64::from(w(10)));
if extent != point_extent(size) {
let want = point_extent(size);
wrong.push(format!("point size {size:e}: {extent:?}, not {want:?}"));
}
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
}
/// The clipper holds the most vertices a polygon reaches ([`POLYGON`], 9): a hexagon whose
/// vertices lie by turns in front of the eye and behind it clips by the eye's plane to 9, which
/// only a polygon the clipper's rounding left not convex can be; and on seeded polygons of 2 to 6
/// vertices, by each plane, the clipper's polygon is the reference's, bit for bit.
#[test]
fn the_clipper_holds_its_most_vertices() {
let planes: [fn(&[f32; 4]) -> f32; 3] = [|v| v[2], |v| v[3] - v[2], |v| v[3]];
let hexagon: Vec<[f32; 4]> = (0..6)
.map(|j| {
let a = j as f32 * std::f32::consts::FRAC_PI_3;
[a.cos(), a.sin(), 0.5, if j % 2 == 0 { 1.0 } else { -0.5 }]
})
.collect();
assert_eq!(clip(&hexagon, planes[2]).len(), POLYGON as usize);
let mut cases = vec![(2, hexagon)];
let mut rng = Rng(0xc11b_0009);
for _ in 0..600 {
let n = rng.pick(&[2, 3, 4, 5, 6]);
let plane = rng.below(3) as u32;
let polygon = (0..n)
.map(|_| [0; 4].map(|_| rng.grid(-2.0, 2.0, 64.0) as f32))
.collect();
cases.push((plane, polygon));
}
let words = CLIP_WORDS as usize;
let mut bytes = Vec::with_capacity(cases.len() * words * 4);
for (plane, polygon) in &cases {
let mut record = vec![0u32; words];
record[0] = *plane;
record[1] = polygon.len() as u32;
for (j, v) in polygon.iter().enumerate() {
for (c, x) in v.iter().enumerate() {
record[2 + 4 * j + c] = x.to_bits();
}
}
bytes.extend(record.iter().flat_map(|w| w.to_le_bytes()));
}
let m = clip_module().expect("module");
let cfg = Config {
workgroups: [(cases.len() as u32).div_ceil(M::LOCAL_SIZE), 1, 1],
step_limit: 1 << 40,
..Config::default()
};
let res = Resources {
buffers: vec![buffer(PRIMITIVES, bytes)],
push: Vec::new(),
spec: Default::default(),
};
let out = run(&m, &cfg, res).expect("run").buffers.swap_remove(0);
let (mut wrong, mut most) = (Vec::new(), 0);
for (i, (plane, polygon)) in cases.iter().enumerate() {
let w = |k: usize| word(&out, i * words + k);
let want = clip(polygon, planes[*plane as usize]);
let got: Vec<[f32; 4]> = (0..w(1) as usize)
.map(|j| [0, 1, 2, 3].map(|c| f32::from_bits(w(2 + 4 * j + c))))
.collect();
let bits =
|p: &[[f32; 4]]| -> Vec<u32> { p.iter().flatten().map(|x| x.to_bits()).collect() };
if bits(&got) != bits(&want) {
wrong.push(format!(
"plane {plane} of {polygon:?}: {got:?}, not {want:?}"
));
}
most = most.max(got.len());
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
assert_eq!(most, POLYGON as usize);
}
fn buffer(slot: ResourceSlot, bytes: Vec<u8>) -> Buffer {
Buffer {
slot: Some(slot),
address: None,
bytes,
}
}
/// Word `i` of little-endian bytes.
fn word(bytes: &[u8], i: usize) -> u32 {
u32::from_le_bytes(bytes[4 * i..4 * i + 4].try_into().expect("a word"))
}
/// One primitive of a pass: its reference form, the kind the kernel reads (its own, or one that
/// is none), the index of its state and its layer.
#[derive(Clone, Copy, Debug)]
pub(super) struct Drawn {
prim: Primitive,
kind: u32,
state: u32,
layer: u32,
}
impl Drawn {
pub(super) fn of(prim: Primitive, state: u32, layer: u32) -> Drawn {
let kind = match prim {
Primitive::Point(..) => M::POINT,
Primitive::Line(_) => M::LINE,
Primitive::Triangle(_) => M::TRIANGLE,
};
Drawn {
prim,
kind,
state,
layer,
}
}
pub(super) fn record(&self) -> [u8; 64] {
let none = [0.0; 4];
let (size, vertices) = match self.prim {
Primitive::Point(v, size) => (size, [v, none, none]),
Primitive::Line([a, b]) => (1.0, [a, b, none]),
Primitive::Triangle(t) => (1.0, t),
};
M::primitive(self.kind, self.state, self.layer, size, vertices)
}
}
/// A pass the kernel bins: its render area, samples and layers, the states its primitives were
/// drawn under (their area and samples the pass's), and its primitives.
#[derive(Clone, Debug)]
pub(super) struct Pass {
pub(super) area: [u32; 2],
pub(super) samples: u32,
pub(super) layers: u32,
pub(super) states: Vec<Raster>,
pub(super) drawn: Vec<Drawn>,
}
/// What a pass binned: the tiles `[x, y]` each slice reached, and the primitives counted near-far
/// and unmeasured.
#[derive(Debug, PartialEq, Eq)]
pub(super) struct Binned {
pub(super) slices: Vec<BTreeSet<[u32; 2]>>,
pub(super) near_far: u32,
pub(super) unmeasured: u32,
}
pub(super) fn cull(c: Cull) -> u32 {
match c {
Cull::None => 0,
Cull::Front => 1,
Cull::Back => 2,
}
}
pub(super) fn winding(w: Winding) -> u32 {
match w {
Winding::Clockwise => 0,
Winding::CounterClockwise => 1,
}
}
impl Pass {
/// The tiles of a slice's row and column.
pub(super) fn grid(&self) -> [u32; 2] {
let th = if self.samples == 4 { 16 } else { 32 };
[self.area[0].div_ceil(32), self.area[1].div_ceil(th)]
}
/// The rule's answer: each primitive's reach by the reference function, into the slice it
/// renders (a layer past the pass's renders its first); a state past the pass's or a kind
/// that is none reach nothing, flagged unmeasured.
pub(super) fn rule(&self) -> Binned {
let mut out = Binned {
slices: vec![BTreeSet::new(); self.layers as usize],
near_far: 0,
unmeasured: 0,
};
for d in &self.drawn {
let mut flags = Flags::default();
match self.states.get(d.state as usize) {
Some(_) if d.kind > M::TRIANGLE => flags.unmeasured = true,
None => flags.unmeasured = true,
Some(state) => {
let mut raster = *state;
raster.area = self.area;
raster.samples = self.samples;
let tiles = reach(&raster, &d.prim, &mut flags);
let slice = if d.layer < self.layers { d.layer } else { 0 };
out.slices[slice as usize].extend(tiles);
}
}
out.near_far += u32::from(flags.near_far);
out.unmeasured += u32::from(flags.unmeasured);
}
out
}
/// The kernel's answer, through the interpreter in both invocation orders (alike).
fn kernel(&self, m: &TypedModule) -> Binned {
let prims: Vec<u8> = self.drawn.iter().flat_map(|d| d.record()).collect();
let count = self.drawn.len() as u32;
let mut pass = M::header(self.area, self.samples, self.layers, count).to_vec();
for s in &self.states {
pass.extend(M::state(
s.viewport,
s.scissor,
cull(s.cull),
winding(s.winding),
u32::from(s.clamp),
));
}
let words = M::mask_words(self.area, self.samples, self.layers).max(1) as usize;
let mut outs = Vec::new();
for order in [Order::Forward, Order::Reverse] {
let res = Resources {
buffers: vec![
buffer(PRIMITIVES, prims.clone()),
buffer(PASS, pass.clone()),
buffer(TILES, vec![0; 4 * words]),
],
push: Vec::new(),
spec: Default::default(),
};
let cfg = Config {
order,
workgroups: [count.div_ceil(M::LOCAL_SIZE).max(1), 1, 1],
step_limit: 1 << 40,
..Config::default()
};
outs.push(run(m, &cfg, res).expect("run").buffers);
}
assert_eq!(outs[0], outs[1], "order independent");
let buffers = &outs[0];
let [gx, gy] = self.grid().map(|g| g as usize);
let mut slices = vec![BTreeSet::new(); self.layers as usize];
for i in 0..words {
let w = word(&buffers[2], i);
for bit in (0..32).filter(|b| w >> b & 1 == 1) {
let tile = 32 * i + bit;
let (slice, at) = (tile / (gx * gy), tile % (gx * gy));
assert!(slice < slices.len(), "a bit past the pass's tiles");
slices[slice].insert([(at % gx) as u32, (at / gx) as u32]);
}
}
Binned {
slices,
near_far: word(&buffers[1], M::NEAR_FAR_WORD as usize),
unmeasured: word(&buffers[1], M::UNMEASURED_WORD as usize),
}
}
/// Where the kernel and the rule differ: each primitive that differs alone, else the pass.
pub(super) fn differences(&self, m: &TypedModule) -> Vec<String> {
if self.kernel(m) == self.rule() {
return Vec::new();
}
let mut out = Vec::new();
for d in &self.drawn {
let alone = Pass {
drawn: vec![*d],
..self.clone()
};
let (kernel, rule) = (alone.kernel(m), alone.rule());
if kernel != rule {
let state = self.states.get(d.state as usize);
out.push(format!(
"{d:?} under {state:?} (area {:?}, {} samples): kernel {kernel:?}, rule {rule:?}",
self.area, self.samples
));
}
}
if out.is_empty() {
out.push(format!("the pass {self:?} differs, no primitive alone"));
}
out
}
}
/// The pass of a measured case: its draw's primitives, under its one state.
fn pass_of(row: &Row) -> Pass {
Pass {
area: row.raster.area,
samples: row.raster.samples,
layers: row.slices,
states: vec![row.raster],
drawn: row
.primitives()
.into_iter()
.map(|p| Drawn::of(p, 0, row.layer))
.collect(),
}
}
/// On every measured case drawn directly or indirectly, the kernel bins what the rule does, and,
/// where the case's answer is its primitives' reach (no attachment cleared and stored), the
/// tiles the M4 reached.
#[test]
fn the_kernel_reaches_every_measured_answer() {
let m = typed_module().expect("module");
let mut rows = measured::rows();
rows.extend(measured::later_rows());
rows.extend(points::rows());
let mut wrong = Vec::new();
let mut checked = 0;
for row in rows
.iter()
.filter(|r| matches!(r.draw, Draw::Direct | Draw::Indirect))
{
let pass = pass_of(row);
let kernel = pass.kernel(&m);
let rule = pass.rule();
if kernel != rule {
wrong.push(format!(
"{}/{}: kernel {kernel:?}, rule {rule:?}",
row.probe, row.name
));
}
if matches!(row.other, Other::None | Other::ColorClearDontCare)
&& kernel.slices != row.measured()
{
wrong.push(format!(
"{}/{}: kernel {:?}, measured {:?}",
row.probe,
row.name,
kernel.slices,
row.measured()
));
}
checked += 1;
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
assert!(checked > 300, "{checked} cases");
}
/// A random state over a render area of `area`: Metal's defaults, or a viewport and a scissor of
/// its own (past the area too, the viewport flipped at times), any cull mode and winding, depth
/// clipped or clamped.
fn state(rng: &mut Rng, area: [u32; 2]) -> Raster {
let mut r = Raster::over(area);
let [w, h] = area.map(f64::from);
if rng.chance(1, 2) {
let ox = rng.grid(-w / 4.0, w, 512.0);
let oy = rng.grid(-h / 4.0, h, 512.0);
let vw = rng.grid(1.0, 1.5 * w + 1.0, 512.0);
let vh = rng.grid(1.0, 1.5 * h + 1.0, 512.0) * rng.pick(&[1.0, 1.0, 1.0, -1.0]);
r.viewport = [ox, oy, vw, vh].map(|c| c as f32);
}
if rng.chance(1, 2) {
let sx = rng.below(u64::from(area[0]) + 8) as u32;
let sy = rng.below(u64::from(area[1]) + 8) as u32;
let sw = rng.below(u64::from(area[0]) + 8) as u32;
let sh = rng.below(u64::from(area[1]) + 8) as u32;
r.scissor = [sx, sy, sw, sh];
}
r.cull = rng.pick(&[Cull::None, Cull::Front, Cull::Back]);
r.winding = rng.pick(&[Winding::Clockwise, Winding::CounterClockwise]);
r.clamp = rng.chance(1, 3);
r
}
/// A random pixel position about a render area of `area`: on or beside a tile's corner (within
/// 1/64 of a pixel, on 1/512 steps), anywhere about the area on 1/1024 steps, or far past it.
fn position(rng: &mut Rng, area: [u32; 2], tile: [u32; 2]) -> [f64; 2] {
let near = |rng: &mut Rng, extent: u32, size: u32| {
let k = rng.below(u64::from(extent / size) + 3) as f64 - 1.0;
k * f64::from(size) + (rng.below(17) as f64 - 8.0) / 512.0
};
let [w, h] = area.map(f64::from);
match rng.below(10) {
0..=3 => [near(rng, area[0], tile[0]), near(rng, area[1], tile[1])],
4..=8 => [
rng.grid(-40.0, w + 40.0, 1024.0),
rng.grid(-40.0, h + 40.0, 1024.0),
],
_ => [
rng.grid(-2e5, 2e5, 4.0) * rng.pick(&[1.0, 1e-3]),
rng.grid(-2e5, 2e5, 4.0) * rng.pick(&[1.0, 1e-3]),
],
}
}
/// The clip-space vertex at pixel `p` of a frame of `area` and depth `z`, at `w` (its
/// coordinates scaled by it), each rounded to `f32`.
fn vertex(area: [u32; 2], p: [f64; 2], z: f64, w: f64) -> [f32; 4] {
let [x, y, _, _] = clip_in(area, p[0], p[1], z);
[
(f64::from(x) * w) as f32,
(f64::from(y) * w) as f32,
(z * w) as f32,
w as f32,
]
}
/// A random depth and `w` for a primitive's vertices: within the depth range at `w = 1` mostly,
/// at times in perspective or across the near or far plane.
fn depth(rng: &mut Rng) -> (f64, f64) {
let z = match rng.chance(1, 5) {
true => rng.grid(-1.0, 2.0, 256.0),
false => rng.grid(0.0, 1.0, 256.0),
};
let w = match rng.chance(1, 3) {
true => rng.pick(&[0.5, 2.0, 3.0, 0.3, 7.25, 1.0e3]) * rng.grid(0.5, 2.0, 64.0),
false => 1.0,
};
(z, w)
}
/// `v` with one component at times replaced by a value the rule flags: not finite, subnormal,
/// huge, or a `w` at or behind the eye.
fn spoiled(rng: &mut Rng, mut v: [f32; 4]) -> [f32; 4] {
if rng.chance(1, 30) {
let c = rng.below(4) as usize;
v[c] = rng.pick(&[
f32::NAN,
f32::INFINITY,
f32::NEG_INFINITY,
1.0e-40,
-1.0e-40,
1.0e30,
-1.0e30,
0.0,
-1.0,
]);
}
v
}
/// A random point size: fractional, on the extent's ties, zero, past the largest, or flagged
/// (negative, not a number, subnormal).
fn point_size(rng: &mut Rng) -> f32 {
match rng.below(8) {
0 => rng.pick(&[0.0, 0.25, 1.0, 511.0, 511.5, 600.0, f32::INFINITY]),
1 => rng.pick(&[f32::NAN, -1.0, 1.0e-40, -0.0]),
2 => (2 * rng.below(2048) + 1) as f32 / 32.0,
3 => (2 * rng.below(8192) + 1) as f32 / 256.0,
_ => rng.grid(0.0, 80.0, 512.0) as f32,
}
}
/// A random primitive about a render area of `area`: a point, a line (at times of no length or
/// at 45 degrees), or a triangle (at times small, for the small-primitive cull).
fn primitive(rng: &mut Rng, area: [u32; 2], tile: [u32; 2]) -> Primitive {
let (z, w) = depth(rng);
let at = |rng: &mut Rng, p: [f64; 2]| {
let (dz, dw) = match rng.chance(1, 4) {
true => depth(rng),
false => (z, w),
};
spoiled(rng, vertex(area, p, dz, dw))
};
let p = position(rng, area, tile);
match rng.below(10) {
0..=2 => Primitive::Point(at(rng, p), point_size(rng)),
3..=5 => {
let q = match rng.below(6) {
0 => p,
1 => {
let d = rng.grid(-40.0, 40.0, 256.0);
[p[0] + d, p[1] + d * rng.pick(&[1.0, -1.0])]
}
_ => position(rng, area, tile),
};
Primitive::Line([at(rng, p), at(rng, q)])
}
_ => {
let small = rng.chance(1, 2);
let near = |rng: &mut Rng| match small {
true => [
p[0] + rng.grid(-4.0, 4.0, 64.0),
p[1] + rng.grid(-4.0, 4.0, 64.0),
],
false => position(rng, area, tile),
};
let (b, c) = (near(rng), near(rng));
Primitive::Triangle([at(rng, p), at(rng, b), at(rng, c)])
}
}
}
/// A random pass of `area` and `samples`: a few states; each primitive in a slice of its own
/// (slice 0 holding those whose layer is past the pass's), a few under a state past the pass's
/// or of a kind that is none.
pub(super) fn random_pass(rng: &mut Rng, area: [u32; 2], samples: u32, count: u32) -> Pass {
let states: Vec<Raster> = (0..1 + rng.below(3)).map(|_| state(rng, area)).collect();
let tile = [32, if samples == 4 { 16 } else { 32 }];
let layers = count + 1;
let drawn = (0..count)
.map(|i| {
let prim = primitive(rng, area, tile);
let state = match rng.chance(1, 40) {
true => states.len() as u32 + rng.below(3) as u32,
false => rng.below(states.len() as u64) as u32,
};
let layer = match rng.chance(1, 20) {
true => layers + rng.below(4) as u32,
false => i + 1,
};
let mut d = Drawn::of(prim, state, layer);
if rng.chance(1, 40) {
d.kind = rng.pick(&[3, 4, u32::MAX]);
}
d
})
.collect();
Pass {
area,
samples,
layers,
states,
drawn,
}
}
/// On seeded random passes (render areas of a pixel to a few tiles, 1, 2 and 4 samples and
/// other counts, viewports, scissors, culls and windings, depth clipped and clamped; points,
/// lines and triangles about tile edges, in perspective, across the near and far planes, with
/// values the rule flags), the kernel bins what the rule does.
#[test]
fn the_kernel_bins_what_the_rule_does_on_random_passes() {
let m = typed_module().expect("module");
let mut rng = Rng(0x0d67_1a2b);
let areas = [
[128, 128],
[96, 64],
[200, 72],
[33, 31],
[256, 40],
[1, 1],
[64, 200],
[160, 96],
];
let mut wrong = Vec::new();
for _ in 0..96 {
let area = rng.pick(&areas);
let samples = rng.pick(&[1, 1, 2, 4, 4, 3, 8]);
let pass = random_pass(&mut rng, area, samples, 32);
wrong.extend(pass.differences(&m));
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
}
/// On the largest render areas (16384 pixels a side and others large), small primitives about
/// tile edges anywhere in the area, at every sample count, bin as the rule does.
#[test]
fn the_kernel_bins_what_the_rule_does_on_large_areas() {
let m = typed_module().expect("module");
let mut rng = Rng(0x1a29_e5ee);
let mut wrong = Vec::new();
for (area, samples) in [([16384, 16384], 1), ([16384, 9000], 4), ([12000, 16384], 2)] {
let tile = [32, if samples == 4 { 16 } else { 32 }];
let states = vec![Raster::over(area), state(&mut rng, area)];
let drawn = (0..6)
.map(|i| {
let [w, h] = area.map(f64::from);
let p = match rng.chance(1, 2) {
true => [
(rng.below(u64::from(area[0] / tile[0])) * u64::from(tile[0])) as f64
+ (rng.below(17) as f64 - 8.0) / 512.0,
(rng.below(u64::from(area[1] / tile[1])) * u64::from(tile[1])) as f64
+ (rng.below(17) as f64 - 8.0) / 512.0,
],
false => [rng.grid(0.0, w, 512.0), rng.grid(0.0, h, 512.0)],
};
let near = |rng: &mut Rng| {
[
p[0] + rng.grid(-24.0, 24.0, 256.0),
p[1] + rng.grid(-24.0, 24.0, 256.0),
]
};
let v = |q: [f64; 2]| vertex(area, q, 0.5, 1.0);
let prim = match i % 3 {
0 => Primitive::Point(v(p), point_size(&mut rng).min(64.0)),
1 => Primitive::Line([v(p), v(near(&mut rng))]),
_ => Primitive::Triangle([v(p), v(near(&mut rng)), v(near(&mut rng))]),
};
Drawn::of(prim, (i % 2) as u32, i as u32)
})
.collect();
let pass = Pass {
area,
samples,
layers: 6,
states,
drawn,
};
wrong.extend(pass.differences(&m));
}
assert!(wrong.is_empty(), "{}", wrong.join("\n"));
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,526 +0,0 @@
//! The tile reach rule (the module docs) as a plain function over one primitive's clip-space
//! vertices: the reference every measured case checks, and the kernel answers as.
//!
//! Arithmetic: a vertex's window position in `f32` (`x_w = (w / 2) * x_ndc + (o_x + w / 2)`, y
//! down, each operation rounded on its own), snapped to 1/256 of a pixel ties to even (the cases
//! measured cannot tell even from up), and every test after that in integers: a primitive's
//! closed area against a half-open rectangle by the separating axes of both (the rectangle's far
//! edges approached from inside, [`meets`]), a triangle's sample cull row by row of samples
//! ([`covers_sample`]), a point's square from its integer extent ([`point_extent`]).
use std::collections::BTreeSet;
/// Units of a pixel a vertex snaps to.
pub(super) const SUBPIXEL: i64 = 256;
/// The largest snapped coordinate the rule is measured near (1e5 pixels) is far below this (2^21
/// pixels): past it a coordinate is clamped and the answer flagged unmeasured. Below it every
/// product the kernel's integer tests form fits an `i64`.
pub(super) const COORDINATE_LIMIT: i64 = 1 << 29;
/// The largest point size Metal draws, in pixels: a larger size draws as this one.
pub(super) const POINT_SIZE_LIMIT: f32 = 511.0;
/// Which faces a draw culls.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Cull {
/// None.
None,
/// Front faces.
Front,
/// Back faces.
Back,
}
/// Which winding faces front.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Winding {
/// Clockwise in window coordinates (y down), Metal's default.
Clockwise,
/// Counter-clockwise.
CounterClockwise,
}
/// A draw's rasterization state: the pass's render area and samples, the encoder's viewport,
/// scissor, cull mode, winding and depth clip mode.
#[derive(Clone, Copy, Debug)]
pub(super) struct Raster {
/// The render area's width and height, in pixels.
pub area: [u32; 2],
/// The viewport's origin and size, in pixels.
pub viewport: [f32; 4],
/// The scissor rectangle's origin and size, in pixels.
pub scissor: [u32; 4],
/// The cull mode.
pub cull: Cull,
/// The front-facing winding.
pub winding: Winding,
/// Whether depth clamps rather than clips.
pub clamp: bool,
/// The pass's samples per pixel: 1, 2 or 4.
pub samples: u32,
}
impl Raster {
/// Metal's defaults over a render area of `area`: the viewport and scissor of the area, no
/// cull, clockwise front faces, depth clipped, one sample.
pub(super) fn over(area: [u32; 2]) -> Raster {
Raster {
area,
viewport: [0.0, 0.0, area[0] as f32, area[1] as f32],
scissor: [0, 0, area[0], area[1]],
cull: Cull::None,
winding: Winding::Clockwise,
clamp: false,
samples: 1,
}
}
/// A tile's width and height in pixels: 32 by 32, 32 by 16 at 4 samples.
pub(super) fn tile(&self) -> [u32; 2] {
match self.samples {
4 => [32, 16],
_ => [32, 32],
}
}
/// The sample positions of a pixel in 1/256 units: Metal's defaults, Vulkan's standard ones
/// (a triangle holding each one alone reaches, at 2 and at 4 samples).
fn sample_offsets(&self) -> &'static [[i64; 2]] {
match self.samples {
2 => &[[192, 192], [64, 64]],
4 => &[[96, 32], [224, 96], [32, 160], [160, 224]],
_ => &[[128, 128]],
}
}
/// The half-open rectangle `[x0, x1) x [y0, y1)`, in 1/256 units, that clips every
/// primitive: the viewport's, the scissor's and the render area's.
fn region(&self) -> [i64; 4] {
let [ox, oy, w, h] = self.viewport;
let along = |o: f32, e: f32| {
let (a, b) = (snap_clamped(o).0, snap_clamped(o + e).0);
(a.min(b), a.max(b))
};
let (vx0, vx1) = along(ox, w);
let (vy0, vy1) = along(oy, h);
let [sx, sy, sw, sh] = self.scissor.map(i64::from);
let [aw, ah] = self.area.map(i64::from);
[
vx0.max(sx * SUBPIXEL).max(0),
vx1.min((sx + sw) * SUBPIXEL).min(aw * SUBPIXEL),
vy0.max(sy * SUBPIXEL).max(0),
vy1.min((sy + sh) * SUBPIXEL).min(ah * SUBPIXEL),
]
}
/// Whether the viewport's edges lie within the coordinates measured.
fn viewport_measured(&self) -> bool {
let [ox, oy, w, h] = self.viewport;
[ox, ox + w, oy, oy + h]
.into_iter()
.all(|c| snap_clamped(c).1)
}
/// The window position of the clip-space vertex `v`, unsnapped.
fn window(&self, v: [f32; 4]) -> [f32; 2] {
let [ox, oy, w, h] = self.viewport;
let (xn, yn) = (v[0] / v[3], v[1] / v[3]);
let (px, py) = (w * 0.5, h * 0.5);
[px * xn + (ox + px), -py * yn + (oy + py)]
}
}
/// One primitive's clip-space vertices.
#[derive(Clone, Copy, Debug)]
pub(super) enum Primitive {
/// A point and its size.
Point([f32; 4], f32),
/// A line's two ends.
Line([[f32; 4]; 2]),
/// A triangle's three vertices.
Triangle([[f32; 4]; 3]),
}
/// Why the tiles a primitive reached may not be Metal's.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct Flags {
/// A primitive crossed the near or far plane under depth clipping: its reach is that of the
/// clipped polygon, whose new vertices Apple's clipper may place otherwise (unmeasured).
pub near_far: bool,
/// A case the measurements do not cover: a vertex not finite, with a subnormal component, at
/// or behind the eye, or past the coordinates measured; a viewport past them; a line of no
/// length; a point past the depth range, or of a size negative, not a number or subnormal.
pub unmeasured: bool,
}
/// The tiles `[x, y]` that `prim`, drawn under `raster`, reaches.
pub(super) fn reach(raster: &Raster, prim: &Primitive, flags: &mut Flags) -> BTreeSet<[u32; 2]> {
let mut tiles = BTreeSet::new();
if !raster.viewport_measured() {
flags.unmeasured = true;
}
match *prim {
Primitive::Point(v, size) => point(raster, v, size, flags, &mut tiles),
Primitive::Line(ends) => line(raster, ends, flags, &mut tiles),
Primitive::Triangle(vertices) => triangle(raster, vertices, flags, &mut tiles),
}
tiles
}
/// Every tile of the render area, as a pass's clear reaches it.
pub(super) fn every_tile(raster: &Raster) -> BTreeSet<[u32; 2]> {
let [tw, th] = raster.tile();
let [w, h] = raster.area;
(0..h.div_ceil(th))
.flat_map(|y| (0..w.div_ceil(tw)).map(move |x| [x, y]))
.collect()
}
/// The coordinate `c` snapped to 1/256, and whether it lay within the coordinates measured.
pub(super) fn snap_clamped(c: f32) -> (i64, bool) {
let scaled = f64::from(c) * SUBPIXEL as f64;
if !scaled.is_finite() {
return (0, false);
}
let limit = COORDINATE_LIMIT as f64;
if scaled.abs() >= limit {
return (scaled.clamp(-limit, limit) as i64, false);
}
(scaled.round_ties_even() as i64, true)
}
/// The snapped window position of the clip-space vertex `v`.
fn snapped(raster: &Raster, v: [f32; 4], flags: &mut Flags) -> [i64; 2] {
let [x, y] = raster.window(v);
let (x, xi) = snap_clamped(x);
let (y, yi) = snap_clamped(y);
if !(xi && yi) {
flags.unmeasured = true;
}
[x, y]
}
/// The planes a primitive is clipped by, as signed distances (inside where not negative):
/// `z >= 0` and `z <= w` under depth clipping.
fn depth_planes(raster: &Raster) -> Vec<fn(&[f32; 4]) -> f32> {
let near: fn(&[f32; 4]) -> f32 = |v| v[2];
let far: fn(&[f32; 4]) -> f32 = |v| v[3] - v[2];
match raster.clamp {
true => Vec::new(),
false => vec![near, far],
}
}
/// `polygon` clipped by the plane `distance` (Sutherland-Hodgman, in `f32`); a polygon of two
/// vertices is a segment.
pub(super) fn clip(polygon: &[[f32; 4]], distance: fn(&[f32; 4]) -> f32) -> Vec<[f32; 4]> {
let mut out = Vec::new();
let n = polygon.len();
let edges = if n == 2 { 1 } else { n };
for i in 0..edges {
let (a, b) = (polygon[i], polygon[(i + 1) % n]);
let (da, db) = (distance(&a), distance(&b));
if da >= 0.0 {
out.push(a);
}
if (da >= 0.0) != (db >= 0.0) {
let t = da / (da - db);
out.push([0, 1, 2, 3].map(|k| a[k] + t * (b[k] - a[k])));
}
if n == 2 && db >= 0.0 {
out.push(b);
}
}
out
}
/// `vertices` clipped by the depth planes (flagging a crossing) and by `w > 0` (flagging a
/// vertex at or behind the eye); empty where wholly past one plane.
fn depth_clipped(raster: &Raster, vertices: &[[f32; 4]], flags: &mut Flags) -> Vec<[f32; 4]> {
if vertices.iter().flatten().any(|c| !c.is_finite()) {
flags.unmeasured = true;
return Vec::new();
}
if vertices.iter().flatten().any(|c| c.is_subnormal()) {
flags.unmeasured = true;
}
let mut polygon = vertices.to_vec();
for plane in depth_planes(raster) {
if polygon.iter().all(|v| plane(v) < 0.0) {
return Vec::new();
}
if polygon.iter().any(|v| plane(v) < 0.0) {
flags.near_far = true;
polygon = clip(&polygon, plane);
}
}
if polygon.iter().any(|v| v[3] <= 0.0) {
flags.unmeasured = true;
polygon = clip(&polygon, |v| v[3]);
}
polygon
}
/// A triangle's reach (the module docs).
fn triangle(
raster: &Raster,
vertices: [[f32; 4]; 3],
flags: &mut Flags,
tiles: &mut BTreeSet<[u32; 2]>,
) {
let polygon = depth_clipped(raster, &vertices, flags);
if polygon.len() < 3 {
return;
}
let points: Vec<[i64; 2]> = polygon.iter().map(|&v| snapped(raster, v, flags)).collect();
for i in 1..points.len() - 1 {
let t = [points[0], points[i], points[i + 1]];
let area = cross(t[0], t[1], t[2]);
if area == 0 {
continue;
}
// Clockwise in window coordinates, y down, is a positive area.
let front = (area > 0) == (raster.winding == Winding::Clockwise);
let culled = match raster.cull {
Cull::None => false,
Cull::Front => front,
Cull::Back => !front,
};
if culled || sample_culled(raster, t, area.signum()) {
continue;
}
let polygon: Vec<[i128; 2]> = t.iter().map(|p| p.map(i128::from)).collect();
bin(raster, &polygon, 1, tiles);
}
}
/// Twice the signed area of the triangle `a`, `b`, `c`.
fn cross(a: [i64; 2], b: [i64; 2], c: [i64; 2]) -> i128 {
let d = |p: [i64; 2], q: [i64; 2]| [i128::from(q[0] - p[0]), i128::from(q[1] - p[1])];
let (u, v) = (d(a, b), d(a, c));
u[0] * v[1] - u[1] * v[0]
}
/// `n / d` rounded down.
fn floor_div(n: i128, d: i128) -> i128 {
let q = n / d;
if (n % d != 0) && ((n < 0) != (d < 0)) {
q - 1
} else {
q
}
}
/// `n / d` rounded up.
fn ceil_div(n: i128, d: i128) -> i128 {
-floor_div(-n, d)
}
/// Whether the small-primitive cull drops the triangle `t` of orientation `sign`: one whose box
/// (closed) holds few sample positions and whose closed area holds none of them. The cull tests a
/// box of at most 12 positions at 1 and 2 samples and of at most 24 at 4, in every shape measured
/// (1 by 12 to 12 by 1 pixel centres; slopes from 1 in 3 to 3 in 1 at 2 and 4 samples), and
/// keeps one of more.
fn sample_culled(raster: &Raster, t: [[i64; 2]; 3], sign: i128) -> bool {
let tested = match raster.samples {
4 => 24,
_ => 12,
};
box_samples(raster, t) <= tested && !covers_sample(raster, t, sign)
}
/// The sample positions the closed box of `t` holds.
fn box_samples(raster: &Raster, t: [[i64; 2]; 3]) -> i128 {
let unit = i128::from(SUBPIXEL);
let span = |axis: usize, offset: i64| {
let lo = i128::from(t.iter().map(|p| p[axis]).min().unwrap_or(0));
let hi = i128::from(t.iter().map(|p| p[axis]).max().unwrap_or(0));
let o = i128::from(offset);
(floor_div(hi - o, unit) - ceil_div(lo - o, unit) + 1).max(0)
};
raster
.sample_offsets()
.iter()
.map(|&[ox, oy]| span(0, ox) * span(1, oy))
.sum()
}
/// Whether the closed triangle `t`, of orientation `sign`, holds a sample of the plane: row by
/// row of sample positions, the span the three edges leave holds one.
fn covers_sample(raster: &Raster, t: [[i64; 2]; 3], sign: i128) -> bool {
let unit = i128::from(SUBPIXEL);
let min_y = i128::from(t.iter().map(|p| p[1]).min().unwrap_or(0));
let max_y = i128::from(t.iter().map(|p| p[1]).max().unwrap_or(0));
for &[ox, oy] in raster.sample_offsets() {
let (ox, oy) = (i128::from(ox), i128::from(oy));
for row in ceil_div(min_y - oy, unit)..=floor_div(max_y - oy, unit) {
let y = row * unit + oy;
let (mut lo, mut hi) = (i128::MIN, i128::MAX);
let mut empty = false;
for k in 0..3 {
let (a, b) = (t[k].map(i128::from), t[(k + 1) % 3].map(i128::from));
// sign * cross(b - a, (x, y) - a) >= 0, as alpha - beta * x >= 0.
let beta = sign * (b[1] - a[1]);
let alpha = sign * ((b[0] - a[0]) * (y - a[1]) + (b[1] - a[1]) * a[0]);
match beta.signum() {
1 => hi = hi.min(floor_div(alpha, beta)),
-1 => lo = lo.max(ceil_div(alpha, beta)),
_ => empty |= alpha < 0,
}
}
if !empty && lo <= hi && ceil_div(lo - ox, unit) <= floor_div(hi - ox, unit) {
return true;
}
}
}
false
}
/// Add each tile the closed convex `polygon` meets, its vertices in 1/256 units times `scale`,
/// within the region of `raster`.
fn bin(raster: &Raster, polygon: &[[i128; 2]], scale: i128, tiles: &mut BTreeSet<[u32; 2]>) {
let [x0, x1, y0, y1] = raster.region().map(i128::from);
let [tw, th] = raster.tile().map(|t| i128::from(t) * i128::from(SUBPIXEL));
let [w, h] = raster.area;
for ty in 0..h.div_ceil(raster.tile()[1]) {
for tx in 0..w.div_ceil(raster.tile()[0]) {
let (i, j) = (i128::from(tx), i128::from(ty));
let rect = [
x0.max(i * tw),
x1.min((i + 1) * tw),
y0.max(j * th),
y1.min((j + 1) * th),
];
if rect[0] < rect[1] && rect[2] < rect[3] && meets(polygon, scale, rect) {
tiles.insert([tx, ty]);
}
}
}
}
/// Whether the closed convex `polygon` (in 1/256 units times `scale`, of non-zero area) meets
/// the half-open rectangle `[x0, x1) x [y0, y1)` (in 1/256 units): no separating axis among the
/// rectangle's two and the polygon's edge normals, the rectangle's far edges taken an
/// infinitesimal inside it (a tie on one of them separates).
fn meets(polygon: &[[i128; 2]], scale: i128, [x0, x1, y0, y1]: [i128; 4]) -> bool {
let [x0, x1, y0, y1] = [x0, x1, y0, y1].map(|c| c * scale);
let xs = polygon.iter().map(|p| p[0]);
let ys = polygon.iter().map(|p| p[1]);
let (min_x, max_x) = (xs.clone().min(), xs.max());
let (min_y, max_y) = (ys.clone().min(), ys.max());
let (Some(min_x), Some(max_x), Some(min_y), Some(max_y)) = (min_x, max_x, min_y, max_y) else {
return false;
};
if !(min_x < x1 && max_x >= x0 && min_y < y1 && max_y >= y0) {
return false;
}
let n = polygon.len();
let doubled: i128 = (0..n)
.map(|i| {
let (p, q) = (polygon[i], polygon[(i + 1) % n]);
p[0] * q[1] - p[1] * q[0]
})
.sum();
let sign = doubled.signum();
for i in 0..n {
let (p, q) = (polygon[i], polygon[(i + 1) % n]);
// f(x, y) = sign * cross(q - p, (x, y) - p), not negative inside.
let gx = -sign * (q[1] - p[1]);
let gy = sign * (q[0] - p[0]);
let x = if gx > 0 { x1 } else { x0 };
let y = if gy > 0 { y1 } else { y0 };
let f = gx * (x - p[0]) + gy * (y - p[1]);
if f < 0 || (f == 0 && (gx > 0 || gy > 0)) {
return false;
}
}
true
}
/// A line's reach (the module docs).
fn line(raster: &Raster, ends: [[f32; 4]; 2], flags: &mut Flags, tiles: &mut BTreeSet<[u32; 2]>) {
let segment = depth_clipped(raster, &ends, flags);
if segment.len() < 2 {
return;
}
let [p, q] = [segment[0], segment[1]].map(|v| snapped(raster, v, flags).map(i128::from));
let (dx, dy) = (q[0] - p[0], q[1] - p[1]);
let half = i128::from(SUBPIXEL / 2);
if dx == 0 && dy == 0 {
flags.unmeasured = true;
let square = [[-1, -1], [1, -1], [1, 1], [-1, 1]]
.map(|[sx, sy]| [p[0] + sx * half, p[1] + sy * half]);
bin(raster, &square, 1, tiles);
return;
}
// Scaled by the major axis's extent: the ends move half a pixel along the major axis, along
// the line, and the sides lie half a pixel each way across it.
let x_major = dx.abs() > dy.abs();
let scale = if x_major { dx.abs() } else { dy.abs() };
let along = [half * dx, half * dy];
let across = match x_major {
true => [0, half * scale],
false => [half * scale, 0],
};
let (p, q) = (p.map(|c| c * scale), q.map(|c| c * scale));
let start = [p[0] - along[0], p[1] - along[1]];
let end = [q[0] + along[0], q[1] + along[1]];
let quad = [
[start[0] - across[0], start[1] - across[1]],
[end[0] - across[0], end[1] - across[1]],
[end[0] + across[0], end[1] + across[1]],
[start[0] + across[0], start[1] + across[1]],
];
bin(raster, &quad, scale, tiles);
}
/// Where a point of `size` pixels (not negative, at most [`POINT_SIZE_LIMIT`]) reaches about its
/// snapped centre, in 1/256 units: how far back from the centre its square starts, along x and
/// along y, and its extent from there. It starts half its size back, the start rounded half up
/// (the left and top edges reach from more than half a unit past a tile's edge), and spans its
/// size rounded to the nearest 1/16 of a pixel, a half up (the right and bottom edges follow from
/// the left and top ones).
pub(super) fn point_extent(size: f32) -> (i64, i64) {
// Exact in f64: an f32 size below 512 times 256.
let units = f64::from(size) * SUBPIXEL as f64;
let back = (units / 2.0 - 0.5).ceil() as i64;
let extent = ((units / 16.0 + 0.5).floor() * 16.0) as i64;
(back, extent)
}
/// A point's reach (the module docs).
fn point(
raster: &Raster,
v: [f32; 4],
size: f32,
flags: &mut Flags,
tiles: &mut BTreeSet<[u32; 2]>,
) {
if v.iter().any(|c| !c.is_finite()) || v[3] <= 0.0 {
flags.unmeasured = true;
return;
}
if v.iter().any(|c| c.is_subnormal()) {
flags.unmeasured = true;
}
if depth_planes(raster).iter().any(|plane| plane(&v) < 0.0) {
flags.unmeasured = true;
return;
}
let size = match size >= 0.0 {
true => size,
false => {
flags.unmeasured = true;
0.0
}
};
if size.is_subnormal() {
flags.unmeasured = true;
}
let (back, extent) = point_extent(size.min(POINT_SIZE_LIMIT));
let [cx, cy] = snapped(raster, v, flags);
let [x0, y0] = [cx - back, cy - back].map(i128::from);
let [x1, y1] = [x0, y0].map(|c| c + i128::from(extent));
bin(raster, &[[x0, y0], [x1, y0], [x1, y1], [x0, y1]], 1, tiles);
}
-602
View File
@@ -1,602 +0,0 @@
//! An extended-range or padded 10-bit texture's words as Metal's tile store leaves them.
//!
//! A render pass on an Apple GPU stores its attachments a 32 x 32 tile at a time. A pass that
//! loads a color attachment of an extended-range format (`BGR10_XR`, `BGRA10_XR`,
//! `RGB10A8_2P_XR10`, their `_sRGB` twins), a padded 10-bit one (`R10Unorm_X6`,
//! `RG10Unorm_X12`, their `_sRGB` twins) or `RGB10A2Unorm_sRGB` and records a draw writes every
//! texel of each tile it stores back, where a channel a fragment writes takes the write; every
//! other texel keeps its codes, the bits they leave unused made canonical (on an Apple M4 and the
//! consumer's Apple M3 Max):
//!
//! - `BGR10_XR`'s word: bits 30 and 31 set;
//! - `BGRA10_XR`'s four 16-bit fields: each field's low six bits cleared, and the alpha field's
//! code clamped to `[384, 894]`;
//! - the two-plane formats' color word: bits 30 and 31 cleared (the alpha byte kept);
//! - a padded 16-bit word: its low six bits cleared, an `_sRGB` twin's code through Metal's table
//! (`ExtendedRange::load_code`: 23 codes of `R10Unorm_X6_sRGB` move, 1021 of
//! `RG10Unorm_X12_sRGB`);
//! - `RGB10A2Unorm_sRGB`'s word: each color field's code through `R10Unorm_X6_sRGB`'s table, alpha's
//! kept (an Apple M3 Max under macOS 27.0.1: 260 of 4096 words move);
//! - a bfloat format's 16-bit code (`R16Bfloat`, `RG16Bfloat`, `RGBA16Bfloat`): its value through
//! `half` to nearest even and back to the nearest bfloat code, ties to even, a NaN `0x7fc0`
//! (`ExtendedRange::load_code`; on an Apple M4 under macOS 27.0.1: 56,829 of the
//! 65,536 codes move, in every tile a draw reaches).
//!
//! A consumer copies the region's texels, row after row, into a buffer of words, one dispatch of
//! [`unused_bits_module`] of the texture's form rewrites the words of the tiles a mask names, and
//! it copies them back before the pass: the pass's write masks, discards, tests and uncovered
//! texels then keep Metal's words.
//!
//! **The module** (one per device, format and [`TexelWords`]). One `GLCompute` entry `main` with
//! local size ([`UnusedBitsModule::LOCAL_SIZE`], 1, 1), no push constants, and three storage
//! buffers of 4-byte words in set 0:
//!
//! - [`WORDS_BINDING`](UnusedBitsModule::WORDS_BINDING): the texels, each row
//! `row_words` words (its texels, then any padding to a word), the rows of each layer
//! `layer_rows` apart, layer after layer, from the region's row `first_row`;
//! - [`TILES_BINDING`](UnusedBitsModule::TILES_BINDING): the tile mask, one bit a 32 x 32 tile
//! (bit `t % 32` of word `t / 32`), tile `t = (layer * tile_rows + y / 32) * tiles_per_row +
//! x / 32` of the texel at `(x, y)` of a layer, `tile_rows = ceil(layer_rows / 32)`;
//! - [`SHAPE_BINDING`](UnusedBitsModule::SHAPE_BINDING): `[row_words, first_row, layer_rows,
//! tiles_per_row]` ([`UnusedBitsModule::shape`]).
//!
//! Invocation `i` below the texels' words rewrites word `i` where its texel's tile's bit is set
//! (a tile past the mask's words is not); one past them writes nothing. A consumer whose words
//! exceed `maxStorageBufferRange` or `maxComputeWorkGroupCount[0]` workgroups binds them in
//! bands of rows, each with its `first_row`, one dispatch each: no word reads another.
//!
//! **Synchronization** (consumer): the copy into the words and the mask's and shape's writes
//! (`TRANSFER_WRITE`) → `SHADER_STORAGE_READ` and `SHADER_STORAGE_WRITE` in `COMPUTE_SHADER`
//! before the dispatch; its writes → `TRANSFER_READ` before the words are copied back.
use std::sync::Arc;
use crate::budget::{Budget, Meter};
use crate::device::requirements::Requirements;
use crate::device::Device;
use crate::error::{Error, Feature, InternalError, InternalKind, Unsupported};
use crate::metal::format::ExtendedRange;
use crate::metal::PixelFormat;
use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, Symbol};
use crate::spirv::builder::constructs::{ArmEnd, ArmFn};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{GlobalId, TypeId, Value};
use crate::spirv::ir::{
natural_layout, BinOp, ConstBits, Constant, ExecMode, ExecModel, GlslOp, IoDir, LayoutRule,
MemAccess, StorageClass, Type, TypedModule,
};
/// The crate-owned unused bits module of one device, format and [`TexelWords`], validated like
/// any output: the words of the texels Metal's tile store rewrites (the module docs).
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnusedBitsModule {
/// SPIR-V 1.5 words, entry point `main`, its bindings numbered as below in set 0.
pub spirv: Arc<[u32]>,
/// What the module needs from the device (within every Vulkan 1.2 device).
pub requirements: Requirements,
}
impl UnusedBitsModule {
/// Descriptor set of the bindings.
pub const SET: u32 = 0;
/// The texels' words, a storage buffer the dispatch rewrites in place.
pub const WORDS_BINDING: u32 = 0;
/// The tile mask, a storage buffer of one bit a tile.
pub const TILES_BINDING: u32 = 1;
/// The shape ([`shape`](Self::shape)), a storage buffer of [`SHAPE_WORDS`](Self::SHAPE_WORDS)
/// words.
pub const SHAPE_BINDING: u32 = 2;
/// Invocations of one workgroup, along x: one 4-byte word each.
pub const LOCAL_SIZE: u32 = 64;
/// The side of a tile, in texels.
pub const TILE: u32 = 32;
/// The shape's words.
pub const SHAPE_WORDS: u32 = 4;
/// The shape's bytes: each row's words, the region's row of the first word bound, each
/// layer's rows, and the tiles of a layer's row of tiles (the module docs).
pub fn shape(row_words: u32, first_row: u32, layer_rows: u32, tiles_per_row: u32) -> [u8; 16] {
let mut bytes = [0; 16];
for (at, word) in [row_words, first_row, layer_rows, tiles_per_row]
.into_iter()
.enumerate()
{
bytes[4 * at..4 * at + 4].copy_from_slice(&word.to_le_bytes());
}
bytes
}
/// The bytes of one texel of `format` held as `words`: an extended-range, padded or bfloat
/// format's raw texel (`ExtendedRange::raw_format`) or a two-plane format's color word
/// alone. `None` where `format` has no such words: another format, or
/// [`TexelWords::ColorPlane`] of a format but a two-plane one.
pub fn texel_bytes(format: PixelFormat, words: TexelWords) -> Option<u32> {
let rule = rule(format, words)?;
let form = ExtendedRange::of(format)?;
Some(match (rule, form) {
(Rule::Padded(_), ExtendedRange::R10X6 | ExtendedRange::R10X6Srgb) => 2,
(Rule::Bfloat, ExtendedRange::R16Bfloat) => 2,
(Rule::Bfloat, ExtendedRange::Rgba16Bfloat) => 8,
(Rule::Fields | Rule::PlaneTexel, _) => 8,
_ => 4,
})
}
}
/// How a consumer holds a texture's texels in the words it binds.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TexelWords {
/// The raw texels of `ExtendedRange::raw_format`: a two-plane format's color word and then its
/// alpha byte in a word of its own.
Raw,
/// A two-plane format's color words alone, as Metal lays its plane 0 in memory (a texture over
/// a surface's planes or a heap's bytes).
ColorPlane,
}
/// What the kernel does to each word.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Rule {
/// Bits 30 and 31 set: `BGR10_XR`'s word.
OnesOnTop,
/// Bits 30 and 31 cleared: a two-plane format's color word.
ZerosOnTop,
/// A two-plane format's raw texel: the even word's bits 30 and 31 cleared, the odd word (the
/// alpha byte) kept.
PlaneTexel,
/// `BGRA10_XR`'s fields: each field's low six bits cleared, and the odd word's high field
/// (alpha) code clamped to `[384, 894]`.
Fields,
/// A padded form's two 16-bit words: each one's low six bits cleared, or each one's code
/// replaced by the table's word for it (an `_sRGB` twin's, [`rewritten_words`]).
Padded(Option<Vec<u32>>),
/// `RGB10A2Unorm_sRGB`'s word: each color field's code replaced by the table's code for it
/// (`ExtendedRange::load_code`), alpha's kept.
SrgbFields(Vec<u32>),
/// A bfloat form's two 16-bit codes: each one's value through `half` and back
/// (`ExtendedRange::load_code`, [`bfloat_load`]).
Bfloat,
}
/// The rule of `format`'s texels held as `words`, or `None` where it has none.
fn rule(format: PixelFormat, words: TexelWords) -> Option<Rule> {
extended_rule(ExtendedRange::of(format)?, words)
}
/// The rule of an extended-range, padded or bfloat `form`'s texels held as `words`, or `None`
/// where it has none.
fn extended_rule(form: ExtendedRange, words: TexelWords) -> Option<Rule> {
Some(match (form, words) {
(ExtendedRange::Bgr10 { .. }, TexelWords::Raw) => Rule::OnesOnTop,
(ExtendedRange::Bgra10 { .. }, TexelWords::Raw) => Rule::Fields,
(ExtendedRange::Planes { .. }, TexelWords::Raw) => Rule::PlaneTexel,
(ExtendedRange::Planes { .. }, TexelWords::ColorPlane) => Rule::ZerosOnTop,
(_, TexelWords::ColorPlane) => return None,
(ExtendedRange::Rgb10A2Srgb, TexelWords::Raw) => Rule::SrgbFields(
(0..1024u32)
.map(|c| form.load_code(c))
.collect::<Option<_>>()?,
),
_ if form.padded() => Rule::Padded(rewritten_words(form)),
_ if form.bfloat() => Rule::Bfloat,
_ => return None,
})
}
/// The mask a padded linear form's word is ANDed with: the top ten bits of each of its two 16-bit
/// words. `BGRA10_XR`'s fields take it too.
const FIELDS_MASK: u32 = 0xffc0_ffc0;
/// The color word's code bits: bits 30 and 31 apart.
const CODES: u32 = 0x3fff_ffff;
/// `BGRA10_XR`'s alpha codes Metal's store keeps.
const ALPHA_CODES: [u32; 2] = [384, 894];
/// The words of the codes a loading pass leaves for each code `c` of `form`, `load_code(c) << 6`
/// (`ExtendedRange::load_code`), or `None` where every code stays (the linear forms: a mask
/// does) or `form` is not padded.
fn rewritten_words(form: ExtendedRange) -> Option<Vec<u32>> {
let words: Vec<u32> = (0..1024u32)
.map(|c| form.load_code(c).map(|m| m << 6))
.collect::<Option<_>>()?;
let moved = words.iter().zip(0u32..).any(|(&w, c)| w != c << 6);
moved.then_some(words)
}
/// A `Private` `u32[1024]` holding `words`.
fn words_table(b: &mut ModuleBuilder, u32_: TypeId, words: &[u32]) -> BResult<GlobalId> {
let len = b.constant(Constant::Scalar {
ty: u32_,
bits: ConstBits(words.len() as u64),
})?;
let arr = b.ty(Type::Array {
elem: u32_,
len,
stride: None,
})?;
let mut parts = Vec::with_capacity(words.len());
for &w in words {
parts.push(b.constant(Constant::Scalar {
ty: u32_,
bits: ConstBits(u64::from(w)),
})?);
}
let init = b.constant(Constant::Composite {
ty: arr,
parts: parts.into(),
})?;
b.plain_global(StorageClass::Private, arr, Some(init))
}
/// The binding symbols of the words, the mask and the shape in the typed module.
const WORDS: ResourceSlot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Buffer,
index: 0,
};
const TILES: ResourceSlot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Buffer,
index: 1,
};
const SHAPE: ResourceSlot = ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::Buffer,
index: 2,
};
/// A `Block { u32 words[]; }` storage buffer bound at `sym`.
fn words_buffer(b: &mut ModuleBuilder, sym: ResourceSlot, u32_: TypeId) -> BResult<GlobalId> {
let rta = b.ty(Type::RuntimeArray {
elem: u32_,
stride: Some(4),
})?;
let layout = natural_layout(b.types(), LayoutRule::Std430, true, &[rta])?;
let block = b.ty(Type::Struct {
members: [rta].into(),
layout: Some(layout),
})?;
b.resource(sym, StorageClass::StorageBuffer, block)
}
fn u32_value(f: &mut FunctionBuilder<'_>, v: u32) -> BResult<Value> {
let c = f.u32_const(v)?;
f.module().const_value(c)
}
/// `rule`'s rewrite of `word`, the `odd` (a `bool`) word of its texel; `table` is a padded
/// `_sRGB` twin's table of rewritten words ([`words_table`]).
fn rewritten(
f: &mut FunctionBuilder<'_>,
rule: &Rule,
table: Option<GlobalId>,
word: Value,
odd: Value,
) -> BResult<Value> {
Ok(match rule {
Rule::OnesOnTop => {
let top = u32_value(f, !CODES)?;
f.binary(BinOp::BitwiseOr, word, top)?
}
Rule::ZerosOnTop => {
let codes = u32_value(f, CODES)?;
f.binary(BinOp::BitwiseAnd, word, codes)?
}
Rule::PlaneTexel => {
let codes = u32_value(f, CODES)?;
let color = f.binary(BinOp::BitwiseAnd, word, codes)?;
f.select(odd, word, color)?
}
Rule::Fields => extended_range_fields(f, word, odd)?,
Rule::Padded(_) => {
let Some(table) = table else {
let mask = u32_value(f, FIELDS_MASK)?;
return f.binary(BinOp::BitwiseAnd, word, mask);
};
// Each 16-bit word's code indexes the table of its rewritten word.
let (k6, k16) = (u32_value(f, 6)?, u32_value(f, 16)?);
let low = u32_value(f, 0xffff)?;
let table = f.module().global_value(table)?;
let lo = f.binary(BinOp::BitwiseAnd, word, low)?;
let lo = f.binary(BinOp::ShiftRightLogical, lo, k6)?;
let hi = f.binary(BinOp::ShiftRightLogical, word, k16)?;
let hi = f.binary(BinOp::ShiftRightLogical, hi, k6)?;
let lo = f.access_chain(table, &[lo])?;
let lo = f.load(lo, MemAccess::default())?;
let hi = f.access_chain(table, &[hi])?;
let hi = f.load(hi, MemAccess::default())?;
let hi = f.binary(BinOp::ShiftLeftLogical, hi, k16)?;
f.binary(BinOp::BitwiseOr, lo, hi)?
}
Rule::SrgbFields(_) => {
let table = table.ok_or(crate::spirv::error::BuildError::Operand {
op: crate::spv::Op::AccessChain,
rule: crate::spirv::error::OperandRule::NotPointer,
})?;
let table = f.module().global_value(table)?;
let field = u32_value(f, 0x3ff)?;
let alpha = u32_value(f, !CODES)?;
let mut out = f.binary(BinOp::BitwiseAnd, word, alpha)?;
for shift in [0u32, 10, 20] {
let k = u32_value(f, shift)?;
let c = f.binary(BinOp::ShiftRightLogical, word, k)?;
let c = f.binary(BinOp::BitwiseAnd, c, field)?;
let c = f.access_chain(table, &[c])?;
let c = f.load(c, MemAccess::default())?;
let c = f.binary(BinOp::ShiftLeftLogical, c, k)?;
out = f.binary(BinOp::BitwiseOr, out, c)?;
}
out
}
Rule::Bfloat => {
let (k16, low) = (u32_value(f, 16)?, u32_value(f, 0xffff)?);
let lo = f.binary(BinOp::BitwiseAnd, word, low)?;
let lo = bfloat_load(f, lo)?;
let hi = f.binary(BinOp::ShiftRightLogical, word, k16)?;
let hi = bfloat_load(f, hi)?;
let hi = f.binary(BinOp::ShiftLeftLogical, hi, k16)?;
f.binary(BinOp::BitwiseOr, lo, hi)?
}
})
}
/// `x >> k` rounded to nearest, ties to even (`k` at most 31, `x` below `2^30`).
fn shift_nearest_even(f: &mut FunctionBuilder<'_>, x: Value, k: Value) -> BResult<Value> {
let (zero, one) = (u32_value(f, 0)?, u32_value(f, 1)?);
let q = f.binary(BinOp::ShiftRightLogical, x, k)?;
let back = f.binary(BinOp::ShiftLeftLogical, q, k)?;
let rest = f.binary(BinOp::ISub, x, back)?;
// Twice the rest against `2^k`: past it rounds up, at it (a tie) up to an even quotient.
let twice = f.binary(BinOp::ShiftLeftLogical, rest, one)?;
let unit = f.binary(BinOp::ShiftLeftLogical, one, k)?;
let past = f.binary(BinOp::UGreaterThan, twice, unit)?;
let tie = f.binary(BinOp::IEqual, twice, unit)?;
let odd = f.binary(BinOp::BitwiseAnd, q, one)?;
let odd = f.binary(BinOp::INotEqual, odd, zero)?;
let tie_up = f.binary(BinOp::LogicalAnd, tie, odd)?;
let up = f.binary(BinOp::LogicalOr, past, tie_up)?;
let up = f.select(up, one, zero)?;
f.binary(BinOp::IAdd, q, up)
}
/// The bfloat code a loading pass leaves for the code `code` (a `u32` below `0x10000`;
/// `ExtendedRange::load_code`): a NaN `0x7fc0`; at least `65536` in magnitude the infinity of
/// its sign; a value `half` holds (at least `2^-14`) itself; a smaller one rounded to a multiple
/// of `2^-24` (nearest, ties to even), then to the bfloat code nearest that (ties to even), its
/// sign kept. Integer operations on the bits alone, so no float mode changes the answer.
fn bfloat_load(f: &mut FunctionBuilder<'_>, code: Value) -> BResult<Value> {
let c = |f: &mut FunctionBuilder<'_>, v: u32| u32_value(f, v);
let sign_bit = c(f, 0x8000)?;
let sign = f.binary(BinOp::BitwiseAnd, code, sign_bit)?;
let magnitude_bits = c(f, 0x7fff)?;
let mag = f.binary(BinOp::BitwiseAnd, code, magnitude_bits)?;
// The code's exponent field and its significand (the hidden bit set past the subnormals).
let k7 = c(f, 7)?;
let exponent = f.binary(BinOp::ShiftRightLogical, mag, k7)?;
let fraction_bits = c(f, 0x7f)?;
let fraction = f.binary(BinOp::BitwiseAnd, mag, fraction_bits)?;
let (zero, one) = (c(f, 0)?, c(f, 1)?);
let subnormal = f.binary(BinOp::IEqual, exponent, zero)?;
let hidden = c(f, 0x80)?;
let normal = f.binary(BinOp::BitwiseOr, fraction, hidden)?;
let significand = f.select(subnormal, fraction, normal)?;
let exponent = f.select(subnormal, one, exponent)?;
// The value in units of `2^-24`, `significand * 2^(exponent - 110)`: four times the
// significand shifted right by `112 - exponent`, rounded to nearest even.
let top = c(f, 112)?;
let capped = f.glsl(GlslOp::UMin, &[exponent, top])?;
let k = f.binary(BinOp::ISub, top, capped)?;
let k31 = c(f, 31)?;
let k = f.glsl(GlslOp::UMin, &[k, k31])?;
let k2 = c(f, 2)?;
let quad = f.binary(BinOp::ShiftLeftLogical, significand, k2)?;
let units = shift_nearest_even(f, quad, k)?;
// Those units (at most `2^10`) rounded to eight significant bits, the bfloat's.
let by_two = shift_nearest_even(f, units, one)?;
let by_two = f.binary(BinOp::ShiftLeftLogical, by_two, one)?;
let by_four = shift_nearest_even(f, units, k2)?;
let by_four = f.binary(BinOp::ShiftLeftLogical, by_four, k2)?;
let (k256, k512) = (c(f, 256)?, c(f, 512)?);
let nine = f.binary(BinOp::UGreaterThanEqual, units, k256)?;
let ten = f.binary(BinOp::UGreaterThanEqual, units, k512)?;
let units = f.select(nine, by_two, units)?;
let units = f.select(ten, by_four, units)?;
// The `float` of `units * 2^-24`, its top 16 bits: the exponent field `msb + 103` and the
// bits below the most significant one.
let msb = f.glsl(GlslOp::FindUMsb, &[units])?;
let bias = c(f, 103)?;
let field = f.binary(BinOp::IAdd, msb, bias)?;
let k23 = c(f, 23)?;
let field = f.binary(BinOp::ShiftLeftLogical, field, k23)?;
let up = f.binary(BinOp::ISub, k23, msb)?;
let mantissa = f.binary(BinOp::ShiftLeftLogical, units, up)?;
let mantissa_bits = c(f, 0x7f_ffff)?;
let mantissa = f.binary(BinOp::BitwiseAnd, mantissa, mantissa_bits)?;
let bits = f.binary(BinOp::BitwiseOr, field, mantissa)?;
let k16 = c(f, 16)?;
let small = f.binary(BinOp::ShiftRightLogical, bits, k16)?;
let none = f.binary(BinOp::IEqual, units, zero)?;
let small = f.select(none, zero, small)?;
let small = f.binary(BinOp::BitwiseOr, small, sign)?;
// The value `half` holds, the infinity past it, and a NaN.
let least_normal = c(f, 0x3880)?;
let held = f.binary(BinOp::UGreaterThanEqual, mag, least_normal)?;
let out = f.select(held, code, small)?;
let overflow = c(f, 0x4780)?;
let past = f.binary(BinOp::UGreaterThanEqual, mag, overflow)?;
let infinity = c(f, 0x7f80)?;
let signed_infinity = f.binary(BinOp::BitwiseOr, infinity, sign)?;
let out = f.select(past, signed_infinity, out)?;
let nan = f.binary(BinOp::UGreaterThan, mag, infinity)?;
let quiet = c(f, 0x7fc0)?;
f.select(nan, quiet, out)
}
/// `BGRA10_XR`'s `word`, the `odd` (a `bool`) word of its texel, with each field's low six bits
/// cleared and (the odd word's high field) alpha's code clamped to `[384, 894]`: Metal's tile
/// store.
fn extended_range_fields(f: &mut FunctionBuilder<'_>, word: Value, odd: Value) -> BResult<Value> {
let mask = u32_value(f, FIELDS_MASK)?;
let even = f.binary(BinOp::BitwiseAnd, word, mask)?;
// The odd word: red's field, then alpha's code clamped.
let low_mask = u32_value(f, FIELDS_MASK & 0xffff)?;
let low = f.binary(BinOp::BitwiseAnd, word, low_mask)?;
let k22 = u32_value(f, 22)?;
let code = f.binary(BinOp::ShiftRightLogical, word, k22)?;
let [least, most] = ALPHA_CODES;
let (least, most) = (u32_value(f, least)?, u32_value(f, most)?);
let below = f.binary(BinOp::ULessThan, code, least)?;
let code = f.select(below, least, code)?;
let above = f.binary(BinOp::UGreaterThan, code, most)?;
let code = f.select(above, most, code)?;
let high = f.binary(BinOp::ShiftLeftLogical, code, k22)?;
let odd_word = f.binary(BinOp::BitwiseOr, low, high)?;
f.select(odd, odd_word, even)
}
/// The module as a typed module, before serialization: the module [`unused_bits_module`]
/// serializes, which the CPU interpreter runs, of `rule` over texels of `texel_bytes` bytes. Its
/// bindings are the symbols `WORDS`, `TILES` and `SHAPE`.
fn typed_module(rule: &Rule, texel_bytes: u32) -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let u32_ = b.ty(Type::Int {
width: 32,
signed: false,
})?;
let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?;
let words = words_buffer(&mut b, WORDS, u32_)?;
let tiles = words_buffer(&mut b, TILES, u32_)?;
let shape = words_buffer(&mut b, SHAPE, u32_)?;
let table = match rule {
Rule::Padded(Some(t)) | Rule::SrgbFields(t) => Some(words_table(&mut b, u32_, t)?),
_ => None,
};
let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
let mut f = b.function(void)?;
let zero = u32_value(&mut f, 0)?;
let invocation = f.module().global_value(invocation)?;
let invocation = f.load(invocation, MemAccess::default())?;
let i = f.composite_extract(invocation, &[0])?;
let words = f.module().global_value(words)?;
let tiles = f.module().global_value(tiles)?;
let shape = f.module().global_value(shape)?;
let count = f.array_length(words, 0)?;
let inside = f.binary(BinOp::ULessThan, i, count)?;
let rule = rule.clone();
let rewrite: ArmFn<'_, ()> = Box::new(move |f, _| {
let shape_word = |f: &mut FunctionBuilder<'_>, at: u32| -> BResult<Value> {
let at = u32_value(f, at)?;
let p = f.access_chain(shape, &[zero, at])?;
f.load(p, MemAccess::default())
};
let row_words = shape_word(f, 0)?;
let first_row = shape_word(f, 1)?;
let layer_rows = shape_word(f, 2)?;
let tiles_per_row = shape_word(f, 3)?;
let (k1, k5, k31) = (u32_value(f, 1)?, u32_value(f, 5)?, u32_value(f, 31)?);
// The word's row of the region (across its layers), and its word in that row.
let row = f.binary(BinOp::UDiv, i, row_words)?;
let row = f.binary(BinOp::IAdd, first_row, row)?;
let w = f.binary(BinOp::UMod, i, row_words)?;
let layer = f.binary(BinOp::UDiv, row, layer_rows)?;
let y = f.binary(BinOp::UMod, row, layer_rows)?;
// The word's first texel: its byte in the row over the texel's bytes.
let four = u32_value(f, 4)?;
let texel = u32_value(f, texel_bytes)?;
let byte = f.binary(BinOp::IMul, w, four)?;
let x = f.binary(BinOp::UDiv, byte, texel)?;
let tile_rows = f.binary(BinOp::IAdd, layer_rows, k31)?;
let tile_rows = f.binary(BinOp::ShiftRightLogical, tile_rows, k5)?;
let tile_y = f.binary(BinOp::ShiftRightLogical, y, k5)?;
let tile_x = f.binary(BinOp::ShiftRightLogical, x, k5)?;
let tile = f.binary(BinOp::IMul, layer, tile_rows)?;
let tile = f.binary(BinOp::IAdd, tile, tile_y)?;
let tile = f.binary(BinOp::IMul, tile, tiles_per_row)?;
let tile = f.binary(BinOp::IAdd, tile, tile_x)?;
let at = f.binary(BinOp::ShiftRightLogical, tile, k5)?;
let bit = f.binary(BinOp::BitwiseAnd, tile, k31)?;
let mask_words = f.array_length(tiles, 0)?;
let named = f.binary(BinOp::ULessThan, at, mask_words)?;
// A tile past the mask's words reads as unset (its word read from 0, which exists).
let read_at = f.select(named, at, zero)?;
let p = f.access_chain(tiles, &[zero, read_at])?;
let mask = f.load(p, MemAccess::default())?;
let mask = f.binary(BinOp::ShiftRightLogical, mask, bit)?;
let mask = f.binary(BinOp::BitwiseAnd, mask, k1)?;
let set = f.binary(BinOp::INotEqual, mask, zero)?;
let set = f.binary(BinOp::LogicalAnd, set, named)?;
let odd = f.binary(BinOp::BitwiseAnd, w, k1)?;
let odd = f.binary(BinOp::INotEqual, odd, zero)?;
let p = f.access_chain(words, &[zero, i])?;
let word = f.load(p, MemAccess::default())?;
let made = rewritten(f, &rule, table, word, odd)?;
let kept = f.select(set, made, word)?;
f.store(p, kept, MemAccess::default())?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), inside, rewrite, None)?;
f.ret(None)?;
let id = f.finish()?;
b.entry(
ExecModel::GLCompute,
id,
vec![ExecMode::LocalSize {
x: UnusedBitsModule::LOCAL_SIZE,
y: 1,
z: 1,
}],
)?;
b.finalize()
}
/// The fixed binding numbers of the module's symbols.
fn binding_of(sym: &Symbol) -> Option<u32> {
match sym {
Symbol::DescriptorSet(_) => Some(UnusedBitsModule::SET),
Symbol::Binding(s) if *s == WORDS => Some(UnusedBitsModule::WORDS_BINDING),
Symbol::Binding(s) if *s == TILES => Some(UnusedBitsModule::TILES_BINDING),
Symbol::Binding(s) if *s == SHAPE => Some(UnusedBitsModule::SHAPE_BINDING),
_ => None,
}
}
/// The unused bits module of `device` for textures of `format` held as `words`: built with the
/// typed builder, checked by the owned verifier against the device's profile (requirements
/// included), serialized, and numbered with the fixed bindings of [`UnusedBitsModule`]. A format
/// that has no such words ([`UnusedBitsModule::texel_bytes`] is `None`) is
/// `NotImplemented(Format)`.
pub fn unused_bits_module(
device: &Device,
format: PixelFormat,
words: TexelWords,
) -> Result<UnusedBitsModule, Error> {
let (Some(rule), Some(texel_bytes)) = (
rule(format, words),
UnusedBitsModule::texel_bytes(format, words),
) else {
return Err(Unsupported::not_implemented(Feature::Format).into());
};
let profile = device.profile();
let m = typed_module(&rule, texel_bytes)?;
let mut meter = Meter::new(&Budget::default());
crate::spirv::verify::verify(&m, profile, &mut meter)?;
let r = crate::spirv::serialize::serialize(m)?;
profile.check(&r.requirements).map_err(|c| {
Error::Internal(InternalError::new(
InternalKind::RequirementsExceedProfile,
format!("the unused bits kernel needs {c:?}"),
))
})?;
let words = crate::spirv::serialize::relocate(&r, &binding_of)?;
Ok(UnusedBitsModule {
spirv: words.into(),
requirements: r.requirements,
})
}
#[cfg(test)]
mod tests;
@@ -1,316 +0,0 @@
use super::{rule, typed_module, TexelWords, UnusedBitsModule, SHAPE, TILES, WORDS};
use crate::metal::format::ExtendedRange;
use crate::metal::PixelFormat;
use crate::spirv::interp::{run, Buffer, Config, Order, Resources};
use crate::spirv::testing::{assert_valid, committed_profiles};
/// Every format and the words it is held in.
fn formats() -> Vec<(PixelFormat, TexelWords)> {
let mut all = Vec::new();
for (plain, srgb) in [
(PixelFormat::BGR10XR, PixelFormat::BGR10XRSRGB),
(PixelFormat::BGRA10XR, PixelFormat::BGRA10XRSRGB),
(PixelFormat::RGB10A82PXR10, PixelFormat::RGB10A82PXR10SRGB),
] {
all.push((plain, TexelWords::Raw));
all.push((srgb, TexelWords::Raw));
}
for format in [PixelFormat::RGB10A82PXR10, PixelFormat::RGB10A82PXR10SRGB] {
all.push((format, TexelWords::ColorPlane));
}
for format in [
PixelFormat::R10UnormX6,
PixelFormat::RG10UnormX12,
PixelFormat::R10UnormX6SRGB,
PixelFormat::RG10UnormX12SRGB,
PixelFormat::R16Bfloat,
PixelFormat::RG16Bfloat,
PixelFormat::RGBA16Bfloat,
] {
all.push((format, TexelWords::Raw));
}
all
}
/// The module of `format` held as `words`.
fn module(format: PixelFormat, words: TexelWords) -> crate::spirv::ir::TypedModule {
let rule = rule(format, words).expect("a rule");
let bytes = UnusedBitsModule::texel_bytes(format, words).expect("texel bytes");
typed_module(&rule, bytes).expect("module")
}
#[test]
fn the_unused_bits_kernel_is_valid_on_every_committed_profile() {
for (_, p) in committed_profiles().expect("profiles") {
for (format, words) in formats() {
assert_valid(module(format, words), &p);
}
}
}
/// Only a two-plane format has color-plane words, and a format Metal's tile store keeps has no
/// rule.
#[test]
fn only_a_two_plane_format_has_color_plane_words() {
for (format, words) in formats() {
assert!(rule(format, words).is_some(), "{format:?} {words:?}");
let plane = rule(format, TexelWords::ColorPlane).is_some();
let two_planes = matches!(
ExtendedRange::of(format),
Some(ExtendedRange::Planes { .. })
);
assert_eq!(plane, two_planes, "{format:?}");
}
for format in [
PixelFormat::RGBA8Unorm,
PixelFormat::RGBA16Float,
PixelFormat::RG11B10Float,
PixelFormat::RGBA8Snorm,
PixelFormat::RGB9E5Float,
] {
assert!(rule(format, TexelWords::Raw).is_none(), "{format:?}");
assert!(UnusedBitsModule::texel_bytes(format, TexelWords::Raw).is_none());
}
}
/// Metal's store of `word`, the `odd` word of its texel, of `format` held as `words` (the module
/// docs), computed here apart from the kernel.
fn stored(format: PixelFormat, words: TexelWords, word: u32, odd: bool) -> u32 {
let codes = 0x3fff_ffff;
let form = ExtendedRange::of(format).expect("an extended-range, padded or bfloat form");
match (form, words) {
(ExtendedRange::Bgr10 { .. }, _) => word | !codes,
(ExtendedRange::Planes { .. }, TexelWords::Raw) if odd => word,
(ExtendedRange::Planes { .. }, _) => word & codes,
(ExtendedRange::Bgra10 { .. }, _) if !odd => word & 0xffc0_ffc0,
(ExtendedRange::Bgra10 { .. }, _) => (word & 0xffc0) | (word >> 22).clamp(384, 894) << 22,
_ if form.bfloat() => {
let code = |h: u32| form.load_code(h).expect("a bfloat code");
code(word & 0xffff) | code(word >> 16) << 16
}
_ => {
let half = |h: u32| form.load_code(h >> 6).expect("a padded code") << 6;
half(word & 0xffff) | half(word >> 16) << 16
}
}
}
/// A splitmix64 stream: every bit of each word random.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u32 {
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
(z ^ (z >> 31)) as u32
}
}
/// Run the kernel of `format` held as `words` over `bytes` with the mask `tiles` and the shape
/// `shape`, in `groups` workgroups, both invocation orders.
fn rewritten(
(format, words): (PixelFormat, TexelWords),
bytes: &[u8],
tiles: &[u32],
shape: [u8; 16],
groups: u32,
) -> Vec<u8> {
let m = module(format, words);
let mut out = Vec::new();
for order in [Order::Forward, Order::Reverse] {
let res = Resources {
buffers: vec![
Buffer {
slot: Some(WORDS),
address: None,
bytes: bytes.to_vec(),
},
Buffer {
slot: Some(TILES),
address: None,
bytes: tiles.iter().flat_map(|w| w.to_le_bytes()).collect(),
},
Buffer {
slot: Some(SHAPE),
address: None,
bytes: shape.to_vec(),
},
],
push: Vec::new(),
spec: Default::default(),
};
let cfg = Config {
order,
workgroups: [groups, 1, 1],
..Config::default()
};
out.push(run(&m, &cfg, res).expect("run").buffers.swap_remove(0));
}
assert_eq!(out[0], out[1], "order independent");
out.swap_remove(0)
}
/// A region of 70 texels a row (rows padded to a word), 40 rows a layer, 2 layers, bound from
/// row 3 on, under a mask of every third tile: each word of a set tile's texel takes Metal's
/// store, every other word stays, for every format, and invocations past the words write nothing.
#[test]
fn each_word_of_a_masked_tile_takes_metals_store_and_no_other_changes() {
let (columns, layer_rows, layers, first_row) = (70u32, 40u32, 2u32, 3u32);
let tiles_per_row = columns.div_ceil(UnusedBitsModule::TILE);
let tile_rows = layer_rows.div_ceil(UnusedBitsModule::TILE);
let tiles = layers * tile_rows * tiles_per_row;
let mask: Vec<u32> = (0..tiles.div_ceil(32))
.map(|at| {
(0..32)
.filter(|bit| (32 * at + bit) % 3 == 0)
.fold(0, |m, bit| m | 1 << bit)
})
.collect();
let set = |tile: u32| tile < tiles && mask[(tile / 32) as usize] >> (tile % 32) & 1 == 1;
for (format, words) in formats() {
let texel = UnusedBitsModule::texel_bytes(format, words).unwrap();
let row_words = (columns * texel).div_ceil(4);
let rows = layers * layer_rows - first_row;
let mut rng = Rng(u64::from(texel) << 32 | u64::from(row_words));
let before: Vec<u32> = (0..rows * row_words).map(|_| rng.next()).collect();
let bytes: Vec<u8> = before.iter().flat_map(|w| w.to_le_bytes()).collect();
let groups = (before.len() as u32).div_ceil(UnusedBitsModule::LOCAL_SIZE) + 1;
let shape = UnusedBitsModule::shape(row_words, first_row, layer_rows, tiles_per_row);
let after = rewritten((format, words), &bytes, &mask, shape, groups);
let (mut changed, mut kept) = (0, 0);
for (i, (&word, got)) in before.iter().zip(after.chunks(4)).enumerate() {
let i = i as u32;
let row = first_row + i / row_words;
let w = i % row_words;
let (layer, y) = (row / layer_rows, row % layer_rows);
let x = 4 * w / texel;
let tile = (layer * tile_rows + y / 32) * tiles_per_row + x / 32;
let want = match set(tile) {
true => stored(format, words, word, w % 2 == 1),
false => word,
};
let got = u32::from_le_bytes([got[0], got[1], got[2], got[3]]);
assert_eq!(
got, want,
"{format:?} {words:?} word {i} (row {row}, word {w}, tile {tile}): {word:08x}"
);
match got == word {
true => kept += 1,
false => changed += 1,
}
}
assert!(changed > 0 && kept > 0, "{format:?} {words:?}");
}
}
/// Every 16-bit word of a padded linear form keeps its top ten bits and loses its low six, and an
/// `_sRGB` twin's takes its code's load code (`ExtendedRange::load_code`: 23 codes of
/// `R10Unorm_X6_sRGB` move, 1021 of `RG10Unorm_X12_sRGB`), every value of a word among them,
/// under a mask of every tile, across several workgroups.
#[test]
fn every_padded_word_takes_its_code_s_load_code_with_its_low_six_bits_zeroed() {
let halves: Vec<u16> = (0..=u16::MAX).collect();
let bytes: Vec<u8> = halves.iter().flat_map(|h| h.to_le_bytes()).collect();
let words = (bytes.len() / 4) as u32;
let groups = words.div_ceil(UnusedBitsModule::LOCAL_SIZE) + 1;
for format in [
PixelFormat::R10UnormX6,
PixelFormat::RG10UnormX12,
PixelFormat::R10UnormX6SRGB,
PixelFormat::RG10UnormX12SRGB,
] {
let form = ExtendedRange::of(format).expect("a padded form");
let moved = (0..1024).filter(|&c| form.load_code(c) != Some(c)).count();
let want_moved = match form {
ExtendedRange::R10X6Srgb => 23,
ExtendedRange::Rg10X12Srgb => 1021,
_ => 0,
};
assert_eq!(moved, want_moved, "{form:?}");
let want: Vec<u8> = halves
.iter()
.flat_map(|&h| {
let c = form.load_code(u32::from(h >> 6)).expect("a padded code");
(u16::try_from(c << 6).expect("a word")).to_le_bytes()
})
.collect();
// One row of every word: its texels' tiles all set.
let texel = UnusedBitsModule::texel_bytes(format, TexelWords::Raw).unwrap();
let tiles_per_row = (4 * words / texel).div_ceil(32);
let mask = vec![u32::MAX; tiles_per_row.div_ceil(32) as usize];
let shape = UnusedBitsModule::shape(words, 0, 1, tiles_per_row);
assert_eq!(
rewritten((format, TexelWords::Raw), &bytes, &mask, shape, groups),
want,
"{form:?}"
);
}
}
/// Every code of each bfloat form takes its load code (`ExtendedRange::load_code`, measured for
/// every code), under a mask of every tile, across several workgroups: 56,829
/// codes move (the NaNs to `0x7fc0`, the magnitudes from 65,536 to infinity, those below
/// `2^-14` to `half`'s step), the 8,707 others stay.
#[test]
fn every_bfloat_code_takes_its_load_code() {
let codes: Vec<u16> = (0..=u16::MAX).collect();
let bytes: Vec<u8> = codes.iter().flat_map(|h| h.to_le_bytes()).collect();
let words = (bytes.len() / 4) as u32;
let groups = words.div_ceil(UnusedBitsModule::LOCAL_SIZE) + 1;
for format in [
PixelFormat::R16Bfloat,
PixelFormat::RG16Bfloat,
PixelFormat::RGBA16Bfloat,
] {
let form = ExtendedRange::of(format).expect("a bfloat form");
let load = |c: u16| form.load_code(u32::from(c)).expect("a bfloat code");
let moved = codes.iter().filter(|&&c| load(c) != u32::from(c)).count();
assert_eq!(moved, 56_829, "{form:?}");
// A few of Metal's answers: the NaNs, an overflow, the codes `half`
// holds, and the double rounding below `2^-14`.
for (code, metal) in [
(0x7f81, 0x7fc0),
(0xffff, 0x7fc0),
(0xff7a, 0xff80),
(0x4780, 0x7f80),
(0x477f, 0x477f),
(0x3880, 0x3880),
(0x8001, 0x8000),
(0x0001, 0x0000),
(0x3301, 0x3380),
] {
assert_eq!(load(code), metal, "{form:?} {code:#06x}");
}
let want: Vec<u8> = codes
.iter()
.flat_map(|&c| (u16::try_from(load(c)).expect("a code")).to_le_bytes())
.collect();
let texel = UnusedBitsModule::texel_bytes(format, TexelWords::Raw).unwrap();
let tiles_per_row = (4 * words / texel).div_ceil(32);
let mask = vec![u32::MAX; tiles_per_row.div_ceil(32) as usize];
let shape = UnusedBitsModule::shape(words, 0, 1, tiles_per_row);
assert_eq!(
rewritten((format, TexelWords::Raw), &bytes, &mask, shape, groups),
want,
"{form:?}"
);
}
}
/// A mask of no word leaves every word, and a tile past the mask's words reads as unset.
#[test]
fn a_tile_past_the_mask_is_not_rewritten() {
let form = (PixelFormat::BGR10XR, TexelWords::Raw);
// Two layers of one row of 64 texels, 40 tiles a row: the first row's tiles 0 and 1 are the
// mask's one word's bits 0 and 1 (tile 0 set), and the second's, 40 and 41, lie past it.
let bytes = vec![0u8; 4 * 128];
let shape = UnusedBitsModule::shape(64, 0, 1, 40);
let after = rewritten(form, &bytes, &[0b01], shape, 2);
for (i, word) in after.chunks(4).enumerate() {
let word = u32::from_le_bytes([word[0], word[1], word[2], word[3]]);
let want = if i < 32 { 0xc000_0000 } else { 0 };
assert_eq!(word, want, "word {i}");
}
}
+2 -5
View File
@@ -53,8 +53,8 @@ use crate::pipeline::layout::{
BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange,
};
use crate::pipeline::lower_inputs::{
BlendEquation, CaptureForm, ChannelWrite, ColorGroup, ExtendedRangeColor, FactorLane,
RotatedBlendForm, VertexFetch,
BlendEquation, ChannelWrite, ColorGroup, ExtendedRangeColor, FactorLane, RotatedBlendForm,
VertexFetch,
};
use crate::pipeline::stage_io::{
CoverageLoop, CoverageLoopRefusal, DepthCompares, DepthMode, Interpolation as IoInterpolation,
@@ -876,7 +876,6 @@ codec_enum! {
VertexDepthClamp,
BlendColor,
ShaderTestsState,
CaptureAddress,
CaptureLayout,
CaptureIndexAddress,
StorageKeptChannels,
@@ -1176,7 +1175,6 @@ codec_enum! {
WordAttachment { Packed16 { fields }, Srgb8 { fields }, Rgb9e5 }
FactorLane { Zero, One, Output(f0) }
RotatedBlendForm { Premultiplied, Unmeasured }
CaptureForm { Vertices, Indexed(f0) }
TextureWriteRoundingMode { TowardZero, NearestEven }
CompareFunction { Never, Less, Equal, LessEqual, Greater, NotEqual, GreaterEqual, Always }
CoverageLoopRefusal {
@@ -1247,7 +1245,6 @@ codec_enum! {
CubicSampler { slot },
CubicArgumentSampler { stage },
ShaderTests { formatless, multisampled, planes },
CapturedPositions { form },
HeapRawSamples { stage, sampler },
ShaderStencilTest { formatless },
ExtendedRangeInputBlend { color, blend, kept },
+4 -16
View File
@@ -36,7 +36,7 @@ use std::fmt;
pub use crate::air::container::Hash256;
use crate::device::Device;
use crate::pipeline::lower_inputs::{CaptureForm, StorageImageChoice};
use crate::pipeline::lower_inputs::StorageImageChoice;
use crate::pipeline::sym::{SlotRef, SnapshotForm};
use crate::vk;
@@ -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 = 1909;
pub const SEMANTICS_VERSION: u32 = 1910;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 476;
/// 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 = 1681;
pub const RUNTIME_VERSION: u32 = 1682;
/// 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
@@ -379,14 +379,6 @@ pub struct VariantKey {
serde(default, with = "crate::pipeline::serde_pairs")
)]
pub cubic_samplers: BTreeMap<SlotRef, u32>,
/// The capture form of the vertex function (`LoweringInputs::captured_positions`): besides
/// its outputs, each vertex it runs writes Metal's clip position and point size to a record
/// at `PushHole::CaptureAddress`, the positions a tile reach kernel bins, for the draws of
/// its [`CaptureForm`]. A consumer asks for it itself (no bind shape does), for a draw it runs
/// again before its pass, and the plan of a pipeline compiled under it states it; a draw of
/// the other form is `BindError::NeedsVariant` with that form.
#[cfg_attr(feature = "serde", serde(default))]
pub captured_positions: Option<CaptureForm>,
/// The de-indexed form of a pipeline whose vertex function writes the primitive ID's varying
/// (`LoweringInputs::primitive_id_indices`, `BindShape::primitive_id_indices`): the vertex
/// function of an indexed draw of this index type runs the draw's indices as `index count`
@@ -547,7 +539,6 @@ impl VariantKey {
&& !self.shader_stencil
&& !self.window_depth_varying
&& self.cubic_samplers.is_empty()
&& self.captured_positions.is_none()
&& self.primitive_id_indices.is_none()
&& !self.quad_primitive_ids
&& !self.private_list
@@ -564,7 +555,7 @@ impl VariantKey {
/// the fragment function the colors it writes zero to and those it drops, its depth's clamp
/// range and whether its draws' tests are read-only, for a tile function the imageblock bytes
/// its pass keeps, and for the vertex function the
/// dropped `Layer` output, the viewport compensation, the window depth and the capture form
/// dropped `Layer` output, the viewport compensation and the window depth
/// (a vertex function's projection is
/// derived from the vertex descriptor and
/// [`pulled_vertex_buffers`](VariantKey::pulled_vertex_buffers) when the pipeline compiles,
@@ -685,9 +676,6 @@ impl VariantKey {
}
out.window_depth_varying =
self.window_depth_varying && stage == crate::pipeline::sym::Stage::Vertex;
out.captured_positions = self
.captured_positions
.filter(|_| stage == crate::pipeline::sym::Stage::Vertex);
out.primitive_id_indices = self
.primitive_id_indices
.filter(|_| stage == crate::pipeline::sym::Stage::Vertex);
-70
View File
@@ -1294,76 +1294,6 @@ fn the_dropped_vertex_layer_variant_round_trips() {
}
}
/// A render pipeline whose vertex function is compiled in a capture form round trips with its
/// `CapturedPositions` fact and its capture push fields (the index address in the indexed form),
/// and the decoded pipeline's plan states the variant, so a cached capture variant settles as the
/// compiled one does.
#[test]
fn the_captured_positions_variant_round_trips() {
use crate::cache::VariantKey;
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::sym::PushField;
use crate::pipeline::CaptureForm;
let dev = device("moltenvk-m3");
let Some(bc) = fixture("rch_vertex_math") else {
return;
};
let f = Library::from_air(&bc)
.and_then(|lib| lib.function("rch_vertex_math"))
.expect("vertex");
let d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f)));
for form in [
CaptureForm::Vertices,
CaptureForm::Indexed(crate::metal::IndexType::UInt16),
] {
let mut key = VariantKey::new();
key.captured_positions = Some(form);
let pipeline = dev
.compile_render_variant(&d, &key, &Budget::standard())
.expect("pipeline");
let decoded = RenderPipeline::from_bytes(&pipeline.to_bytes(), &dev).expect("decoded");
assert_eq!(decoded, pipeline);
assert!(decoded
.dependencies
.iter()
.any(|d| d.fact == RuntimeFact::CapturedPositions { form }));
let placed = |field| {
decoded
.interface
.push
.iter()
.any(|p| p.fields.iter().any(|f| f.field == field))
};
assert!(placed(PushField::CaptureAddress), "{form:?}");
assert!(placed(PushField::CaptureLayout), "{form:?}");
assert_eq!(
placed(PushField::CaptureIndexAddress),
form != CaptureForm::Vertices,
"{form:?}"
);
check_plan(&decoded, &dev, &key);
}
}
/// `decoded`'s plan for `rch_vertex_math`'s buffers states `key`.
fn check_plan(decoded: &RenderPipeline, dev: &Device, key: &crate::cache::VariantKey) {
use crate::bind::{BindState, BoundBuffer, StageTable};
let buffer = |length| BoundBuffer::Buffer {
length,
offset: 0,
gpu_address: 0x1_0000,
device_address: Some(0x7_0000_0000),
attribute_stride: None,
};
let mut vertex = StageTable::default();
vertex.buffers.insert(0, buffer(1024));
vertex.buffers.insert(1, buffer(256));
let mut state = BindState::default();
state.stages.insert(Stage::Vertex, vertex);
let plan = decoded.plan(dev, &state.shape()).expect("plan");
assert_eq!(&plan.variant, key);
}
/// A render pipeline compiled under the amplification draws variant round trips with its fact and
/// its amplification push fields, and the decoded pipeline's plan for a state whose amplification
/// multiview cannot express states the variant, so a cached variant settles as the compiled one
+7 -20
View File
@@ -307,24 +307,16 @@ pub(crate) fn among<F: Copy + Ord>(
///
/// `MetalDepth16BiasedStores`, measured by
/// `runtime_lane::unorm_depth_bias::a_constant_bias_on_a_16_bit_unorm_depth_stores_metals_codes`
/// (every depth and constant of the probes' draws, each biased by the device: our probe at
/// d51c2aa8, 2026-10-07):
/// - RADV, Mesa 26.2.4 on the Radeon 780M, through `VK_EXT_depth_bias_control`'s float
/// representation with `depthBiasExact`: every code Metal's.
/// - MoltenVK 1.4.1 on Apple's GPUs, which takes Metal's constant in Metal's own unit (it has no
/// `VK_EXT_depth_bias_control`): every code Metal's on an M4 mini. On
/// every Apple GPU by construction: MoltenVK 1.4.1 hands the recorded constant, slope and clamp
/// unchanged to the render encoder's `setDepthBias:slopeScale:clamp:`
/// (every depth and constant of the probes' draws, each biased by the device):
/// - MoltenVK 1.4.1 on Apple's GPUs, which takes Metal's constant in Metal's own unit: every code
/// Metal's on an M4 mini. On every Apple GPU by construction: MoltenVK 1.4.1 hands the recorded
/// constant, slope and clamp unchanged to the render encoder's `setDepthBias:slopeScale:clamp:`
/// (`MVKCommandEncoderState.mm`) and makes the depth Metal's own `Depth16Unorm`
/// (`MVKPixelFormats.mm`), so Metal biases and stores the depth on whichever Apple GPU runs it.
///
/// Measured not to have it, so not listed, each storing the code next to Metal's for a sum near a
/// code's midpoint: ANV, Mesa 26.2.4 on the Iris Xe (RPL-P), which rounds the sum to nearest, not
/// toward zero; lavapipe, Mesa 26.0.8 on LLVM 21.1.8, x86_64 (the linux-gate container), which also
/// scales it by 65535 as a `float` (0 biased by 0.5 stored as 2 where Metal's is 1); NVIDIA's
/// 615.71.09 on the RTX 5080 Laptop GPU, through `depthBiasExact` in 2^-16, whose conversion of
/// every depth rounds down near a midpoint (`MetalDepth16Stores` above). ANV on the UHD 770 (RPL-S)
/// is unmeasured.
/// Not listed: every other driver. Each biases Metal's constant `c` by its own unit (Vulkan's `r`
/// of a 16-bit unorm depth, at most twice 2^-16), where Metal biases by `c + 1` units of 1/65535
/// (`c - 1` below 0), so a constant bias stores another code than Metal's.
///
/// `MetalInterpolation`: MoltenVK 1.4.1 hands each fragment input to Metal with its
/// interpolation (SPIRV-Cross `adec7acb` writes it as a `[[user(...)]]` input qualified
@@ -600,11 +592,6 @@ pub(crate) const DEVIATIONS: &[Measured<DriverDeviation>] = &[
(INTEL_VENDOR_ID, INTEL_UHD_770_RPL_S),
),
moltenvk_on_apple(DriverDeviation::MetalDepth16Stores),
mesa_on(
DriverDeviation::MetalDepth16BiasedStores,
DriverId::MESA_RADV,
(AMD_VENDOR_ID, AMD_RADEON_780M),
),
moltenvk_on_apple(DriverDeviation::MetalDepth16BiasedStores),
moltenvk_on_apple(DriverDeviation::MetalInterpolation),
moltenvk_on_apple(DriverDeviation::MetalFirstVertexIndices),
+3 -1
View File
@@ -348,7 +348,6 @@ fn facts(ext: VkExtension) -> ExtensionFacts {
| E::KhrMaintenance8
| E::KhrShaderFma
| E::ExtDepthRangeUnrestricted
| E::ExtDepthBiasControl
| E::ExtDepthClipEnable
| E::ExtDepthClampControl
| E::ExtSampleLocations
@@ -388,6 +387,9 @@ fn facts(ext: VkExtension) -> ExtensionFacts {
| E::KhrShaderSubgroupRotate => fact(true, Some(4), &[]),
// Enabled only as another extension's requirement.
E::ExtCustomBorderColor => fact(false, None, &[]),
// Described, never enabled: a depth bias counts the device's own unit
// (`metal::state::depth_bias`), so the core reads none of its features.
E::ExtDepthBiasControl => fact(false, None, &[]),
E::KhrDynamicRendering => fact(false, Some(3), &[]),
// Object and mesh functions. `VK_KHR_spirv_1_4` is core at the 1.2 floor.
E::ExtMeshShader => fact(true, None, &[]),
@@ -222,9 +222,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
// The planner admits a listed cubic sampler beside the stage's sampler table; the
// function marks the `ExecutionStatus` buffer where it reaches one.
RuntimeFact::CubicArgumentSampler { .. } => Mechanism::PlanTimeCheck,
// A pipeline compiled in the capture form, which a consumer asks for; its plans state
// it, and the binder writes each draw's capture layout.
RuntimeFact::CapturedPositions { .. } => Mechanism::Variant,
// The planner refuses a texture a heap holds by its raw texels alone that a plan names
// beside the stage; a consumer's own heap announces one.
RuntimeFact::HeapRawSamples { .. } => Mechanism::PlanTimeCheck,
@@ -770,9 +770,9 @@ pub enum VkProperty {
/// The device stores every depth a draw biases on a `Depth16Unorm` attachment as Metal's code
/// (the driver's measured deviation
/// [`DriverDeviation::MetalDepth16BiasedStores`](crate::error::DriverDeviation::MetalDepth16BiasedStores)).
/// No Vulkan query reports it: Vulkan leaves the biased sum's rounding to the device. No module
/// requires it: every biased depth is the device's own, and where the profile lacks it the
/// runtime announces `unorm-depth-bias`.
/// No Vulkan query reports it: Vulkan leaves the bias's unit and the biased sum's rounding to
/// the device. No module requires it: every biased depth is the device's own, and where the
/// profile lacks it the runtime announces `unorm-depth-bias`.
MetalDepth16BiasedStores,
/// The device interpolates a varying as Metal does, bit for bit (the driver's measured
/// deviation
@@ -281,7 +281,6 @@ fn the_profile_takes_the_deviations_its_driver_is_measured_with() {
D::MetalHalfTexelWrites,
D::MetalNormStorageWrites,
D::MetalDepth16Stores,
D::MetalDepth16BiasedStores,
],
(false, "intel-irisxe-rplp-anv") => vec![
D::MetalFloatDenormals,
@@ -67,16 +67,26 @@ fn recommendations_are_closed_fixed_points_on_every_committed_profile() {
}
// Every listed feature with a member is recommended (the committed profiles list only
// exposed features whose extensions' requirements are listed), except the buffer
// update-after-bind features VUID 10247 forbids beside `robustBufferAccess`.
// update-after-bind features VUID 10247 forbids beside `robustBufferAccess`, and
// `VK_EXT_depth_bias_control`'s, an extension the core reads nothing of.
let forbidden = |f: VkFeature| {
!desc.robust_buffer_access_update_after_bind
&& desc.has(VkFeature::RobustBufferAccess)
&& BUFFER_UPDATE_AFTER_BIND.contains(&f)
};
let unread = [
VkFeature::DepthBiasControl,
VkFeature::FloatRepresentation,
VkFeature::DepthBiasExact,
];
assert!(
!rec.extensions.contains(&VkExtension::ExtDepthBiasControl),
"{stem}"
);
for &f in &desc.features {
assert_eq!(
rec.features.contains(&f),
f.exposure().has_member(desc.api_version) && !forbidden(f),
f.exposure().has_member(desc.api_version) && !forbidden(f) && !unread.contains(&f),
"{stem}: {f:?}"
);
if forbidden(f) {
@@ -188,9 +188,6 @@ fn every_fact() -> Vec<RuntimeFact> {
planes: true,
},
RuntimeFact::StorageTextureIntegerChannels { slot },
RuntimeFact::CapturedPositions {
form: crate::pipeline::CaptureForm::Indexed(crate::metal::IndexType::UInt16),
},
RuntimeFact::HeapRawSamples {
stage: Stage::Fragment,
sampler: Some(1),
@@ -334,7 +331,6 @@ fn variant(f: &RuntimeFact) -> usize {
RuntimeFact::CubicSampler { .. } => 68,
RuntimeFact::CubicArgumentSampler { .. } => 69,
RuntimeFact::ShaderTests { .. } => 70,
RuntimeFact::CapturedPositions { .. } => 72,
RuntimeFact::HeapRawSamples { .. } => 73,
RuntimeFact::ShaderStencilTest { .. } => 74,
RuntimeFact::ExtendedRangeInputBlend { .. } => 75,
@@ -349,7 +345,7 @@ fn variant(f: &RuntimeFact) -> usize {
RuntimeFact::ObjectThreadgroupArena { .. } => 85,
RuntimeFact::WordInputMerge { .. } => 87,
RuntimeFact::ReplayBindings => 88,
RuntimeFact::MergedDraws => 89,
RuntimeFact::MergedDraws => 72,
RuntimeFact::QuadPrimitiveIds => 58,
RuntimeFact::RotatedWeights => 82,
RuntimeFact::PrivateList => 86,
@@ -362,7 +358,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..90).collect(), "every_fact misses a variant");
assert_eq!(covered, (0..89).collect(), "every_fact misses a variant");
for (stem, _) in super::committed_profiles() {
let dev = device(&stem);
let p = dev.profile();
@@ -445,8 +441,7 @@ fn mechanism_is_total_over_every_fact_and_profile() {
| RuntimeFact::MovableStorageWrites { .. }
| RuntimeFact::ConstexprSampled { .. }
| RuntimeFact::CubicSampler { .. }
| RuntimeFact::AnisotropicSampler { .. }
| RuntimeFact::CapturedPositions { .. } => Mechanism::Variant,
| RuntimeFact::AnisotropicSampler { .. } => Mechanism::Variant,
RuntimeFact::ImageViewShape { .. }
| RuntimeFact::StorageTextureLevelViews { .. }
| RuntimeFact::UlongAtomicView { .. } => Mechanism::BinderView,
+11 -21
View File
@@ -764,11 +764,11 @@ pub enum DriverDeviation {
/// `unorm-depth-rounding` at a draw that tests or writes such a depth.
MetalDepth16Stores,
/// The device stores every depth a draw biases on a `Depth16Unorm` attachment as Metal's code,
/// the bias recorded as [`depth_bias`](crate::metal::state::depth_bias) records it
/// (`VkProperty::MetalDepth16BiasedStores`): Metal biases by `c ± 1` units of 1/65535 as
/// `float` (one unit for a slope alone), adds the bias to the depth rounding toward zero, and
/// stores the sum rounded to nearest, a tie up. Vulkan leaves the sum's rounding, and without
/// `depthBiasExact` the unit, to the device. Every biased depth is the device's own, the
/// Metal's constant recorded in the device's unit as [`depth_bias`](crate::metal::state::depth_bias)
/// records it (`VkProperty::MetalDepth16BiasedStores`): Metal biases by `c ± 1` units of
/// 1/65535 as `float` (one unit for a slope alone), adds the bias to the depth rounding toward
/// zero, and stores the sum rounded to nearest, a tie up. Vulkan leaves the unit (at most twice
/// 2^-16) and the sum's rounding to the device. Every biased depth is the device's own, the
/// attachment's fixed-function bias applied; no module reads the deviation. Unmeasured, the
/// runtime announces `unorm-depth-bias` at a draw that biases such a depth by a constant, or
/// by a slope alone.
@@ -1443,16 +1443,6 @@ pub enum Feature {
/// the interlocked storage form, where Metal's measured model does not hold the part it names
/// ([`ExtendedRangeBlend`]). Every other such blend is Metal's arithmetic, bit for bit.
ExtendedRangeBlend(ExtendedRangeBlend),
/// The tiles a render pass's primitives reach, binned on the device
/// ([`tile_reach_module`](crate::bind::tile_reach_module)), on a device without what the
/// kernel's exact arithmetic needs: `shaderInt64` ([`Needs::AnyOf`]). Also the capture form
/// of a vertex function, whose records hold the positions the kernel bins
/// (`LoweringInputs::captured_positions`): on a device without device addresses or
/// `vertexPipelineStoresAndAtomics` (naming what it needs), and, not implemented, for a
/// post-tessellation vertex function, an attribute a hand-built projection fetches in fixed
/// function under the indexed form, an indirect or amplified draw, and an indexed draw whose
/// indices run past its buffer or whose index offset is not a multiple of the index size.
TileReach,
/// A program-scope buffer binding of MSL 3.2 (macOS 15 and later), `constant T* constant p
/// [[buffer(n)]];` in Apple's `!air.global_bindings` list, valid AIR this version does not
/// implement yet.
@@ -1947,9 +1937,8 @@ pub enum BindError {
/// and instantiates the dispatch there. Nothing is dispatched on the plan asked. A draw answers
/// it when the pipeline planned is not the variant its vertex function's render target slice
/// asks for at the shape's render target array length (`VariantKey::dropped_vertex_layer`);
/// `variant` is then the plan's own. A draw of a capture variant answers it when the draw is of
/// the other capture form (`VariantKey::captured_positions`): `variant` is the plan's with the
/// draw's form. Boxed: a key holds a set per kind of variant, and the error stays small.
/// `variant` is then the plan's own. Boxed: a key holds a set per kind of variant, and the
/// error stays small.
NeedsVariant {
variant: Box<crate::cache::VariantKey>,
},
@@ -2018,9 +2007,10 @@ pub enum BindError {
/// not a mesh render pipeline, or a draw of primitives or patches with one (Metal ends the
/// process on `drawPrimitives` with a mesh pipeline state).
InvalidMeshDraw { mesh: bool },
/// An indexed draw of an indexed capture variant (`CaptureForm::Indexed`) whose bind state
/// names no primitive type (`BindState::primitive_type`): whether the draw restarts at the
/// index type's all-ones index, where Metal shades no vertex, depends on it.
/// A draw of a pipeline whose vertex function writes the primitive ID
/// (`LoweringInputs::primitive_id_varying`) whose bind state names no primitive type
/// (`BindState::primitive_type`): its vertices per primitive, and whether an indexed draw
/// runs de-indexed (a strip's does not), depend on it.
MissingPrimitiveType,
}
@@ -1975,24 +1975,6 @@ fn padded_srgb_forms_read_and_write_metals_codes() {
assert_eq!(*g, want, "{form:?} values {r}, {gr}");
}
}
// The crate's clear texels and load codes agree with the write rule (the runtime's clear
// writes `clear_texel`, its load pass `load_code`).
for c in 0..1024u32 {
let read = step(c << 6);
let code = padded_srgb_code(ExtendedRange::R10X6Srgb, read);
assert_eq!(
ExtendedRange::R10X6Srgb.load_code(c),
Some(code),
"code {c}"
);
let read = linear(c << 6);
let code = padded_srgb_code(ExtendedRange::Rg10X12Srgb, read);
assert_eq!(
ExtendedRange::Rg10X12Srgb.load_code(c),
Some(code),
"code {c}"
);
}
}
/// `a / 3` correctly rounded to `f32` (`a` below 4): the `f64` quotient's neighbours compared
@@ -2088,12 +2070,7 @@ fn rgb10a2_srgb_reads_and_writes_metals_codes() {
let word = code(0) | code(1) << 10 | code(2) << 20 | alpha_code(v[3]) << 30;
assert_eq!(*g, [word, 0, 0, 0], "values {v:?}");
}
// The crate's clear texels and load codes agree with the rules (the runtime's clear writes
// `clear_texel`, its load pass `load_code`, alpha kept).
for c in 0..1024u32 {
let code = padded_srgb_code(ExtendedRange::R10X6Srgb, step(c));
assert_eq!(form.load_code(c), Some(code), "code {c}");
}
// The crate's clear texels agree with the rules (the runtime's clear writes `clear_texel`).
let half = |v: f64| crate::float16::f16_bits_to_f32(crate::float16::f32_to_f16_bits(v as f32));
for color in [
[0.25, 0.5, 0.75, 0.4],
+7 -20
View File
@@ -70,7 +70,6 @@ pub const fn shape(f: PushField) -> FieldShape {
match f {
PushField::RootTableAddress
| PushField::ExecutionStatusAddress
| PushField::CaptureAddress
| PushField::CaptureIndexAddress
| PushField::MergedDrawAddress
| PushField::CommandRecordsAddress
@@ -109,7 +108,7 @@ pub const fn shape(f: PushField) -> FieldShape {
PushField::ShaderTestsState => FieldShape::UVec4Array(1),
// The faces' stencil words, the references, and a zero word.
PushField::ShaderStencilState => FieldShape::UVec4Array(1),
// The draw's first vertex, vertex count, first instance, and a zero word.
// A zero word, the index count, the first instance, and the base vertex.
PushField::CaptureLayout => FieldShape::UVec4Array(1),
// Four bits of kept channels per color attachment.
PushField::StorageKeptChannels => FieldShape::U32,
@@ -457,12 +456,12 @@ mod tests {
}
}
/// A vertex function's capture addresses are holes the consumer fills, which must be in the
/// push block: the placement order puts them right after the two other addresses, so the vertex
/// window holds them whatever else the function reads, and its layout follows the window's
/// A vertex function's index address is a hole the consumer fills, which must be in the push
/// block: the placement order puts it right after the two other addresses, so the vertex
/// window holds it whatever else the function reads, and its layout follows the window's
/// other fields.
#[test]
fn the_capture_address_is_always_placed_in_the_vertex_window() {
fn the_index_address_is_always_placed_in_the_vertex_window() {
let mut later = BTreeSet::from([
PushField::AmplificationId,
PushField::AmplificationLayerOffset,
@@ -479,7 +478,6 @@ mod tests {
let (start, end) = window(Stage::Vertex);
for (root, status) in [(false, false), (true, false), (false, true), (true, true)] {
let mut fields = later.clone();
fields.insert(PushField::CaptureAddress);
fields.insert(PushField::CaptureIndexAddress);
if root {
fields.insert(PushField::RootTableAddress);
@@ -488,25 +486,14 @@ mod tests {
fields.insert(PushField::ExecutionStatusAddress);
}
let placement = check(Stage::Vertex, &fields);
let capture = placement
.fields
.iter()
.find(|f| f.field == PushField::CaptureAddress)
.expect("placed");
let at = start + 8 * (u32::from(root) + u32::from(status));
assert_eq!(capture.loc, PushLoc::Push { offset: at }, "{root} {status}");
let index = placement
.fields
.iter()
.find(|f| f.field == PushField::CaptureIndexAddress)
.expect("placed");
let after = at + capture.size;
assert_eq!(
index.loc,
PushLoc::Push { offset: after },
"{root} {status}"
);
assert!(after + index.size <= end);
assert_eq!(index.loc, PushLoc::Push { offset: at }, "{root} {status}");
assert!(at + index.size <= end);
let layout = placement
.fields
.iter()
@@ -123,8 +123,8 @@ declare { <4 x float>, i8 } @air.sample_texture_2d_grad.v4f32(ptr addrspace(1),
"#;
/// Committed profile `stem` without `samplerAnisotropy`: every Vulkan sampler is isotropic there,
/// so Metal's anisotropic filter is emulated (the emulation's home besides a cube's unmeasured
/// gradient route), the profile the emulation's shape tests compile under.
/// so Metal's anisotropic filter is emulated (the emulation's home), the profile the emulation's
/// shape tests compile under.
fn p(stem: &str) -> DeviceProfile {
let mut desc = crate::pipeline::testing::description(stem).expect(stem);
desc.features.remove(&VkFeature::SamplerAnisotropy);
@@ -19,8 +19,8 @@
//! `u32` arithmetic, where `element` is the step's element index:
//!
//! - `PerVertex`: `VertexIndex` (it includes the base vertex in Vulkan as `[[vertex_id]]` does in
//! Metal); in the indexed capture form (`CaptureForm::Indexed`), whose draw has no indices, the
//! vertex the draw's index names ([`Step::CapturedVertex`], `super::CapturedIndex`), as
//! Metal); in the de-indexed and private list forms, whose draws have no indices, the vertex
//! the draw's index names ([`Step::CapturedVertex`], `super::CapturedIndex`), as
//! `[[vertex_id]]` reads it there;
//! - `PerInstance` with rate 1: `InstanceIndex` (which includes the base instance in both APIs);
//! - `PerInstance` with rate `n > 1`: `base + (InstanceIndex - base) / n`, the element the
@@ -341,7 +341,7 @@ pub enum Step {
/// A kernel stage-in step through the index buffer on `axis`: the index at the thread position
/// clamped to the region's last element, plus the region's origin.
Indexed { axis: u8, index: IndexRead },
/// A per-vertex step in the indexed capture form: the vertex the draw's index names
/// A per-vertex step in the de-indexed or private list form: the vertex the draw's index names
/// (`super::CapturedIndex`), read once at entry.
CapturedVertex,
}
@@ -489,7 +489,7 @@ pub(super) fn select(
narrow_float_nans(cx, encoding, form);
let s = slot(Stage::Vertex, buffer);
let draw_parameters = cx.profile.fields().draw_parameters;
// The indexed capture form's per-vertex element is the vertex its index names.
// The de-indexed and private list forms' per-vertex element is the vertex its index names.
let captured = super::plan::captured_index_type(cx);
if let (VertexStepFunction::PerVertex, Some(ty)) = (step_function, captured) {
super::plan::captured_index(cx, ty)?;
+42 -270
View File
@@ -48,8 +48,8 @@
//! macOS 27.0.1: lists, strips, lines, points, indirect draws). The varying's `VertexIndex` is a
//! draw's own only without indices: an indexed draw's primitives share vertices, so it runs in
//! the de-indexed form (`LoweringInputs::primitive_id_indices`), `index count` vertices from 0
//! that read their indices at the draw's index address as the indexed capture form does
//! ([`CapturedIndex`]), whose first vertex is 0. A vertex function that writes memory is
//! that read their indices at the draw's index address ([`CapturedIndex`]), whose first vertex
//! is 0. A vertex function that writes memory is
//! refused there (it would run once per index), and so are the draws the binder cannot run
//! so (`NotImplemented(PrimitiveId)`). A draw of one of Metal's private primitive types in the
//! private list form (`LoweringInputs::private_list`) runs its list's positions from its first
@@ -112,8 +112,9 @@
//! flips y with a negative viewport) and their depth and stencil modes.
//!
//! A vertex function's position is decorated `Invariant`, `[[invariant]]` in Metal or not: every
//! pipeline that draws a vertex function computes its position the same way, so the tile reach's
//! capture of a draw's positions holds the positions the draw rasterizes.
//! pipeline that draws a vertex function computes its position the same way, so a draw run
//! through more than one variant of its pipeline (each color group's) rasterizes the same
//! positions in each.
//!
//! A fragment function compiled for a render pipeline that rasterizes more than one sample
//! (`LoweringInputs::multisampled`) reads what Metal reads at the pixel center in every invocation
@@ -258,11 +259,12 @@ pub enum Source {
/// `shaderDrawParameters`: the lane of `PushField::BaseVertexInstance` that holds the draw's
/// `base`, into an integer of this form.
DrawBase { base: DrawBase, form: Form },
/// A vertex function's `[[vertex_id]]` in the indexed capture form: the vertex its index
/// names ([`CapturedIndex`]), into an integer of this form.
/// A vertex function's `[[vertex_id]]` in the de-indexed or private list form: the vertex its
/// index names ([`CapturedIndex`]), into an integer of this form.
CapturedVertex(Form),
/// A vertex function's `[[base_vertex]]` in the indexed capture form: the draw's base vertex,
/// lane 3 of `PushField::CaptureLayout`, into an integer of this form.
/// A vertex function's `[[base_vertex]]` in the de-indexed or private list form: the draw's
/// base vertex, lane 3 of `PushField::CaptureLayout` (the word before the private list),
/// into an integer of this form.
CapturedBaseVertex(Form),
/// A merged draw's vertex function's `[[vertex_id]]`, `[[instance_id]]`, `[[base_vertex]]` or
/// `[[base_instance]]` (`LoweringInputs::merged_draws`): its corner's command's, which the
@@ -455,12 +457,9 @@ pub struct StageIoPlan {
/// A vertex function compiled under `LoweringInputs::window_depth_varying` writes its
/// position's window depth to a varying ([`WindowDepth`]).
pub window_depth: Option<WindowDepth>,
/// A vertex function compiled under `LoweringInputs::captured_positions` writes each
/// vertex's capture record ([`Capture`]).
pub capture: Option<Capture>,
/// A vertex function compiled in the indexed capture form (`CaptureForm::Indexed`) reads its
/// vertex from the draw's index buffer ([`CapturedIndex`]): planned where the function reads
/// it (`[[vertex_id]]`, a per-vertex attribute, or its record's restart flag).
/// A vertex function compiled in the de-indexed or private list form reads its vertex from
/// the draw's indices ([`CapturedIndex`]): planned where the function reads it
/// (`[[vertex_id]]`, a per-vertex attribute, `[[base_vertex]]` or the primitive ID).
pub captured_index: Option<CapturedIndex>,
/// A vertex function compiled under `LoweringInputs::merged_draws` finds its corner's command
/// at entry ([`MergedRead`]).
@@ -521,7 +520,7 @@ pub enum FirstVertex {
/// indirect one's from its arguments read on the CPU).
Push,
/// Vertex 0: the de-indexed form draws an indexed draw's indices as `index count` vertices
/// from 0 (`LoweringInputs::primitive_id_indices`), as the indexed capture form does.
/// from 0 (`LoweringInputs::primitive_id_indices`).
Zero,
}
@@ -545,36 +544,14 @@ pub struct WindowDepth {
/// entry, two extracts, the division, and the store.
const WINDOW_DEPTH_WORDS: u64 = 40;
/// How a vertex function compiled under `LoweringInputs::captured_positions` writes its capture
/// record at each return: the value it returns to its `Position` object (`position`, Metal's
/// clip position, before any compensation) and to its own `PointSize` object (`point_size`; 1.0
/// where it writes none), and the restart flag (the indexed form's raw index is its type's
/// all-ones value, [`CapturedIndex`]; 0 in the vertices form), stored as one record of
/// [`CAPTURE_RECORD_BYTES`] at its slot from `PushField::CaptureAddress`. The slot is `p +
/// (InstanceIndex - first instance) · vertex count` from `PushField::CaptureLayout`, `p` being
/// `VertexIndex` less the first vertex in the vertices form and `VertexIndex` itself in the
/// indexed form (`vertex` and `instance` are the two input builtins' objects), in 64 bits.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Capture {
pub position: usize,
pub point_size: Option<usize>,
pub vertex: usize,
pub instance: usize,
}
/// The bytes of one capture record: the clip position's four `f32`s at 0, the point size's
/// `f32` at 16, the restart flag's `u32` at 20, and words 6 and 7 reserved (unwritten).
pub(crate) const CAPTURE_RECORD_BYTES: u64 = 32;
/// How a vertex function compiled in the indexed capture form (`CaptureForm::Indexed`) reads its
/// vertex: its stream position `p = VertexIndex` (`vertex` is the input builtin's object; the
/// capture draw starts at vertex 0) names the raw index of type `ty` at
/// `PushField::CaptureIndexAddress + p · size`, read once at entry (`u16`: from the aligned word
/// that holds it, shifted by its address's bit 1), and the vertex is the raw index plus the
/// layout's base vertex (lane 3), wrapping as `u32`s. Where the draw restarts (lane 0 of
/// `PushField::CaptureLayout` is not 0: a line or triangle strip) and the raw index is the type's
/// all-ones value, the invocation stores its record's restart flag alone and returns before any
/// fetch or instruction of the body, as Metal shades no vertex there.
/// How a vertex function compiled in the primitive ID's de-indexed form
/// (`LoweringInputs::primitive_id_indices`) reads its vertex: its stream position
/// `p = VertexIndex` (`vertex` is the input builtin's object; the draw starts at vertex 0) names
/// the raw index of type `ty` at `PushField::CaptureIndexAddress + p · size`, read once at entry
/// (`u16`: from the aligned word that holds it, shifted by its address's bit 1), and the vertex is
/// the raw index plus the layout's base vertex (lane 3 of `PushField::CaptureLayout`), wrapping
/// as `u32`s. The draw is a list or points: a strip, which Metal restarts at the all-ones index,
/// does not run so (`bind::graphics`).
///
/// In the private list form (`LoweringInputs::private_list`, `first` is the draw's first vertex)
/// the draw runs its list from `first` without indices: the raw index, a `u32`, lies at
@@ -592,17 +569,9 @@ pub struct CapturedIndex {
/// The words a vertex function's index read adds: its input builtin's variable, decorations and
/// interface entry, its load, the layout's extract, the 64-bit address arithmetic, the device
/// place (its block and pointer types, conversion and access chain), the load, a `u16`'s
/// alignment and shift, the base vertex's extract and add, and the restart test, its record
/// address and the selection that returns at a strip's restart index (measured 186 for `u32` and
/// 224 for `u16` on `tests::engine_vertex_capture`'s function).
/// alignment and shift, and the base vertex's extract and add (at most 224, a `u16` read's).
pub(super) const CAPTURED_INDEX_WORDS: u64 = 400;
/// The words a vertex function's capture adds: the two input builtins' variables, decorations
/// and interface entries, their loads, the layout's extracts, the slot's 64-bit arithmetic, the
/// three device places (their block and pointer types, conversions and access chains), and the
/// three stores (measured 246 to 259 on `tests::engine_vertex_capture`'s functions).
const CAPTURE_WORDS: u64 = 300;
/// Plan an emulated post-tessellation vertex function's primitive ID output under
/// `LoweringInputs::primitive_id_varying`: the index of its object, the flat `uint` varying of
/// `IoRole::PrimitiveId` to which its entry wrapper writes its patch's position in the draw
@@ -1146,15 +1115,12 @@ fn metal_interpolated_constant(
/// come after it in program order and never reach it, as Metal's attribute is fetched before its
/// function runs.
pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<()> {
// The indexed capture form's raw index, read once in the first block, where it dominates
// every use, and a strip's restart index's return before the body.
// The de-indexed or private list form's raw index, read once in the first block, where it
// dominates every use, and the private list form's base vertex.
if let Some(c) = cx.plan.families.stage_io.captured_index {
let raw = cx.captured_index(fb)?;
match c.first {
Some(_) => {
cx.listed_base(fb)?;
}
None => skip_restart(cx, fb, c, raw)?,
cx.captured_index(fb)?;
if c.first.is_some() {
cx.listed_base(fb)?;
}
}
// A merged draw's vertex finds its corner's command before the body, which every read of the
@@ -1605,7 +1571,6 @@ pub fn emit_return(
let compensation = plan.compensation;
let depth_clamp = plan.depth_clamp;
let window_depth = plan.window_depth;
let capture = plan.capture;
let primitive_id = plan.primitive_id;
// The private masks: the pixel's ANDed into the function's own `[[sample_mask]]` output
// where this return stores one, else stored as that output.
@@ -1631,17 +1596,8 @@ pub fn emit_return(
Some(_) => Some(selected_viewport(cx, fb, x, returned, &outputs)?),
None => None,
};
// The capture record's position and point size, as the function returns them.
let (mut clip, mut size) = (None, None);
for o in &outputs {
let part = output_part(cx, fb, x, returned, o)?;
if let Some(c) = capture {
if c.position == o.link.object {
clip = Some(part);
} else if c.point_size == Some(o.link.object) {
size = Some(part);
}
}
let part =
match point_size_object(&cx.plan.families.stage_io.objects, o.link.object) {
true => metal_point_size(fb, part)?,
@@ -1675,9 +1631,6 @@ pub fn emit_return(
};
store(cx, fb, &o.link, part)?;
}
if let (Some(c), Some(clip)) = (capture, clip) {
store_capture(cx, fb, c, clip, size)?;
}
for s in &seconds {
let first = match returned {
Returned::Struct => fb.composite_extract(x, &[s.field])?,
@@ -1756,8 +1709,7 @@ fn point_size_object(objects: &[IoObject], object: usize) -> bool {
/// The point size `size` (an `f32`) a vertex or mesh function stores to `PointSize`, as Metal
/// draws it: [`METAL_POINT_SIZE_LIMIT`] where `size` is past it (an infinity too), `size` itself
/// otherwise. A NaN fails the ordered comparison and is stored as written: Metal's answer for a
/// NaN, a negative or a denormal size is not measured (the tile reach reference flags them
/// unmeasured, `bind::tile_reach`).
/// NaN, a negative or a denormal size is not measured.
pub(crate) fn metal_point_size(fb: &mut FunctionBuilder<'_>, size: SValue) -> BResult<SValue> {
let f32_ = fb.module().ty(SType::Float { width: 32 })?;
let limit = fb.module().constant(Constant::Scalar {
@@ -1832,193 +1784,9 @@ fn store_primitive_id(
store(cx, fb, &link, id)
}
/// Store vertex capture record `c` ([`Capture`]): the clip position `clip` and the point size
/// `size` (1.0 where the function writes none) at the vertex's slot from
/// `PushField::CaptureAddress`, its address and slot in 64 bits. Words 5 to 7 are left unwritten.
fn store_capture(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
c: Capture,
clip: SValue,
size: Option<SValue>,
) -> BResult<()> {
let u64_ = fb.module().ty(SType::Int {
width: 64,
signed: false,
})?;
let f32_ = fb.module().ty(SType::Float { width: 32 })?;
let vec4 = fb.module().ty(SType::Vector { elem: f32_, len: 4 })?;
let k64 = |fb: &mut FunctionBuilder<'_>, x: u64| -> BResult<SValue> {
let k = fb.module().constant(Constant::Scalar {
ty: u64_,
bits: ConstBits(x),
})?;
fb.module().const_value(k)
};
let record = record_address(cx, fb, c)?;
let place = fb.device_place(record, vec4)?;
let aligned = |n| MemAccess {
aligned: Some(n),
..MemAccess::default()
};
fb.store(place, clip, aligned(16))?;
let size = match size {
Some(size) => size,
None => {
let one = fb.module().constant(Constant::Scalar {
ty: f32_,
bits: ConstBits(u64::from(1.0f32.to_bits())),
})?;
fb.module().const_value(one)?
}
};
let sixteen = k64(fb, 16)?;
let at = fb.binary(BinOp::IAdd, record, sixteen)?;
let place = fb.device_place(at, f32_)?;
fb.store(place, size, aligned(4))?;
// The restart flag: the indexed form's raw index is its type's all-ones value.
let u32_ = fb.module().ty(SType::Int {
width: 32,
signed: false,
})?;
let k32 = |fb: &mut FunctionBuilder<'_>, x: u32| crate::memory::leaf::k32(fb, x);
let flag = match cx.plan.families.stage_io.captured_index {
Some(c) => {
let raw = cx.captured_index(fb)?;
let all = k32(fb, all_ones(c.ty))?;
let restart = fb.binary(BinOp::IEqual, raw, all)?;
let one = k32(fb, 1)?;
let zero = k32(fb, 0)?;
fb.select(restart, one, zero)?
}
None => k32(fb, 0)?,
};
let twenty = k64(fb, 20)?;
let at = fb.binary(BinOp::IAdd, record, twenty)?;
let place = fb.device_place(at, u32_)?;
fb.store(place, flag, aligned(4))
}
/// The address of capture record `c` of the invocation ([`Capture`]): `32 · slot` past
/// `PushField::CaptureAddress`, `slot = p + (InstanceIndex - first instance) · vertex count` from
/// `PushField::CaptureLayout`, where `p` is `VertexIndex` less the layout's first vertex in the
/// vertices form, and `VertexIndex` itself in the indexed form, whose draw starts at vertex 0 (its
/// layout's lane 0 says whether the draw restarts). The subtractions wrap as `u32`s; the rest is
/// 64-bit.
fn record_address(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
c: Capture,
) -> BResult<SValue> {
let u64_ = fb.module().ty(SType::Int {
width: 64,
signed: false,
})?;
let layout = cx.push_field(fb, PushField::CaptureLayout)?;
let count = fb.composite_extract(layout, &[0, 1])?;
let first_instance = fb.composite_extract(layout, &[0, 2])?;
let load = |cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, object| -> BResult<SValue> {
let g = global(cx, object)?;
let p = fb.module().global_value(g)?;
fb.load(p, MemAccess::default())
};
let vertex = load(cx, fb, c.vertex)?;
let instance = load(cx, fb, c.instance)?;
// The draw's vertex and instance, each from its first, wrapping as `u32`s.
let vertex = match cx.plan.families.stage_io.captured_index {
Some(_) => vertex,
None => {
let first_vertex = fb.composite_extract(layout, &[0, 0])?;
fb.binary(BinOp::ISub, vertex, first_vertex)?
}
};
let instance = fb.binary(BinOp::ISub, instance, first_instance)?;
let wide = |fb: &mut FunctionBuilder<'_>, x: SValue| fb.convert(ConvOp::UConvert, x, u64_);
let vertex = wide(fb, vertex)?;
let instance = wide(fb, instance)?;
let count = wide(fb, count)?;
let rows = fb.binary(BinOp::IMul, instance, count)?;
let slot = fb.binary(BinOp::IAdd, vertex, rows)?;
let bytes = fb.module().constant(Constant::Scalar {
ty: u64_,
bits: ConstBits(CAPTURE_RECORD_BYTES),
})?;
let bytes = fb.module().const_value(bytes)?;
let offset = fb.binary(BinOp::IMul, slot, bytes)?;
let base = cx.push_field(fb, PushField::CaptureAddress)?;
fb.binary(BinOp::IAdd, base, offset)
}
/// The indexed capture form's return at a strip's restart index: where the draw restarts (lane 0 of
/// `PushField::CaptureLayout` is not 0) and the raw index `raw` is its type's all-ones value, Metal
/// shades no vertex, so the invocation stores its record's restart flag (1, at byte 20; the
/// record's other words are left as they were) where it has a record, and returns before any fetch
/// or instruction of the body. A list or point draw shades that index as any other.
fn skip_restart(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
c: CapturedIndex,
raw: SValue,
) -> BResult<()> {
use crate::spirv::builder::constructs::{ArmEnd, ArmFn};
let k32 = |fb: &mut FunctionBuilder<'_>, x: u32| crate::memory::leaf::k32(fb, x);
let layout = cx.push_field(fb, PushField::CaptureLayout)?;
let restarts = fb.composite_extract(layout, &[0, 0])?;
let zero = k32(fb, 0)?;
let strip = fb.binary(BinOp::INotEqual, restarts, zero)?;
let all = k32(fb, all_ones(c.ty))?;
let at_restart = fb.binary(BinOp::IEqual, raw, all)?;
let skip = fb.binary(BinOp::LogicalAnd, strip, at_restart)?;
let flag = match cx.plan.families.stage_io.capture {
Some(record) => {
let u64_ = fb.module().ty(SType::Int {
width: 64,
signed: false,
})?;
let u32_ = fb.module().ty(SType::Int {
width: 32,
signed: false,
})?;
let record = record_address(cx, fb, record)?;
let twenty = fb.module().constant(Constant::Scalar {
ty: u64_,
bits: ConstBits(20),
})?;
let twenty = fb.module().const_value(twenty)?;
let at = fb.binary(BinOp::IAdd, record, twenty)?;
Some((fb.device_place(at, u32_)?, k32(fb, 1)?))
}
None => None,
};
let leave: ArmFn<'_, ()> = Box::new(move |fb, _| {
if let Some((place, one)) = flag {
fb.store(
place,
one,
MemAccess {
aligned: Some(4),
..MemAccess::default()
},
)?;
}
fb.ret(None)?;
Ok(ArmEnd::Exits)
});
fb.if_(&mut (), skip, leave, None)?;
Ok(())
}
/// The all-ones index of `ty`, Metal's strip restart index.
fn all_ones(ty: crate::metal::IndexType) -> u32 {
match ty {
crate::metal::IndexType::UInt16 => 0xffff,
crate::metal::IndexType::UInt32 => u32::MAX,
}
}
/// The raw index an indexed capture form's vertex reads ([`CapturedIndex`]), loaded in the open
/// block: `PushField::CaptureIndexAddress + p · size` with `p = VertexIndex` (the capture draw
/// starts at vertex 0), in 64 bits. A `u32` index is read where it lies (the address is a
/// The raw index a de-indexed or private list form's vertex reads ([`CapturedIndex`]), loaded in
/// the open block: `PushField::CaptureIndexAddress + p · size` with `p = VertexIndex` (the
/// de-indexed draw starts at vertex 0), in 64 bits. A `u32` index is read where it lies (the address is a
/// multiple of 4); a `u16` one from the aligned word that holds it, shifted right by 16 where its
/// address's bit 1 is set, and masked to 16 bits. [`EmitCx::captured_index`] reads it once where
/// it dominates.
@@ -2027,7 +1795,7 @@ pub(crate) fn read_captured_index(
fb: &mut FunctionBuilder<'_>,
) -> BResult<SValue> {
let Some(c) = cx.plan.families.stage_io.captured_index else {
return Err(cx.fail("a capture index read without its plan"));
return Err(cx.fail("an index read without its plan"));
};
let u64_ = fb.module().ty(SType::Int {
width: 64,
@@ -2084,8 +1852,8 @@ pub(crate) fn read_captured_index(
}
}
/// The vertex an indexed capture form's function runs ([`CapturedIndex`]): its raw index plus
/// the base vertex ([`captured_base_vertex`]), wrapping as `u32`s.
/// The vertex a de-indexed or private list form's function runs ([`CapturedIndex`]): its raw
/// index plus the base vertex ([`captured_base_vertex`]), wrapping as `u32`s.
pub(super) fn captured_vertex(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
@@ -2604,9 +2372,13 @@ fn nan_drop(cx: &mut EmitCx<'_>) -> BResult<Option<NanDrop>> {
/// flushes denormals keeps a positive one and makes -0 and a negative one +0 alike. A positive NaN
/// fails Metal's depth test, `Always` included: neither depth nor color is written and no sample
/// counts; the invocation is dropped by `kill` ([`nan_drop`]), which drops the same, though Metal
/// also runs the stencil's depth-fail operation; a device that clamps the depth itself stores a NaN
/// as anything (ANV: 0, its color written), so every profile drops it. In a function looping over
/// its covered samples the value passes unchanged. The selects run only where the plan `clamps`,
/// also runs the stencil's depth-fail operation. The drop is capability on every profile: no device
/// has a defined form, since Vulkan leaves a NaN depth undefined after its clamp and range step,
/// with or without depth clamp ("Depth Clamping and Range Adjustment": "If zf is not in the range
/// [zmin, zmax], then zf is undefined following this step", and a NaN lies in no range; only
/// `depthClampZeroOne`, which no profile enables, keeps a float depth unchanged), and a device
/// that clamps the depth itself stores a NaN as anything (ANV: 0, its color written). In a
/// function looping over its covered samples the value passes unchanged. The selects run only where the plan `clamps`,
/// the device storing the value unclamped; elsewhere its own clamp gives Metal's answers.
///
/// Under `range`, `PushField::DepthClampRange`'s `[low, high]`, the value is then clamped to the
+31 -107
View File
@@ -19,7 +19,7 @@ use crate::lower::stage_io::{
use crate::pipeline::artifact::PrecisionNote;
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::lower_inputs::{
CaptureForm, FactorLane, RotatedBlendForm, VertexFetch, ViewportCompensation,
FactorLane, RotatedBlendForm, VertexFetch, ViewportCompensation,
};
use crate::pipeline::stage_io::{
DepthMode, Interpolation, IoNumeric, IoRole, IoType, IoVariable, Sampling, StageBuiltin,
@@ -480,9 +480,9 @@ pub fn param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error> {
.copied();
let pulled = entry.filter(|f| matches!(f, VertexFetch::Pulled { .. }));
let f = io_form(cx, ty)?;
// The indexed capture form's and the de-indexed form's draws have no indices, so
// fixed-function input would fetch at the stream position: their projection pulls
// every attribute, and a hand-built one that does not is refused.
// The de-indexed and private list forms' draws have no indices, so fixed-function
// input would fetch at the stream position: their projection pulls every attribute,
// and a hand-built one that does not is refused.
if pulled.is_none() && captured_index_type(cx).is_some() {
return Err(Unsupported::not_implemented(indices_feature(cx)).into());
}
@@ -720,8 +720,9 @@ pub fn param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error> {
{
return zero_index(cx, b, ty, StageBuiltin::ViewportIndex);
}
// The indexed capture form draws without indices: its vertex is the one its index names,
// and its base vertex the layout's, whatever the profile's draw parameters.
// The de-indexed and private list forms draw without indices: the vertex is the one its
// index names, and its base vertex the layout's (the list's), whatever the profile's draw
// parameters.
(ParamRole::Builtin(Builtin::VertexId), Stage::Vertex)
if captured_index_type(cx).is_some() =>
{
@@ -2446,10 +2447,6 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> {
sp.words = sp.words.saturating_add(super::WINDOW_DEPTH_WORDS);
}
}
// The capture form: each vertex's clip position and point size, written to its record.
if let (Some(form), Stage::Vertex) = (cx.inputs.captured_positions, cx.stage) {
capture(cx, form)?;
}
// The primitive ID a fragment function reads from its varying (an emulated post-tessellation
// vertex function's is its patch's position, `lower::tessellation::emulated`).
if cx.inputs.primitive_id_varying && cx.stage == Stage::Vertex {
@@ -2499,83 +2496,14 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> {
Ok(())
}
/// Plan a vertex function's capture form `form` (`LoweringInputs::captured_positions`): the
/// record of its `Position` output and its own `PointSize` output ([`super::Capture`]), the
/// record's address and layout push fields, the vertex and instance indices, the indexed form's
/// index read ([`captured_index`], whatever else the function reads: its record's restart flag
/// and a strip's restart test need it), and
/// `RuntimeFact::CapturedPositions`, which every function compiled in the form states, so its
/// plans state the variant. A function that writes no position rasterizes nothing and plans no
/// record. Refused [`Feature::TileReach`]: a post-tessellation vertex function (its vertices are
/// the tessellator's, not the draw's), and a device without device addresses or without the
/// vertex stage's stores, naming what it needs.
fn capture(cx: &mut SelectCx<'_>, form: CaptureForm) -> Result<(), Error> {
if matches!(cx.entry.ep.stage, AirStage::Vertex { patch: Some(_) }) {
return Err(Unsupported::not_implemented(Feature::TileReach).into());
}
cx.facts.insert(RuntimeFact::CapturedPositions { form });
// The indexed form reads its index whatever else it reads: a strip's restart index runs no
// body.
if let Some(ty) = form.index_type() {
captured_index(cx, ty)?;
}
let output = |o: &IoObject, b| matches!(o, IoObject::Builtin { builtin, dir: IoDir::Output, .. } if *builtin == b);
let sp = &cx.families.stage_io;
let Some(position) = sp.objects.iter().position(|o| output(o, B::Position)) else {
return Ok(());
};
// The function's own point size: the default one the vertex stage writes is planned later,
// and the record takes 1.0 for it.
let point_size = sp
.outputs
.iter()
.map(|o| o.link.object)
.find(|&i| sp.objects.get(i).is_some_and(|o| output(o, B::PointSize)));
refuse_unaddressed(cx)?;
let f = cx.profile.fields();
let enabled = &f.enabled.features;
if let Some(stores) =
crate::lower::access::dynamic::stage_stores(Stage::Vertex).find(|s| !enabled.contains(s))
{
return Err(Unsupported::needs(Feature::TileReach, Capability::Feature(stores)).into());
}
cx.push.insert(PushField::CaptureAddress);
cx.push.insert(PushField::CaptureLayout);
let sp = &mut cx.families.stage_io;
let vertex = builtin(
sp,
B::VertexIndex,
IoDir::Input,
Shape::U32,
StageBuiltin::VertexIndex,
);
let instance = builtin(
sp,
B::InstanceIndex,
IoDir::Input,
Shape::U32,
StageBuiltin::InstanceIndex,
);
sp.capture = Some(super::Capture {
position,
point_size,
vertex,
instance,
});
sp.words = sp.words.saturating_add(super::CAPTURE_WORDS);
Ok(())
}
/// The index type of the draw whose indices a vertex function reads at their address: the
/// indexed capture form's (`CaptureForm::Indexed`), else the private list form's `u32`
/// (`LoweringInputs::private_list`), else the primitive ID's de-indexed form's
/// (`LoweringInputs::primitive_id_indices`, under `primitive_id_varying`); `None` for any other
/// function.
/// private list form's `u32` (`LoweringInputs::private_list`), else the primitive ID's de-indexed
/// form's (`LoweringInputs::primitive_id_indices`, under `primitive_id_varying`); `None` for any
/// other function.
pub(super) fn captured_index_type(cx: &SelectCx<'_>) -> Option<crate::metal::IndexType> {
match (cx.stage, cx.inputs.captured_positions) {
(Stage::Vertex, Some(form)) => form.index_type(),
(Stage::Vertex, None) if cx.inputs.private_list => Some(crate::metal::IndexType::UInt32),
(Stage::Vertex, None) => cx
match cx.stage {
Stage::Vertex if cx.inputs.private_list => Some(crate::metal::IndexType::UInt32),
Stage::Vertex => cx
.inputs
.primitive_id_indices
.filter(|_| cx.inputs.primitive_id_varying),
@@ -2586,22 +2514,20 @@ pub(super) fn captured_index_type(cx: &SelectCx<'_>) -> Option<crate::metal::Ind
/// Whether a vertex function runs in the private list form (`LoweringInputs::private_list`): its
/// list's positions from the draw's first vertex, Metal's base vertex in the word before.
pub(super) fn listed(cx: &SelectCx<'_>) -> bool {
cx.stage == Stage::Vertex && cx.inputs.captured_positions.is_none() && cx.inputs.private_list
cx.stage == Stage::Vertex && cx.inputs.private_list
}
/// The feature a form that reads a draw's indices or records at their addresses serves: tile
/// reach for the capture form, Metal's private primitive types for the private list form, the
/// primitive ID for its de-indexed form.
/// The feature a form that reads a draw's indices at their address serves: Metal's private
/// primitive types for the private list form, the primitive ID for its de-indexed form.
fn indices_feature(cx: &SelectCx<'_>) -> Feature {
match cx.inputs.captured_positions {
Some(_) => Feature::TileReach,
None if listed(cx) => Feature::PrivatePrimitives,
None => Feature::PrimitiveId,
match listed(cx) {
true => Feature::PrivatePrimitives,
false => Feature::PrimitiveId,
}
}
/// Refuse the capture form or the de-indexed form ([`indices_feature`]) on a device without
/// device addresses, naming what it needs: the records and the indices are reached by address.
/// Refuse the de-indexed or private list form ([`indices_feature`]) on a device without device
/// addresses, naming what it needs: the indices are reached by address.
fn refuse_unaddressed(cx: &SelectCx<'_>) -> Result<(), Error> {
if cx.profile.fields().buffer_access != crate::device::profile::BufferAccess::Addressed {
return Err(Unsupported::needs_any_of(
@@ -2613,9 +2539,9 @@ fn refuse_unaddressed(cx: &SelectCx<'_>) -> Result<(), Error> {
Ok(())
}
/// Plan the index read of type `ty` of the indexed capture form, the de-indexed form or the
/// private list form once ([`super::CapturedIndex`]): its address push field, the capture and
/// de-indexed forms' layout, the private list form's first vertex (as the primitive ID's,
/// Plan the index read of type `ty` of the de-indexed form or the private list form once
/// ([`super::CapturedIndex`]): its address push field, the de-indexed form's layout, the private
/// list form's first vertex (as the primitive ID's,
/// [`first_vertex`]) and its fact, and the vertex index builtin. Refused ([`indices_feature`]) on
/// a device without device addresses.
pub(super) fn captured_index(
@@ -2651,7 +2577,8 @@ pub(super) fn captured_index(
}
/// Plan builtin parameter `b` of AIR type `ty`, a scalar integer, of a vertex function in the
/// indexed capture form of index type `index` (`None` for `[[base_vertex]]`): `[[vertex_id]]` is
/// de-indexed or private list form of index type `index` (`None` for `[[base_vertex]]`):
/// `[[vertex_id]]` is
/// the vertex its index names ([`Source::CapturedVertex`]), `[[base_vertex]]` the layout's base
/// vertex ([`Source::CapturedBaseVertex`]).
fn captured_param(
@@ -2690,14 +2617,13 @@ fn captured_param(
/// (`Unsupported{GpuEncodedIndirectCommands, NotImplemented}`): one compiled without
/// `replay_bindings`, or under an input that reads the draw's own vertex or instance indices or
/// draws it more than once (the primitive ID's varying or de-indexed form, the private list form,
/// the capture form, amplifications drawn apart, tessellation).
/// amplifications drawn apart, tessellation).
fn merged(cx: &mut SelectCx<'_>) -> Result<(), Error> {
let i = cx.inputs;
if !i.replay_bindings
|| i.primitive_id_varying
|| i.primitive_id_indices.is_some()
|| i.private_list
|| i.captured_positions.is_some()
|| i.amplification_draws.is_some()
|| i.tessellation.is_some()
{
@@ -2880,8 +2806,9 @@ fn output(cx: &mut SelectCx<'_>, o: &OutputBinding, ty: AirTypeId) -> Result<Lin
}
};
Ok(match &o.role {
// Decorated `Invariant` whether or not Metal's position is `[[invariant]]`: a draw's
// captured positions (the tile reach's capture variant) are then its drawn ones.
// Decorated `Invariant` whether or not Metal's position is `[[invariant]]`: a draw run
// through more than one variant of its pipeline (each color group's) rasterizes the same
// positions in each.
OutputRole::Position { .. } if vertex => {
let f = io_form(cx, ty)?;
float_lanes(f, 4)?;
@@ -3192,10 +3119,7 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
// where Metal shades each vertex the indices name as its GPU shades it: a function that
// writes memory would write once per index. The private list form runs it once per list
// position, as Metal runs its private types.
let deindexed = cx.stage == Stage::Vertex
&& cx.inputs.captured_positions.is_none()
&& captured_index_type(cx).is_some()
&& !listed(cx);
let deindexed = cx.stage == Stage::Vertex && captured_index_type(cx).is_some() && !listed(cx);
if deindexed && writes {
return Err(Unsupported::not_implemented(Feature::PrimitiveId).into());
}
+6 -40
View File
@@ -188,8 +188,9 @@ pub enum FormatEmulation {
/// function reads and writes through its slot's [`ExtendedRange`] variant
/// (`LoweringInputs::extended_range`), converting Metal's values in the shader. Exact for a
/// sampled image a function fetches from and for a storage image; admitted for those usages
/// and for a color attachment, whose render pass clears and loads the raw codes as Metal's does
/// (`clear_texel`; the runtime's load pass). Metal filters no bfloat texel (a linear sample
/// and for a color attachment, whose render pass clears the raw codes as Metal's does
/// (`clear_texel`) and keeps the codes its draws do not write, where Metal's pass takes them
/// through `half` (the runtime's `extended-range-bits-kept`). Metal filters no bfloat texel (a linear sample
/// reads the nearest texel) and blends none (its validation asserts), so a filter and a blend
/// are not admitted.
Bfloat,
@@ -349,9 +350,9 @@ pub enum ExtendedRange {
/// a `half` read with ties away from zero), and alpha's 2-bit code `a` reads `a / 3`
/// correctly rounded and a write stores the exact product of the value, clamped to `[0, 1]`
/// (a NaN 0), with 3, rounded to nearest. A render pass's store rounds a `float` output to
/// `half` toward zero first, a clear goes through `half` (nearest even), and a pass that loads
/// it and draws elsewhere writes each color code back as `R10Unorm_X6_sRGB`'s
/// ([`load_code`](Self::load_code)), alpha kept.
/// `half` toward zero first, a clear goes through `half` (nearest even), and Metal's pass that
/// loads it and draws elsewhere writes each color code back as `R10Unorm_X6_sRGB`'s, alpha
/// kept, where the device's pass keeps the codes (the runtime's `extended-range-bits-kept`).
Rgb10A2Srgb,
/// `R16Bfloat` (26): a bfloat code (the top 16 bits of an IEEE `float`) in a little-endian
/// 16-bit word, held as `R16_UINT` ([`FormatEmulation::Bfloat`]). Measured on an Apple M4
@@ -738,41 +739,6 @@ impl ExtendedRange {
ExtendedRange::Rgba16Bfloat => rgba,
}
}
/// The code a padded form's word of code `c` holds after a render pass that loads it and
/// draws, where no draw writes it: Metal's pass reads the word and writes it back, its
/// decoded value encoded again (an Apple M4 and an Apple M3 Max, byte-identical). `c` itself
/// for `R10Unorm_X6` and `RG10Unorm_X12`; `R10Unorm_X6_sRGB`'s write of its read, which moves
/// the 23 codes no write stores, and so does each color channel's code of `RGB10A2Unorm_sRGB`
/// (an Apple M3 Max under macOS 27.0.1, every code; its alpha's code stays);
/// `RG10Unorm_X12_sRGB`'s write code of `c`. A bfloat form's code
/// `c` (each channel's 16-bit word) holds the code a `Clear` of its value stores under
/// [`ClearRoute::ThroughHalf`] ([`clear_texel`](Self::clear_texel)): the `float` of its bits
/// rounded to `half` to nearest even (past the largest `half`, the infinity), then the bfloat
/// code nearest that, ties to even, a NaN `0x7fc0` (an Apple M4 under macOS 27.0.1: every code
/// of each bfloat format through a pass that loads it and draws into another attachment; 56,829
/// codes move). The M4's pass alone is measured. `None` for another form, or a code past the
/// form's (1023, or a bfloat form's `0xffff`).
pub fn load_code(self, c: u32) -> Option<u32> {
if self.bfloat() {
let c = u16::try_from(c).ok()?;
let value = f64::from(f32::from_bits(u32::from(c) << 16));
return Some(self.clear_texel([value; 4], ClearRoute::ThroughHalf)[0]);
}
let at = usize::try_from(c).ok().filter(|&c| c < 1024)?;
match self {
ExtendedRange::R10X6 | ExtendedRange::Rg10X12 => Some(c),
ExtendedRange::R10X6Srgb | ExtendedRange::Rgb10A2Srgb => {
let step = padded_srgb::R10X6_SRGB_DECODE_STEPS[at];
let first = &padded_srgb::R10X6_SRGB_ENCODE_FIRST;
Some(first.partition_point(|&f| f <= step).saturating_sub(1) as u32)
}
ExtendedRange::Rg10X12Srgb => {
Some(u32::from(padded_srgb::RG10X12_SRGB_WRITE_CODES[at]))
}
_ => None,
}
}
}
/// How Metal converts a render pass's clear color to a bfloat attachment's codes
@@ -2,8 +2,8 @@
//! Apple M3 Max under macOS 26.7 (the M3's and the M4's files byte-identical): `R10Unorm_X6_sRGB`'s
//! decode step of every code and first encode index of every code, and `RG10Unorm_X12_sRGB`'s code
//! of every linear write code. The shader's `lower::arith::extended_range` declares them once per
//! module that reads or writes such a texture; the runtime's clear values and load pass read them
//! through `ExtendedRange::clear_texel` and `ExtendedRange::load_code`.
//! module that reads or writes such a texture; the runtime's clear values read them through
//! `ExtendedRange::clear_texel`.
/// The decode step `s` of every code `c` of `R10Unorm_X6_sRGB`: Metal reads `s / 8192` (every
/// code read).
+43 -130
View File
@@ -402,41 +402,19 @@ pub struct DepthBias {
/// primitives take a bias at all. It follows the topology only, never the bias values, so one
/// pipeline serves every bias the encoder sets.
pub enable: bool,
/// `depthBiasConstantFactor`: Metal's `depthBias`, in the unit `unit` names.
/// `depthBiasConstantFactor`: Metal's `depthBias`, in the device's unit `r` for the depth
/// attachment's format.
pub constant_factor: f32,
/// `depthBiasClamp`: Metal's `clamp` (0 does not clamp in either API).
pub clamp: f32,
/// `depthBiasSlopeFactor`: Metal's `slopeScale`.
pub slope_factor: f32,
/// The unit `constant_factor` counts, and so the command that records the three factors.
pub unit: DepthBiasUnit,
}
/// The unit a [`DepthBias`]'s constant factor counts (Vulkan's r), which names the command that
/// records the factors.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DepthBiasUnit {
/// The device's own for the depth attachment's format: `vkCmdSetDepthBias`.
Device,
/// Depth itself, so the constant factor is the bias: `vkCmdSetDepthBias2EXT` with a
/// `VkDepthBiasRepresentationInfoEXT` of `VK_DEPTH_BIAS_REPRESENTATION_FLOAT_EXT` and
/// `depthBiasExact` (`VK_EXT_depth_bias_control`'s `floatRepresentation` and
/// `depthBiasExact`).
Depth,
/// 2^-n for a depth aspect of n fixed-point bits: `vkCmdSetDepthBias2EXT` with a
/// `VkDepthBiasRepresentationInfoEXT` of
/// `VK_DEPTH_BIAS_REPRESENTATION_LEAST_REPRESENTABLE_VALUE_FORMAT_EXT` and `depthBiasExact`
/// (`VK_EXT_depth_bias_control`'s `depthBiasExact`).
ExactFormatUnit,
}
/// The Vulkan depth bias of the render encoder's `setDepthBias:slopeScale:clamp:` for a pipeline
/// of `topology` (`GraphicsState::topology`, or the draw's from [`input_assembly`]), in a pass
/// whose depth attachment's texture is of `depth_format` (`None` without one). `DEPTH_BIAS` is
/// dynamic state on every render pipeline: create the pipeline with `enable` and record the three
/// factors by the command `unit` names (Metal's default is no bias, all three 0).
/// of `topology` (`GraphicsState::topology`, or the draw's from [`input_assembly`]). `DEPTH_BIAS`
/// is dynamic state on every render pipeline: create the pipeline with `enable` and record the
/// three factors with `vkCmdSetDepthBias` (Metal's default is no bias, all three 0).
///
/// Metal biases triangles only, never points or lines; Vulkan biases triangles (a tessellation
/// pipeline's included) and may bias points and lines, so `enable` is set for triangle and patch
@@ -444,26 +422,22 @@ pub enum DepthBiasUnit {
/// `depthBiasClamp` (`VUID-vkCmdSetDepthBias-depthBiasClamp-00790`) unless both bias factors are
/// 0, when no bias exists to clamp and the clamp is dropped.
///
/// A float depth format's constant factor counts Vulkan's r, which is Metal's. A `Depth16Unorm`
/// depth's is Metal's own rule (measured on an Apple M3 Max and an M4, plain and validated, and on
/// the M3 Max under macOS 27.0.1 with slopes too): wherever the constant `c` (finite) or the slope
/// factor is nonzero, the constant biases by `c + 1` units of 1/65535 for `c` of 0 or more and
/// `c - 1` below, as `float` (so a slope alone brings one unit), which is added to the depth
/// rounded toward zero, and the sum stored rounded to nearest. Vulkan leaves a unorm
/// format's unit to the device, up to twice 2^-16, unless `depthBiasExact` pins it: with
/// `floatRepresentation` too the factor is that bias in depth ([`DepthBiasUnit::Depth`]), and with
/// `depthBiasExact` alone it is the same bias counted in 2^-16
/// ([`DepthBiasUnit::ExactFormatUnit`]), a scale by a power of two, so the device adds Metal's
/// `float` bias either way. The device's own addition rounds the sum, to nearest where measured, so
/// a biased depth within one `float` ulp above a code's midpoint can store one code above Metal's.
/// A device without `depthBiasExact` takes Metal's `c` in its own unit ([`DepthBiasUnit::Device`]),
/// as a Metal device does; elsewhere that unit is the device's.
/// The constant factor counts the device's own unit `r` on every depth format. A float depth
/// format's is Metal's (`2^(e - n)` of the primitive's largest exponent). A `Depth16Unorm` depth's
/// is the device's: Vulkan leaves a fixed-point format's `r` to the implementation, at most
/// `2 × 2^-16` ("Depth Bias"), where Metal biases by its own rule (measured on an Apple M3 Max and
/// an M4, plain and validated, and on the M3 Max under macOS 27.0.1 with slopes too): wherever the
/// constant `c` (finite) or the slope factor is nonzero, by `c + 1` units of 1/65535 for `c` of 0
/// or more and `c - 1` below, as `float` (so a slope alone brings one unit), added to the depth
/// rounded toward zero, and the sum stored rounded to nearest. The runtime announces the device's
/// bias there (`unorm-depth-bias`) where the profile does not take
/// [`DriverDeviation::MetalDepth16BiasedStores`](crate::error::DriverDeviation::MetalDepth16BiasedStores)
/// (MoltenVK, which hands Metal its constant).
pub fn depth_bias(
topology: vk::PrimitiveTopology,
depth_bias: f32,
slope_scale: f32,
clamp: f32,
depth_format: Option<PixelFormat>,
profile: &DeviceProfile,
) -> Result<DepthBias, Error> {
use vk::PrimitiveTopology as T;
@@ -482,45 +456,19 @@ pub fn depth_bias(
constant_factor: 0.0,
clamp: 0.0,
slope_factor: 0.0,
unit: DepthBiasUnit::Device,
});
}
if clamp != 0.0 {
require(profile, VkFeature::DepthBiasClamp, Feature::DepthBiasClamp)?;
}
let enabled = &profile.fields().enabled.features;
// A bias is set (the return above): a constant, a slope or both.
let unorm16 = depth_format == Some(PixelFormat::Depth16Unorm)
&& depth_bias.is_finite()
&& enabled.contains(&VkFeature::DepthBiasExact);
let (constant_factor, unit) = if !unorm16 {
(depth_bias, DepthBiasUnit::Device)
} else {
let units = depth16_units(depth_bias);
if enabled.contains(&VkFeature::FloatRepresentation) {
((units / 65535.0) as f32, DepthBiasUnit::Depth)
} else {
(
(units * 65536.0 / 65535.0) as f32,
DepthBiasUnit::ExactFormatUnit,
)
}
};
Ok(DepthBias {
enable,
constant_factor,
constant_factor: depth_bias,
clamp,
slope_factor: slope_scale,
unit,
})
}
/// Metal's `c ± 1` units of 1/65535 for a `Depth16Unorm` depth's constant `c` (finite), exact in
/// `f64`: `c + 1` for `c` of 0 or more, `c - 1` below ([`depth_bias`]).
fn depth16_units(c: f32) -> f64 {
f64::from(c) + if c >= 0.0 { 1.0 } else { -1.0 }
}
#[cfg(test)]
mod tests {
use super::*;
@@ -702,24 +650,23 @@ mod tests {
constant_factor,
clamp,
slope_factor,
unit: DepthBiasUnit::Device,
})
};
assert_eq!(
depth_bias(triangles, 1.0, 2.0, 0.0, None, floor.profile()),
depth_bias(triangles, 1.0, 2.0, 0.0, floor.profile()),
bias(true, 1.0, 0.0, 2.0)
);
assert_eq!(
depth_bias(triangles, 1.0, 2.0, 0.5, None, floor.profile()),
depth_bias(triangles, 1.0, 2.0, 0.5, floor.profile()),
Err(needs(Feature::DepthBiasClamp, VkFeature::DepthBiasClamp))
);
assert_eq!(
depth_bias(triangles, 1.0, 2.0, -0.5, None, lavapipe.profile()),
depth_bias(triangles, 1.0, 2.0, -0.5, lavapipe.profile()),
bias(true, 1.0, -0.5, 2.0)
);
// No bias to clamp: the clamp is dropped on any device.
assert_eq!(
depth_bias(triangles, 0.0, 0.0, 0.5, None, floor.profile()),
depth_bias(triangles, 0.0, 0.0, 0.5, floor.profile()),
bias(true, 0.0, 0.0, 0.0)
);
assert_eq!(
@@ -728,7 +675,6 @@ mod tests {
1.0,
0.0,
0.0,
None,
floor.profile()
),
bias(true, 1.0, 0.0, 0.0)
@@ -737,7 +683,7 @@ mod tests {
for &ty in PrimitiveType::ALL {
let (topology, _) = input_assembly(ty);
let triangle = matches!(ty, PrimitiveType::Triangle | PrimitiveType::TriangleStrip);
let mapped = depth_bias(topology, 1.0, 2.0, 0.5, None, lavapipe.profile()).unwrap();
let mapped = depth_bias(topology, 1.0, 2.0, 0.5, lavapipe.profile()).unwrap();
assert_eq!(mapped.enable, triangle, "{ty:?}");
if !triangle {
assert_eq!(
@@ -747,72 +693,39 @@ mod tests {
constant_factor: 0.0,
clamp: 0.0,
slope_factor: 0.0,
unit: DepthBiasUnit::Device,
}
);
assert!(depth_bias(topology, 1.0, 2.0, 0.5, None, floor.profile()).is_ok());
assert!(depth_bias(topology, 1.0, 2.0, 0.5, floor.profile()).is_ok());
}
}
}
/// A `Depth16Unorm` depth's constant bias is Metal's `c ± 1` units of 1/65535 as `float`
/// (one unit for a constant of 0 beside a slope): in depth where the device has
/// `floatRepresentation` and `depthBiasExact`, in 2^-16 where it has `depthBiasExact` alone,
/// and Metal's `c` in the device's own unit elsewhere, as on a float depth format.
/// A constant bias is Metal's constant in the device's own unit on every device: a
/// `Depth16Unorm` depth takes no unit of Metal's (`c ± 1` units of 1/65535) through
/// `depthBiasExact` where the device supports it (lavapipe's and NVIDIA's do), nor one for a
/// slope alone.
#[test]
fn a_unorm_depth_bias_is_metals_where_the_device_pins_its_unit() {
fn a_unorm_depth_bias_is_metals_constant_in_the_devices_unit() {
let triangles = vk::PrimitiveTopology::TRIANGLE_LIST;
let d16 = Some(PixelFormat::Depth16Unorm);
let (lavapipe, nvidia, moltenvk) = (
committed("lavapipe"),
committed("nvidia-rtx5080-laptop"),
committed("moltenvk-m3"),
);
let mapped = |device: &Device, constant: f32, format| {
let bias = depth_bias(triangles, constant, 0.5, 0.0, format, device.profile()).unwrap();
assert_eq!(bias.slope_factor, 0.5);
(bias.constant_factor, bias.unit)
};
for (constant, units) in [
(3.0f32, 4.0f64),
(-3.0, -4.0),
(0.5, 1.5),
(-1000.0, -1001.0),
] {
assert_eq!(
mapped(&lavapipe, constant, d16),
((units / 65535.0) as f32, DepthBiasUnit::Depth)
);
let (scaled, unit) = mapped(&nvidia, constant, d16);
assert_eq!(unit, DepthBiasUnit::ExactFormatUnit);
// A power of two apart: the device's 2^-16 times the factor is the same `float`.
assert_eq!(scaled / 65536.0, (units / 65535.0) as f32);
assert_eq!(
mapped(&moltenvk, constant, d16),
(constant, DepthBiasUnit::Device)
);
for format in [None, Some(PixelFormat::Depth32Float)] {
for stem in ["lavapipe", "nvidia-rtx5080-laptop", "moltenvk-m3"] {
let device = committed(stem);
for constant in [3.0f32, -3.0, 0.5, -1000.0, 0.0, f32::INFINITY] {
let bias = depth_bias(triangles, constant, 0.5, 0.0, device.profile()).unwrap();
assert_eq!(
mapped(&lavapipe, constant, format),
(constant, DepthBiasUnit::Device)
(bias.constant_factor, bias.slope_factor),
(constant, 0.5),
"{stem} {constant}"
);
}
let none = depth_bias(triangles, 0.0, 0.0, 0.0, device.profile()).unwrap();
assert_eq!(none.constant_factor, 0.0, "{stem}");
}
// Lavapipe and NVIDIA's devices support `depthBiasExact`, which no bias pins.
for (stem, desc) in committed_descriptions() {
if stem == "lavapipe" || stem == "nvidia-rtx5080-laptop" {
assert!(desc.features.contains(&VkFeature::DepthBiasExact), "{stem}");
}
}
// A slope alone (`mapped`'s 0.5) brings one unit; no bias at all brings none.
assert_eq!(
mapped(&lavapipe, 0.0, d16),
((1.0f64 / 65535.0) as f32, DepthBiasUnit::Depth)
);
let none = depth_bias(triangles, 0.0, 0.0, 0.0, d16, lavapipe.profile()).unwrap();
assert_eq!(
(none.constant_factor, none.unit),
(0.0, DepthBiasUnit::Device)
);
assert_eq!(mapped(&moltenvk, 0.0, d16), (0.0, DepthBiasUnit::Device));
assert_eq!(
mapped(&lavapipe, f32::INFINITY, d16),
(f32::INFINITY, DepthBiasUnit::Device)
);
}
#[test]
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more