rt: a bind refills its own slot's facts and fields; a push records only the words its command buffer lacks

What. A render encoder's bind now marks its own slot (Rebound: per function a bit per buffer,
texture and sampler slot, plus the factor buffer and the alpha test reference). The next draw finds
again only those slots' facts (Facts::find and Facts::align filtered by Rebound: the vertex
binding's offset, the buffer's alignment and nil, and per slot whether it reaches a device copy, what
the host reads or an attachment, kept as slot bits) and fills only those slots' fields (fill_push
filtered by Rebound), writing into the parameter ring only a parameter block one of them is in. A
change of pipeline state is Rebound::ALL: every fact and field, as before. A pass's move to the
feedback layout refills every texture field, and a change of the shadow slots refills the slots that
join or leave them. Push constants are the VkCommandBuffer's (Pushed, shared by every encoder): a
draw or a dispatch pushes from the first word that differs from what the command buffer holds to the
last, plus every word past what it holds; a render encoder whose own push left Pushed's mark
compares only the words its fill wrote. Metrics::push_bytes counts the bytes pushed. The compute
encoder pushes only changed words too; its per-slot refill is the next step.

Why. rtmeasure (lavapipe, release, layer off, rt at b34b80832b): fill_push + Facts::find + the held
block cost gb-780m-u4 786 instructions a draw (11.5% of rt's) and windrag 1,049 (16.9%), with 4.79 and
4.88 fields filled a fill; every draw followed a bind. The planner ruled this form (a bind re-finds its
own slot's facts and refills its own fields; only a pipeline change redoes everything; push only the
changed words).

Vulkan, read whole (vkCmdPushConstants, 17.10; Pipeline Layout Compatibility, 17.2.1):
"When a command buffer begins recording, all push constant values are undefined." "Push constant
values can be updated incrementally, causing shader stages in stageFlags to read the new data from
pValues for push constants modified by this command, while still reading the previous data for push
constants not modified by this command." "Binding a pipeline with a layout that is not compatible
with the push constant layout does not disturb the push constant values." "Two pipeline layouts are
defined to be compatible for push constants if they were created with identical push constant
ranges." rt makes one VkPipelineLayout for the device, one push range over every stage, and every
compute and render pipeline uses it, so every bind is compatible and keeps the values; the whole
window is pushed at each VkCommandBuffer's first use (Pushed::restart at each segment's begin) and
only changed words otherwise. VUID-vkCmdDraw-None-08601 (a statically used value must have been set)
holds: every word past what the command buffer holds is pushed.

Tests. tests/refill.rs (device, m2v_cpu_icd and m2v_gpu): 1,200 random calls of one encoder
(pipelines of 30 spilled buffers with two textures and a sampler, of 12 buffers, and of a
fixed-function vertex binding; buffers, offsets, bytes and nothing bound; textures; samplers; draws):
every draw's facts, push bytes and blocks equal a find and fill of every slot, its command buffer
holds its push bytes, and a refused draw is refused alike. And one command buffer: the first draw
pushes the whole window, an offset change and a buffer bound push only the changed words, a pipeline
change that changes no word pushes none, a pass after a dispatch pushes only the words the dispatch
changed, a new command buffer's first draw pushes the whole window; every column reads its bound
values and the dispatch writes its words. tests/command.rs: Pushed's words, marks and restarts
without a device.
This commit is contained in:
Anees Iqbal committed 2026-11-20 00:05:05 -08:00
1 parent ba120c3607
commit 68740984ba
10 files changed
+1256 -214

No files matched your search

+10 -4
View File
@@ -2627,10 +2627,16 @@ or does not check is rebuilt from the generations' names, with young counted ful
plus offsets, the resource IDs of their textures and sampler states, the state's constexpr
sampler indices), binds the vertex buffers its vertex descriptor reads and the index buffer,
and sets the dynamic state that changed since the encoder's last draw: all of it at the first.
A draw or a dispatch whose push bytes the command buffer already holds pushes nothing: the push
stays across pipelines, which share the one layout, so 2,000 draws of unchanged bindings are one
push and 2,000 `vkCmdDraw`s, as Metal's bindings set once stay for the draws after them.
`Counters::metrics`' `pushes` counts each push recorded and `pushes_held` each one skipped.
A bind marks its own slot: the next draw finds that slot's facts (its vertex binding's offset,
its buffer's alignment, whether it reaches a device copy or what the host reads) and fills that
slot's fields alone, writing into the parameter ring only a parameter block one of them is in;
a change of pipeline state finds and fills them all. Push constants belong to the
`VkCommandBuffer`: every pipeline shares the one layout and push range, so a push stays across
pipelines, both bind points and encoders, and a draw or a dispatch pushes only the words the
command buffer does not hold (the whole window at its first, then from the first word that
differs to the last). 2,000 draws of unchanged bindings are one push and 2,000 `vkCmdDraw`s, as
Metal's bindings set once stay for the draws after them. `Counters::metrics`' `pushes` counts
each push recorded, `pushes_held` each one skipped and `push_bytes` the bytes pushed.
A draw takes no barrier, as Metal orders none between the draws of one encoder, so a pass of
any number of draws records the barriers a pass of one does. A draw of no vertices, indices or instances
records nothing.
+84 -21
View File
@@ -20,6 +20,7 @@ use crate::sampler::SamplerState;
use crate::texture::{Image, OverCopy, Texture, TextureInner, TextureObject};
use crate::times::{self, Pair, Times};
use ash::vk;
use std::ops::Range;
use std::sync::atomic::Ordering;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
@@ -177,29 +178,76 @@ pub(crate) struct Building {
presents: Vec<(Texture, vk::Semaphore)>,
}
/// The push constant bytes a command buffer holds, from offset 0, as its pushes left them.
/// The push constant bytes a command buffer holds, from offset 0, as its pushes left them, and a
/// mark of them.
///
/// Every pipeline, compute and graphics, has the device's one layout and its one push range of
/// [`PUSH_STAGES`](crate::pipeline::PUSH_STAGES), so a push stays across pipeline binds and both
/// bind points until the next one: a dispatch or a draw whose push bytes are already there
/// records none, as a Metal argument set once stays bound for the commands after it.
/// [`PUSH_STAGES`](crate::pipeline::PUSH_STAGES), so every pipeline bind is compatible for push
/// constants and keeps them, and a push stays for both bind points until the next one: a
/// dispatch's push changes what a later draw of the command buffer reads, and a draw's what a
/// later dispatch reads. The bytes are of the command buffer, not of an encoder: every push its
/// encoders record goes through [`Building::push_words`], which records only the words that
/// change, as a Metal argument set once stays bound for the commands after it. A new
/// `VkCommandBuffer` holds none: its push constants are undefined until a push sets them.
#[derive(Default)]
pub(crate) struct Pushed {
bytes: Vec<u8>,
/// Moves at each push and at each new `VkCommandBuffer`: an encoder whose own last push left
/// this mark knows the command buffer holds what it pushed.
mark: u64,
}
impl Pushed {
/// Whether `push`, written from offset 0, changes the bytes held; they are `push` from now,
/// with the held bytes past its end kept.
pub(crate) fn needed(&mut self, push: &[u8]) -> bool {
if self.bytes.get(..push.len()) == Some(push) {
return false;
/// A new `VkCommandBuffer`'s: no byte held, and a new mark.
pub(crate) fn restart(&mut self) {
self.bytes.clear();
self.mark += 1;
}
/// The bytes of `push`, written from offset 0, that a push records so that the command buffer
/// holds `push`: from the first word that differs from the bytes held to the last, and every
/// word past the bytes held, which no push has set; None where it holds them all. Where `mark`
/// is the mark the caller's own last push left, only the words in `span` (word-aligned bytes)
/// can differ, and only they are compared; otherwise every word is. The bytes held are `push`
/// from now, those past its end kept, and `mark` is the mark they leave.
pub(crate) fn changed(
&mut self,
push: &[u8],
span: Range<usize>,
mark: &mut u64,
) -> Option<Range<usize>> {
let span = match *mark == self.mark {
true => span,
false => 0..push.len(),
};
let held = self.bytes.len().min(push.len());
let (first, end) = {
let words = (span.start..span.end.min(held)).step_by(4);
let differs = |at: &usize| push[*at..*at + 4] != self.bytes[*at..*at + 4];
let first = words.clone().find(differs).unwrap_or(held);
let end = match push.len() > held {
true => push.len(),
false => words.rev().find(differs).map_or(0, |at| at + 4),
};
(first, end)
};
if first >= end {
*mark = self.mark;
return None;
}
if self.bytes.len() < push.len() {
self.bytes.resize(push.len(), 0);
}
self.bytes[..push.len()].copy_from_slice(push);
true
self.bytes[first..end].copy_from_slice(&push[first..end]);
self.mark += 1;
*mark = self.mark;
Some(first..end)
}
/// The bytes held.
#[cfg(test)]
pub(crate) fn bytes(&self) -> &[u8] {
&self.bytes
}
}
@@ -906,7 +954,7 @@ impl Building {
self.last().command = Some(command);
self.bound = None;
self.drawn = None;
self.pushed = Pushed::default();
self.pushed.restart();
self.vertex.clear();
Ok(command)
}
@@ -1147,15 +1195,30 @@ impl Building {
}
}
/// Whether `push`, the push bytes of a dispatch or a draw from offset 0, needs recording in
/// the current command buffer: its push bytes do not already begin with it. They do from now.
pub(crate) fn push_needed(&mut self, push: &[u8]) -> bool {
let needed = self.pushed.needed(push);
self.tally.count(match needed {
true => Metric::Pushes,
false => Metric::PushesHeld,
});
needed
/// The bytes of `push`, the push bytes of a dispatch or a draw from offset 0, that the current
/// command buffer needs pushed so that it holds them ([`Pushed::changed`], of `span` and
/// `mark`); it holds them from now.
pub(crate) fn push_words(
&mut self,
push: &[u8],
span: Range<usize>,
mark: &mut u64,
) -> Option<Range<usize>> {
let words = self.pushed.changed(push, span, mark);
match &words {
Some(words) => {
self.tally.count(Metric::Pushes);
self.tally.count_some(Metric::PushBytes, words.len() as u64);
}
None => self.tally.count(Metric::PushesHeld),
}
words
}
/// The push bytes the current command buffer holds.
#[cfg(test)]
pub(crate) fn pushed(&self) -> &[u8] {
self.pushed.bytes()
}
/// Counts one more of `metric`, added to the device's counters once the encoder ends.
+16 -1
View File
@@ -109,6 +109,8 @@ pub(crate) enum Metric {
Pushes,
/// [`Metrics::pushes_held`].
PushesHeld,
/// [`Metrics::push_bytes`].
PushBytes,
/// [`Metrics::upload_waits`].
UploadWaits,
/// [`Metrics::staging_sleeps`].
@@ -163,6 +165,7 @@ const METRIC_ORDER: [Metric; METRICS] = [
Metric::RingWrites,
Metric::Pushes,
Metric::PushesHeld,
Metric::PushBytes,
Metric::UploadWaits,
Metric::StagingSleeps,
Metric::Synchronizations,
@@ -207,7 +210,12 @@ const _: () = assert!(METRICS <= u32::BITS as usize);
impl Tally {
/// Counts one more of `metric`.
pub(crate) fn count(&mut self, metric: Metric) {
self.counts[metric as usize] += 1;
self.count_some(metric, 1);
}
/// Counts `count` more of `metric`.
pub(crate) fn count_some(&mut self, metric: Metric, count: u64) {
self.counts[metric as usize] += count;
self.counted |= 1 << metric as usize;
}
}
@@ -383,6 +391,7 @@ struct Atomics {
ring_writes: AtomicU64,
pushes: AtomicU64,
pushes_held: AtomicU64,
push_bytes: AtomicU64,
upload_waits: AtomicU64,
staging_sleeps: AtomicU64,
synchronizations: AtomicU64,
@@ -527,6 +536,7 @@ impl Counters {
Metric::RingWrites => &a.ring_writes,
Metric::Pushes => &a.pushes,
Metric::PushesHeld => &a.pushes_held,
Metric::PushBytes => &a.push_bytes,
Metric::UploadWaits => &a.upload_waits,
Metric::StagingSleeps => &a.staging_sleeps,
Metric::Synchronizations => &a.synchronizations,
@@ -1041,6 +1051,7 @@ impl Counters {
ring_writes: a.ring_writes.load(Relaxed),
pushes: a.pushes.load(Relaxed),
pushes_held: a.pushes_held.load(Relaxed),
push_bytes: a.push_bytes.load(Relaxed),
upload_waits: a.upload_waits.load(Relaxed),
staging_sleeps: a.staging_sleeps.load(Relaxed),
synchronizations: a.synchronizations.load(Relaxed),
@@ -1395,6 +1406,10 @@ pub struct Metrics {
/// push: every pipeline shares the device's one layout and push range, so a push stays for the
/// draws and dispatches after it.
pub pushes_held: u64,
/// The bytes those pushes recorded: of a draw's or a dispatch's push bytes, from the first word
/// the command buffer did not hold to the last, and every word past the bytes it held, which
/// are undefined at a command buffer's start (`vkCmdPushConstants`).
pub push_bytes: u64,
/// Calls that waited for an upload to complete before they recorded: the upload at its
/// bound of calls or bytes, or the staging region with no room for a copy.
pub upload_waits: u64,
+11 -2
View File
@@ -1524,8 +1524,17 @@ impl Building {
if self.bind(pipeline) {
device.cmd_bind_pipeline(command, vk::PipelineBindPoint::COMPUTE, pipeline);
}
if !push.is_empty() && self.push_needed(push) {
device.cmd_push_constants(command, core.layout, PUSH_STAGES, 0, push);
// Every word of the window compared with what the command buffer holds, whoever
// pushed it: the words that differ are pushed.
let words = match push.is_empty() {
true => None,
false => self.push_words(push, 0..push.len(), &mut u64::MAX),
};
if let Some(words) = words {
// Word-aligned: each field is at a multiple of its size, 4 bytes or more, and the
// window ends at a multiple of 4.
let offset = words.start as u32;
device.cmd_push_constants(command, core.layout, PUSH_STAGES, offset, &push[words]);
}
match *launch {
Launch::Direct(groups) => {
+496 -175
View File
@@ -102,6 +102,7 @@ use metal2vulkan::metal::{
CullMode, DepthClipMode, IndexType, PrimitiveType, TriangleFillMode, Winding,
};
use metal2vulkan::pipeline::PrecisionNote;
use std::ops::Range;
use std::sync::Arc;
/// `MTLViewport`: an origin and size in pixels, and a depth range.
@@ -218,12 +219,13 @@ struct Shadowed {
cleared: Option<vk::ClearColorValue>,
}
/// What a draw of the encoder's pipeline state reaches of its bound resources, worked out at the
/// first draw after either changes and kept until the next change: the vertex buffers it binds,
/// and whether it reads an attachment of its pass through a texture, reaches a Managed buffer's
/// device copy or a texture over one, or writes memory the host may read. A draw after no change
/// runs none of the scans; one after a change checks its vertex buffers' offsets and its buffers'
/// alignments again.
/// What a draw of the encoder's pipeline state reaches of its bound resources, kept from draw to
/// draw: the vertex buffers it binds, and per function the slots whose objects make it read an
/// attachment of its pass through a texture, reach a Managed buffer's device copy or a texture
/// over one, or write memory the host may read. A draw after no change runs none of the scans. One
/// after binds finds again the facts of the slots bound since ([`Rebound`]), checking their vertex
/// buffers' offsets and their buffers' alignments, and keeps every other slot's; one after a
/// change of the pipeline state finds them all.
///
/// A change is the encoder's own call: a pipeline state set, or a buffer, an offset, bytes or a
/// texture bound. Nothing outside the encoder changes what a fact holds: each is of the objects
@@ -237,30 +239,162 @@ struct Facts {
held: bool,
/// The fixed-function vertex buffers the vertex descriptor reads: binding, buffer, offset.
vertex: Vec<(u32, vk::Buffer, u64)>,
/// A texture the draw reads is of an image the pass renders, or the fragment function reads
/// a colour attachment (`Draws::fetched`).
attachments: bool,
/// A buffer the draw reaches has a device copy, or a texture it writes is over one.
managed: bool,
/// A write the host may read once the command buffer completes: to a Shared buffer or a
/// texture over one, or through an address outside the draw's resources.
host: bool,
/// The nil buffer's address where a buffer argument the draw reaches is bound to nothing
/// (`Ring::nil`), else 0, and the zero range's where the draw checks a load (`Ring::zero`),
/// else 0.
/// Per function, the texture slots the draw reads whose texture is of an image the pass
/// renders.
attached: [u128; 2],
/// The slots of a buffer the draw reaches that has a device copy, and of a texture it writes
/// that is over one.
managed: Slots,
/// The slots of a Shared buffer the draw writes, and of a texture it writes that the host
/// reads (one over a Shared buffer).
host: Slots,
/// The nil buffer's address once a buffer argument the draw reaches was bound to nothing
/// since the pipeline state was set (`Ring::nil`), else 0, and the zero range's where the draw
/// checks a load (`Ring::zero`), else 0.
nil: (u64, u64),
}
/// Per function, a bit per buffer slot and one per texture slot.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
struct Slots {
buffers: [u32; 2],
textures: [u128; 2],
}
impl Slots {
fn any(&self) -> bool {
*self != Slots::default()
}
/// Clears the bits of the slots `rebound` names.
fn forget(&mut self, rebound: &Rebound) {
for table in [VERTEX, FRAGMENT] {
self.buffers[table] &= !rebound.buffer_bits(table);
self.textures[table] &= !rebound.texture_bits(table);
}
}
}
/// What the next draw finds and fills again of its facts and fields: every one after a change of
/// the pipeline state; otherwise, per function, the buffer, texture and sampler slots bound since
/// the last draw filled its fields, the tessellation factor buffer and the alpha test reference
/// where they changed, and the texture slots whose element changed with the pass's moves to the
/// feedback layout or with the shadows the draw reads. A draw fills those fields alone and writes
/// into the ring only the parameter blocks they are in.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
struct Rebound {
all: bool,
buffers: [u32; 2],
textures: [u128; 2],
samplers: [u16; 2],
factors: bool,
alpha_test: bool,
}
impl Rebound {
/// Every fact and field: the pipeline state changed.
const ALL: Rebound = Rebound {
all: true,
buffers: [0; 2],
textures: [0; 2],
samplers: [0; 2],
factors: false,
alpha_test: false,
};
/// Function `table`'s buffer slots it names, a bit each.
fn buffer_bits(&self, table: usize) -> u32 {
match self.all {
true => u32::MAX,
false => self.buffers[table],
}
}
/// Function `table`'s texture slots it names, a bit each.
fn texture_bits(&self, table: usize) -> u128 {
match self.all {
true => u128::MAX,
false => self.textures[table],
}
}
fn buffer(&self, table: usize, slot: u32) -> bool {
self.all || (self.buffers[table].checked_shr(slot)).is_some_and(|bits| bits & 1 != 0)
}
fn texture(&self, table: usize, slot: u32) -> bool {
self.all || (self.textures[table].checked_shr(slot)).is_some_and(|bits| bits & 1 != 0)
}
fn sampler(&self, table: usize, slot: u32) -> bool {
self.all || (self.samplers[table].checked_shr(slot)).is_some_and(|bits| bits & 1 != 0)
}
/// Whether a draw fills `value`, a field of function `table`'s, again: a field of a slot, the
/// factor buffer or the alpha test reference where it names them, and one of the pipeline
/// state and the pass alone only after a change of the state.
fn field(&self, table: usize, value: FieldValue) -> bool {
match value {
FieldValue::BufferAddress { slot, .. } | FieldValue::BufferBounds(slot) => {
self.buffer(table, slot)
}
FieldValue::TextureId(slot) | FieldValue::IntegerChannels(slot) => {
self.texture(table, slot)
}
FieldValue::SamplerId(slot) => self.sampler(table, slot),
FieldValue::TessellationFactors => self.all || self.factors,
FieldValue::AlphaTestReference => self.all || self.alpha_test,
FieldValue::ZeroAddress
| FieldValue::ConstexprSampler(_)
| FieldValue::Word(_)
| FieldValue::FetchedColor(_)
| FieldValue::DispatchRegion
| FieldValue::StageInRegion => self.all,
}
}
}
impl Facts {
/// The facts of a draw of `draws` with `tables` bound in `pass`, but the alignments, which the
/// draw checks after its attachment reads.
/// A texture the draw reads is of an image the pass renders, or the fragment function of
/// `draws` reads a colour attachment (`Draws::fetched`).
fn attachments(&self, draws: &Draws) -> bool {
!draws.fetched.is_empty() || self.attached != [0; 2]
}
/// A buffer the draw reaches has a device copy, or a texture it writes is over one.
fn managed(&self) -> bool {
self.managed.any()
}
/// A write the host may read once the command buffer completes: to a Shared buffer or a
/// texture over one, or through an address outside the resources of a draw of `draws`.
fn host(&self, draws: &Draws) -> bool {
draws.writes_unbound || self.host.any()
}
/// The facts of a draw of `draws` with `tables` bound in `pass`, found again for the slots
/// `rebound` names and kept for the others, but the alignments
/// ([`align`](Self::align)), which the draw checks after its attachment reads. Each slot's
/// facts are of its object alone, so a slot not bound again holds what it held, and the
/// first refusal in the order below is the one a find of every slot meets: every other slot
/// met none when it was found.
///
/// Err: [`Refusal::VertexBufferOffset`]; [`Refusal::NoBufferAtIndex`] for a vertex buffer the
/// vertex descriptor reads that is not bound; [`Gap::SwizzledReadWrite`];
/// [`Gap::StorageElement`].
fn find(&mut self, draws: &Draws, tables: &[Tables; 2], pass: &Pass) -> Result<(), Error> {
self.vertex.clear();
for &(binding, index) in &draws.bindings {
fn find(
&mut self,
draws: &Draws,
tables: &[Tables; 2],
pass: &Pass,
rebound: &Rebound,
) -> Result<(), Error> {
// A change of the pipeline state finds every binding of its own.
(self.vertex).resize(draws.bindings.len(), (0, vk::Buffer::null(), 0));
for (found, &(binding, index)) in self.vertex.iter_mut().zip(&draws.bindings) {
if !rebound.buffer(VERTEX, index) {
continue;
}
let (buffer, offset) = match tables[VERTEX].buffers.get(index as usize) {
Some(Bound::Buffer { buffer, offset }) => {
if *offset >= buffer.length() {
@@ -278,52 +412,108 @@ impl Facts {
return Err(Error::Refused(Refusal::NoBufferAtIndex { index }))
}
};
self.vertex.push((binding, buffer, offset));
*found = (binding, buffer, offset);
}
for &(table, slot) in &draws.storage_reads {
if tables[table].texture(slot).is_some_and(|t| t.swizzled()) {
let swizzled = || tables[table].texture(slot).is_some_and(|t| t.swizzled());
if rebound.texture(table, slot) && swizzled() {
return Err(Error::Unsupported(Gap::SwizzledReadWrite { slot }));
}
}
for table in [VERTEX, FRAGMENT] {
self.attached[table] &= !rebound.texture_bits(table);
}
self.managed.forget(rebound);
self.host.forget(rebound);
for &(table, slot, access) in &draws.textures {
let read = draws.storage_reads.contains(&(table, slot));
let stored = access != Access::Read || read;
let unstored = match tables[table].texture(slot) {
Some(texture) if stored => texture
.unstored()
.or_else(|| texture.unread().filter(|_| read)),
_ => None,
if !rebound.texture(table, slot) {
continue;
}
let Some(texture) = tables[table].texture(slot) else {
continue;
};
if let Some(pixel_format) = unstored {
return Err(Error::Unsupported(Gap::StorageElement {
slot: Some(slot),
pixel_format,
}));
let read = draws.storage_reads.contains(&(table, slot));
if access != Access::Read || read {
let unstored = (texture.unstored()).or_else(|| texture.unread().filter(|_| read));
if let Some(pixel_format) = unstored {
return Err(Error::Unsupported(Gap::StorageElement {
slot: Some(slot),
pixel_format,
}));
}
}
// A slot holds a texture only below `TEXTURE_SLOTS`, 128.
let bit = 1u128 << slot;
let hazard = texture.hazard_id();
if pass.targets().any(|t| t.texture.hazard_id() == hazard) {
self.attached[table] |= bit;
}
if access.writes() {
if texture.managed_over().is_some() {
self.managed.textures[table] |= bit;
}
if texture.host_reads() {
self.host.textures[table] |= bit;
}
}
}
self.attachments = !draws.fetched.is_empty()
|| (draws.textures.iter()).any(|&(table, slot, _)| {
tables[table].texture(slot).is_some_and(|texture| {
let hazard = texture.hazard_id();
pass.targets().any(|t| t.texture.hazard_id() == hazard)
})
});
let copied = |buffer: &Arc<BufferInner>| buffer.held().1.is_some();
self.managed = (draws.buffers.iter())
.any(|&(table, slot, _)| tables[table].buffer(slot).is_some_and(copied))
|| (draws.bindings.iter())
.any(|&(_, index)| tables[VERTEX].buffer(index).is_some_and(copied))
|| (draws.textures.iter()).any(|&(table, slot, access)| {
access.writes()
&& (tables[table].texture(slot)).is_some_and(|t| t.managed_over().is_some())
});
self.host = draws.writes_unbound
|| (draws.buffers.iter()).any(|&(table, slot, access)| {
access.writes() && tables[table].buffer(slot).is_some_and(|b| b.is_shared())
})
|| (draws.textures.iter()).any(|&(table, slot, access)| {
access.writes() && tables[table].texture(slot).is_some_and(|t| t.host_reads())
});
// A slot holds a buffer only below `BUFFER_SLOTS`, 31.
for &(table, slot, access) in &draws.buffers {
if !rebound.buffer(table, slot) {
continue;
}
if let Some(buffer) = tables[table].buffer(slot) {
if copied(buffer) {
self.managed.buffers[table] |= 1 << slot;
}
if access.writes() && buffer.is_shared() {
self.host.buffers[table] |= 1 << slot;
}
}
}
for &(_, index) in &draws.bindings {
let reached = || tables[VERTEX].buffer(index).is_some_and(copied);
if rebound.buffer(VERTEX, index) && reached() {
self.managed.buffers[VERTEX] |= 1 << index;
}
}
Ok(())
}
/// The alignments of the buffers bound at the slots `rebound` names that a field of `draws`
/// reaches by address ([`check_alignment`]), with `tables` bound, and the nil buffer's address
/// where such a slot is bound to nothing and the zero range's where a field checks a load,
/// made on `core` where none is yet. The first refusal is the one a check of every slot
/// meets, as in [`find`](Self::find).
///
/// Err: [`Refusal::BufferOffsetAlignment`]; [`Error::Vulkan`] where the nil buffer or the
/// zero range cannot be made.
fn align(
&mut self,
core: &Core,
draws: &Draws,
tables: &[Tables; 2],
rebound: &Rebound,
) -> Result<(), Error> {
if rebound.all {
self.nil = (0, 0);
}
for &(_, table, value) in &draws.fields {
match value {
FieldValue::BufferAddress { slot, mask } if rebound.buffer(table, slot) => {
match tables[table].buffers.get(slot as usize) {
Some(Bound::Buffer { buffer, offset }) => {
check_alignment(slot, mask, buffer, *offset)?
}
Some(Bound::Bytes(..)) => {}
Some(Bound::Empty) | None => self.nil.0 = core.ring.nil(core)?,
}
}
FieldValue::ZeroAddress if rebound.all => self.nil.1 = core.ring.zero(core)?,
_ => {}
}
}
Ok(())
}
}
@@ -521,9 +711,13 @@ pub struct RenderCommandEncoder {
push: Vec<u8>,
/// The parameter blocks of the last draw's functions, where their fields spill.
blocks: [Vec<u8>; 2],
/// The push bytes are those of the bound pipeline state and resources, and of the images the
/// pass moved and the shadows the last draw read: the next draw pushes them as they are.
push_filled: bool,
/// What changed since the last draw filled its fields, which the next draw finds and fills
/// again.
rebound: Rebound,
/// The mark the encoder's last push left in its command buffer's push bytes (`Pushed`): while
/// they hold it, no other push came between, and they hold `push` but the words a fill wrote
/// since. `u64::MAX`, which no push leaves, before its first.
push_mark: u64,
}
impl CommandBuffer {
@@ -593,7 +787,8 @@ impl CommandBuffer {
facts: Facts::default(),
push: Vec::new(),
blocks: [Vec::new(), Vec::new()],
push_filled: false,
rebound: Rebound::ALL,
push_mark: u64::MAX,
pass,
})
}
@@ -691,11 +886,18 @@ impl RenderCommandEncoder {
.expect("an encoder holds its command buffer's recording until it ends")
}
/// The pipeline state or a binding changed: the next draw finds its facts and fills its push
/// bytes again.
fn changed(&mut self) {
/// Buffer slot `slot` of function `table` holds another binding: the next draw finds its facts
/// and fills its fields again.
fn rebound_buffer(&mut self, table: usize, slot: usize) {
self.rebound.buffers[table] |= 1 << slot;
self.facts.held = false;
}
/// Texture slot `slot` of function `table` holds another texture, as
/// [`rebound_buffer`](Self::rebound_buffer).
fn rebound_texture(&mut self, table: usize, slot: u32) {
self.rebound.textures[table] |= 1 << slot;
self.facts.held = false;
self.push_filled = false;
}
/// `setRenderPipelineState:`. The command buffer keeps the state until it retires.
@@ -711,7 +913,8 @@ impl RenderCommandEncoder {
self.renders_into = state.inner.compiled.renders_into(&self.pass);
// SAFETY: the encoder holds the borrow, and it ends before its command buffer commits.
self.pipeline = Some(unsafe { self.building().lend_render_pipeline(state) });
self.changed();
self.rebound = Rebound::ALL;
self.facts.held = false;
Ok(())
}
@@ -777,7 +980,7 @@ impl RenderCommandEncoder {
None => Bound::Empty,
};
self.tables[table].buffers[slot] = bound;
self.changed();
self.rebound_buffer(table, slot);
Ok(())
}
@@ -797,10 +1000,11 @@ impl RenderCommandEncoder {
}
fn set_buffer_offset(&mut self, table: usize, offset: u64, index: u32) -> Result<(), Error> {
match &mut self.tables[table].buffers[slot(index)?] {
let slot = slot(index)?;
match &mut self.tables[table].buffers[slot] {
Bound::Buffer { offset: bound, .. } => {
*bound = offset;
self.changed();
self.rebound_buffer(table, slot);
Ok(())
}
_ => Err(Error::Refused(Refusal::NoBufferAtIndex { index })),
@@ -838,7 +1042,7 @@ impl RenderCommandEncoder {
let placed = self.building().write_ring_placed(bytes)?;
// At most one chunk, 64 KiB.
self.tables[table].buffers[slot] = Bound::Bytes(placed, bytes.len() as u32);
self.changed();
self.rebound_buffer(table, slot);
Ok(())
}
@@ -895,7 +1099,7 @@ impl RenderCommandEncoder {
None => None,
};
self.tables[table].textures[index as usize] = lent;
self.changed();
self.rebound_texture(table, index);
Ok(())
}
@@ -990,7 +1194,8 @@ impl RenderCommandEncoder {
None => None,
};
self.tables[table].samplers[index as usize] = lent;
self.push_filled = false;
// A sampler state is a field alone: the facts are of buffers and textures.
self.rebound.samplers[table] |= 1 << index;
Ok(())
}
@@ -1121,7 +1326,7 @@ impl RenderCommandEncoder {
let code = alpha_test_code(value);
if code != self.alpha_test {
self.alpha_test = code;
self.push_filled = false;
self.rebound.alpha_test = true;
}
}
@@ -1339,7 +1544,8 @@ impl RenderCommandEncoder {
}
}
self.moved.extend(moves.into_iter().map(|m| m.moved));
self.push_filled = false;
// A texture of a moved image reads through its second element from now.
self.rebound.textures = [u128::MAX; 2];
(self.drew, self.owed) = (false, false);
self.interrupt(|building, core| {
let command = building.ordered_command()?;
@@ -1642,7 +1848,8 @@ impl RenderCommandEncoder {
None => None,
};
self.factors = factors;
self.changed();
// A field alone: no fact is of the factor buffer.
self.rebound.factors = true;
Ok(())
}
@@ -1750,7 +1957,8 @@ impl RenderCommandEncoder {
}
};
if !self.facts.held {
self.facts.find(draws, &self.tables, &self.pass)?;
self.facts
.find(draws, &self.tables, &self.pass, &self.rebound)?;
}
// Metal orders a colour attachment's read (`[[color(n)]]`) after every earlier fragment of
// the pass, with no barrier from the program: after a draw of the pass, a draw that reads
@@ -1766,30 +1974,15 @@ impl RenderCommandEncoder {
shadowed.held.clear();
}
}
let reads = match self.facts.attachments {
let reads = match self.facts.attachments(draws) {
true => Some(self.attachment_reads(draws)?),
false => None,
};
if !self.facts.held {
// A buffer argument bound to nothing reads the nil buffer (`Ring::nil`), and a checked
// load outside its buffer the zero range (`Ring::zero`).
let (mut nil, mut zero) = (0, 0);
for &(_, table, value) in &draws.fields {
match value {
FieldValue::BufferAddress { slot, mask } => {
match self.tables[table].buffers.get(slot as usize) {
Some(Bound::Buffer { buffer, offset }) => {
check_alignment(slot, mask, buffer, *offset)?
}
Some(Bound::Bytes(..)) => {}
Some(Bound::Empty) | None => nil = self.core.ring.nil(&self.core)?,
}
}
FieldValue::ZeroAddress => zero = self.core.ring.zero(&self.core)?,
_ => {}
}
}
self.facts.nil = (nil, zero);
let core = &*self.core;
(self.facts).align(core, draws, &self.tables, &self.rebound)?;
self.facts.held = true;
}
let count = match call {
@@ -1813,6 +2006,7 @@ impl RenderCommandEncoder {
let pipeline = compiled.pipeline(topology)?;
let discards = compiled.discards();
let writes_memory = draws.writes_memory;
let host = self.facts.host(draws);
let building = (self.building.as_ref())
.expect("an encoder holds its command buffer's recording until it ends");
// What a draw reaches that each draw looks at again: an attachment of its pass through a
@@ -1822,17 +2016,14 @@ impl RenderCommandEncoder {
// A patch draw's factor buffer is its read as an index buffer is an indexed draw's.
let factors = (self.factors.as_ref()).filter(|_| patches);
let each = reads.is_some()
|| self.facts.managed
|| self.facts.managed()
|| index_buffer.is_some_and(|buffer| buffer.managed_overs().is_some())
|| factors.is_some_and(|(buffer, _)| buffer.managed_overs().is_some())
|| building.copies_over();
match each {
true => self.draw_reaches(reads, index_buffer)?,
false => {
if !self.shadow_slots.is_empty() {
self.shadow_slots.clear();
self.push_filled = false;
}
self.read_shadows(Vec::new());
self.loop_reads(false);
(self.building.as_mut())
.expect("an encoder holds its command buffer's recording until it ends")
@@ -1841,36 +2032,50 @@ impl RenderCommandEncoder {
}
let building = (self.building.as_mut())
.expect("an encoder holds its command buffer's recording until it ends");
if self.facts.host {
// The fields that changed since the last draw, every one after a change of the pipeline
// state; filled before anything of the draw is recorded, so a ring that cannot grow
// leaves the recording as it was, and the next draw fills them again. `written` is the
// push bytes they changed.
let mut written = 0..0;
if self.rebound != Rebound::default() {
if let Some(state) = &self.pipeline {
let factors = (self.factors.as_ref()).map_or(0, |(buffer, offset)| {
buffer.gpu_address().wrapping_add(*offset)
});
let filled;
(written, filled) = fill_push(
(&mut self.push, &mut self.blocks),
(&self.tables, self.facts.nil, factors, self.alpha_test),
(&self.moved, &self.shadow_slots, &self.pass),
state,
&self.rebound,
);
// Each spilled function's block whose fields changed into the ring, and its new
// address into the range: the GPU may still read the last one.
let made = &state.inner.compiled.draws.blocks;
for ((block, made), filled) in self.blocks.iter().zip(made).zip(filled) {
if let (Some((_, at)), true) = (*made, filled) {
let address = building.write_ring(block)?;
let at = at as usize;
self.push[at..at + 8].copy_from_slice(&address.to_le_bytes());
written = cover(written, at..at + 8);
}
}
}
self.rebound = Rebound::default();
}
if host {
building.wrote_host();
}
self.wrote |= writes_memory;
(self.drew, self.pass_drew) = (true, true);
let (bind, first) = building.bind_graphics(pipeline);
if !self.push_filled {
if let Some(state) = &self.pipeline {
let factors = (self.factors.as_ref()).map_or(0, |(buffer, offset)| {
buffer.gpu_address().wrapping_add(*offset)
});
fill_push(
(&mut self.push, &mut self.blocks),
(&self.tables, self.facts.nil, factors, self.alpha_test),
(&self.moved, &self.shadow_slots, &self.pass),
state,
);
// Each spilled function's block into the ring, and its address into the range.
let made = &state.inner.compiled.draws.blocks;
for (block, made) in self.blocks.iter().zip(made) {
if let Some((_, at)) = *made {
let address = building.write_ring(block)?;
let at = at as usize;
self.push[at..at + 8].copy_from_slice(&address.to_le_bytes());
}
}
}
self.push_filled = true;
}
let push = !self.push.is_empty() && building.push_needed(&self.push);
// The words the command buffer does not hold: every one at its first use, else those the
// fill changed (`Pushed`).
let words = match self.push.is_empty() {
true => None,
false => building.push_words(&self.push, written, &mut self.push_mark),
};
let core = &*self.core;
let command = self.command;
// SAFETY: the command buffer is inside the pass's rendering, which the pipeline renders
@@ -1912,8 +2117,17 @@ impl RenderCommandEncoder {
device.cmd_bind_vertex_buffers(command, binding, &[buffer], &[offset]);
}
}
if push {
device.cmd_push_constants(command, core.layout, PUSH_STAGES, 0, &self.push);
if let Some(words) = words {
// Word-aligned: the push bytes' fields are of 4 and 8 bytes, at multiples of
// their size, and the window ends at a multiple of 4.
let offset = words.start as u32;
device.cmd_push_constants(
command,
core.layout,
PUSH_STAGES,
offset,
&self.push[words],
);
}
match (call, index) {
(
@@ -2126,8 +2340,7 @@ impl RenderCommandEncoder {
if !found.shadow_reads.is_empty() {
self.shadow_copies(&found.shadow_reads)?;
}
self.shadow_slots = found.shadow_slots;
self.push_filled = false;
self.read_shadows(found.shadow_slots);
if found.reads {
(self.building.as_mut())
.expect("an encoder holds its command buffer's recording until it ends")
@@ -2136,10 +2349,7 @@ impl RenderCommandEncoder {
found.reads
}
None => {
if !self.shadow_slots.is_empty() {
self.shadow_slots.clear();
self.push_filled = false;
}
self.read_shadows(Vec::new());
false
}
};
@@ -2212,6 +2422,18 @@ impl RenderCommandEncoder {
Ok(())
}
/// Holds `slots` as the texture slots that read a shadow in the draw being recorded: where
/// they change, the fields of the slots that join or leave them, whose element changes, are
/// filled again.
fn read_shadows(&mut self, slots: Vec<(usize, u32)>) {
if slots != self.shadow_slots {
for &(table, slot) in self.shadow_slots.iter().chain(&slots) {
self.rebound.textures[table] |= 1 << slot;
}
self.shadow_slots = slots;
}
}
/// Sets the feedback loop's aspects for a draw that reads an attachment (`reads`) or none,
/// where the device reads attachments through it: dirty where they change.
fn loop_reads(&mut self, reads: bool) {
@@ -2457,6 +2679,84 @@ impl Drop for RenderCommandEncoder {
}
}
/// What a draw's facts and fields hold: the vertex buffers it binds, whether it reads an
/// attachment, reaches a device copy and writes what the host reads, its push bytes with each
/// parameter block's address zeroed, and its blocks.
#[cfg(test)]
#[derive(Debug, PartialEq)]
pub(crate) struct Filled {
vertex: Vec<(u32, vk::Buffer, u64)>,
facts: [bool; 3],
push: Vec<u8>,
blocks: [Vec<u8>; 2],
}
/// An encoder's facts and fields beside a find and fill of every slot ([`RenderCommandEncoder::refilled`]).
#[cfg(test)]
pub(crate) struct Refilled {
/// The facts and fields the encoder's draws left, found and filled slot by slot since the
/// pipeline state was set.
pub(crate) slot_by_slot: Filled,
/// A find and fill of every slot of what is bound now ([`Rebound::ALL`]), or its refusal's
/// text.
pub(crate) whole: Result<Filled, String>,
/// The push bytes as the encoder holds them.
pub(crate) push: Vec<u8>,
/// The push bytes its command buffer holds.
pub(crate) held: Vec<u8>,
}
#[cfg(test)]
impl RenderCommandEncoder {
/// Its facts and fields beside a find and fill of every slot of what is bound now.
pub(crate) fn refilled(&self) -> Refilled {
let state = self.pipeline.as_ref().expect("a pipeline state set");
let draws = &state.inner.compiled.draws;
let filled = |facts: &Facts, mut push: Vec<u8>, blocks: [Vec<u8>; 2]| {
for &(_, at) in draws.blocks.iter().flatten() {
let at = at as usize;
if let Some(address) = push.get_mut(at..at + 8) {
address.fill(0);
}
}
Filled {
vertex: facts.vertex.clone(),
facts: [facts.attachments(draws), facts.managed(), facts.host(draws)],
push,
blocks,
}
};
let mut facts = Facts::default();
let whole = (facts.find(draws, &self.tables, &self.pass, &Rebound::ALL))
.and_then(|()| facts.align(&self.core, draws, &self.tables, &Rebound::ALL))
.map(|()| {
let (mut push, mut blocks) = (Vec::new(), [Vec::new(), Vec::new()]);
let factors = (self.factors.as_ref()).map_or(0, |(buffer, offset)| {
buffer.gpu_address().wrapping_add(*offset)
});
fill_push(
(&mut push, &mut blocks),
(&self.tables, facts.nil, factors, self.alpha_test),
(&self.moved, &self.shadow_slots, &self.pass),
state,
&Rebound::ALL,
);
filled(&facts, push, blocks)
})
.map_err(|error| format!("{error:?}"));
let held = (self.building.as_ref())
.expect("an encoder holds its command buffer's recording until it ends")
.pushed()
.to_vec();
Refilled {
slot_by_slot: filled(&self.facts, self.push.clone(), self.blocks.clone()),
whole,
push: self.push.clone(),
held,
}
}
}
/// The topology of a draw of `primitive_type`, and whether it restarts strips.
///
/// Err: [`Gap::Draw`] of [`DrawKind::Points`].
@@ -2471,44 +2771,47 @@ fn primitives(primitive_type: PrimitiveType) -> Result<(vk::PrimitiveTopology, b
Ok((topology, restart))
}
/// Fills `push`, the push bytes of a draw of `state`, and `blocks`, each function's parameter
/// block where its fields spill (`Draws::blocks`; their addresses the caller writes once they are
/// in the ring), from the `tables`, a buffer argument bound to nothing taking `nil`, the nil
/// buffer's address, and bounds of 0 and 0, a checked load's zero range at `zero`: a texture whose
/// image the pass `moved` to the feedback layout reads through its second element in that layout,
/// and one in `shadow_slots`, which reads a shadow, through its second element, the shadow's; a
/// colour attachment of `pass` the fragment function reads is read through its texture's second
/// element.
/// Fills, of `push`, the push bytes of a draw of `state`, and of `blocks`, each function's
/// parameter block where its fields spill (`Draws::blocks`; their addresses the caller writes once
/// they are in the ring), the fields `rebound` names: every field, into bytes sized afresh, after
/// a change of the pipeline state. Each is from the `tables`, a buffer argument bound to nothing
/// taking `nil`, the nil buffer's address, and bounds of 0 and 0, a checked load's zero range at
/// `zero`: a texture whose image the pass `moved` to the feedback layout reads through its second
/// element in that layout, and one in `shadow_slots`, which reads a shadow, through its second
/// element, the shadow's; a colour attachment of `pass` the fragment function reads is read
/// through its texture's second element. Returns the push bytes it wrote, from the first to the
/// end of the last, and each block it wrote a field of (every block after a change of the state).
fn fill_push(
(push, blocks): (&mut Vec<u8>, &mut [Vec<u8>; 2]),
(tables, (nil, zero), factors, alpha_test): (&[Tables; 2], (u64, u64), u64, u32),
(moved, shadow_slots, pass): (&[Moved], &[(usize, u32)], &Pass),
state: &RenderPipelineState,
) {
rebound: &Rebound,
) -> (Range<usize>, [bool; 2]) {
let draws = &state.inner.compiled.draws;
let ids = &state.inner.numbered.ids;
push.clear();
push.resize(draws.push_len.next_multiple_of(4) as usize, 0);
for (block, made) in blocks.iter_mut().zip(&draws.blocks) {
block.clear();
block.resize(made.map_or(0, |(len, _)| len as usize), 0);
let (mut written, mut filled) = (0..0, [false; 2]);
if rebound.all {
push.clear();
push.resize(draws.push_len.next_multiple_of(4) as usize, 0);
for (block, made) in blocks.iter_mut().zip(&draws.blocks) {
block.clear();
block.resize(made.map_or(0, |(len, _)| len as usize), 0);
}
written = 0..push.len();
filled = draws.blocks.map(|made| made.is_some());
}
for &(place, table, value) in &draws.fields {
if !rebound.field(table, value) {
continue;
}
let tables = &tables[table];
let (bytes, at) = match place {
DrawPlace::Push(offset) => (&mut *push, offset as usize),
DrawPlace::Block(of, offset) => (&mut blocks[of], offset as usize),
};
match value {
// The field's bytes, the first `len` of a little-endian `u64`.
let (word, len): (u64, usize) = match value {
// At a multiple of the argument's alignment, which the draw checked first.
FieldValue::BufferAddress { slot, .. } => {
let word = address_word(tables.address(slot, nil));
bytes[at..at + 8].copy_from_slice(&word.to_le_bytes());
}
FieldValue::BufferBounds(slot) => {
bytes[at..at + 8].copy_from_slice(&tables.bounds(slot));
}
FieldValue::ZeroAddress => bytes[at..at + 8].copy_from_slice(&zero.to_le_bytes()),
FieldValue::BufferAddress { slot, .. } => (address_word(tables.address(slot, nil)), 8),
FieldValue::BufferBounds(slot) => (u64::from_le_bytes(tables.bounds(slot)), 8),
FieldValue::ZeroAddress => (zero, 8),
FieldValue::TextureId(slot) => {
let id = (tables.texture(slot)).map_or(0, |t| {
let second = (moved.iter()).any(|m| m.hazard == t.hazard_id())
@@ -2518,42 +2821,60 @@ fn fill_push(
false => t.gpu_resource_id().to_bits(),
}
});
bytes[at..at + 8].copy_from_slice(&id.to_le_bytes());
(id, 8)
}
FieldValue::SamplerId(slot) => {
let id = match tables.samplers.get(slot as usize) {
Some(Some(sampler)) => sampler.gpu_resource_id().to_bits(),
_ => 0,
};
bytes[at..at + 8].copy_from_slice(&id.to_le_bytes());
(id, 8)
}
FieldValue::IntegerChannels(slot) => {
let word = (tables.texture(slot))
.map_or(0, |t| integer_channels_word(t.descriptor().pixel_format));
bytes[at..at + 4].copy_from_slice(&word.to_le_bytes());
(u64::from(word), 4)
}
FieldValue::ConstexprSampler(place) => {
let index = ids.get(place).copied().unwrap_or(0);
bytes[at..at + 4].copy_from_slice(&index.to_le_bytes());
}
FieldValue::Word(word) => bytes[at..at + 4].copy_from_slice(&word.to_le_bytes()),
FieldValue::TessellationFactors => {
bytes[at..at + 8].copy_from_slice(&factors.to_le_bytes());
}
FieldValue::AlphaTestReference => {
bytes[at..at + 4].copy_from_slice(&alpha_test.to_le_bytes());
(u64::from(ids.get(place).copied().unwrap_or(0)), 4)
}
FieldValue::Word(word) => (u64::from(word), 4),
FieldValue::TessellationFactors => (factors, 8),
FieldValue::AlphaTestReference => (u64::from(alpha_test), 4),
// The pass's attachment's texture's second element, which the draw's attachment reads
// checked (`attachment_reads`).
FieldValue::FetchedColor(color) => {
let index = (pass.colors.get(color as usize))
.and_then(Option::as_ref)
.map_or(0, |target| target.texture.second_resource_id().index);
bytes[at..at + 4].copy_from_slice(&index.to_le_bytes());
(u64::from(index), 4)
}
// A render content has no dispatch or stage-in region (`render::draws`).
FieldValue::DispatchRegion | FieldValue::StageInRegion => {}
}
FieldValue::DispatchRegion | FieldValue::StageInRegion => continue,
};
let (bytes, at) = match place {
DrawPlace::Push(offset) => {
let at = offset as usize;
written = cover(written, at..at + len);
(&mut *push, at)
}
DrawPlace::Block(of, offset) => {
filled[of] = true;
(&mut blocks[of], offset as usize)
}
};
bytes[at..at + len].copy_from_slice(&word.to_le_bytes()[..len]);
}
(written, filled)
}
/// The bytes from the first of `a` and `b` to the end of the last: either where the other is
/// empty.
fn cover(a: Range<usize>, b: Range<usize>) -> Range<usize> {
match (a.is_empty(), b.is_empty()) {
(true, _) => b,
(_, true) => a,
_ => a.start.min(b.start)..a.end.max(b.end),
}
}
+57 -11
View File
@@ -6,7 +6,7 @@
//! retires; a block's clones, one dropped giving nothing back, and a handle outliving its
//! device; the thread gauge holding the device's four threads as it is made; and a command
//! buffer joining a held group only within the group's expected GPU run. Without a device: a push
//! whose bytes the command buffer holds is not recorded again; a queue's expected run rises to a
//! records only the words the command buffer does not hold; a queue's expected run rises to a
//! longer run at once and halves toward a shorter one; the join and send decisions of the group
//! bound.
@@ -59,18 +59,64 @@ fn a_queues_expected_run_rises_at_once_and_halves_toward_a_shorter_run() {
assert_eq!(next_run(None, u64::MAX), u64::MAX - 1);
}
/// A push whose bytes the command buffer already holds from offset 0 records nothing; one that
/// changes any of them records, and keeps the held bytes past its end.
/// A push records only the words its command buffer does not hold: every word at a new
/// `VkCommandBuffer`'s first push, whatever the caller names, each word past the bytes held, and
/// from the first word that differs to the last; one of words held records nothing and keeps the
/// held bytes past its end. A caller whose own push left the mark has only the words it names
/// compared; after any other push, every word is.
#[test]
fn a_push_of_the_bytes_a_command_buffer_holds_records_nothing() {
fn a_push_records_only_the_words_its_command_buffer_does_not_hold() {
let words = |words: &[u32]| -> Vec<u8> { words.iter().flat_map(|w| w.to_le_bytes()).collect() };
let mut pushed = Pushed::default();
assert!(pushed.needed(&[1, 2, 3, 4]), "the first push");
assert!(!pushed.needed(&[1, 2, 3, 4]), "the same bytes again");
assert!(!pushed.needed(&[1, 2]), "a shorter push of bytes held");
assert!(pushed.needed(&[1, 9]), "a shorter push that changes one");
assert!(!pushed.needed(&[1, 9, 3, 4]), "the bytes past it kept");
assert!(pushed.needed(&[1, 9, 3, 4, 5]), "a longer push");
assert!(Pushed::default().needed(&[1, 9]), "a new command buffer's");
pushed.restart();
let (mut mine, mut other) = (u64::MAX, u64::MAX);
let push = words(&[1, 2, 3, 4]);
assert_eq!(
pushed.changed(&push, 0..0, &mut mine),
Some(0..16),
"a new command buffer's first: every word"
);
assert_eq!(
pushed.changed(&push, 0..16, &mut mine),
None,
"the same words"
);
assert_eq!(
pushed.changed(&words(&[1, 2]), 0..8, &mut mine),
None,
"a shorter push of words held"
);
assert_eq!(
pushed.changed(&words(&[1, 9, 3, 7]), 0..16, &mut mine),
Some(4..16),
"from the first word that differs to the last"
);
assert_eq!(
pushed.changed(&words(&[5, 9, 3, 7]), 0..4, &mut mine),
Some(0..4),
"the caller's own words"
);
assert_eq!(
pushed.changed(&words(&[5, 6]), 0..0, &mut other),
Some(4..8),
"another caller's push: every word compared"
);
assert_eq!(
pushed.changed(&words(&[5, 9, 3, 7]), 0..0, &mut mine),
Some(4..8),
"after another's push: every word compared again"
);
assert_eq!(
pushed.changed(&words(&[5, 9, 3, 7, 8]), 0..0, &mut mine),
Some(16..20),
"a longer push: the words past the bytes held"
);
pushed.restart();
assert_eq!(
pushed.changed(&words(&[5, 9]), 0..0, &mut mine),
Some(0..8),
"the next command buffer's first: every word"
);
}
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
+1
View File
@@ -53,6 +53,7 @@ mod present;
mod push_window;
mod read_write_tier;
mod readback;
mod refill;
mod render;
mod resolve;
mod ring;
+579
View File
@@ -0,0 +1,579 @@
//! A draw finds and fills again only what changed: under a device cfg, on every device of the
//! cfg's kind, with the owned fixtures `examples/runtime_examples.ll` and
//! `engine/fca_vertex_unread_attribute.ll` and fragment functions this test writes:
//! - over 1,200 random calls of one encoder (pipeline states of 30 spilled buffers with two
//! textures and a sampler, of 12 buffers, and of a fixed-function vertex binding; buffers,
//! offsets, bytes and nothing bound at the vertex and fragment functions' slots; textures,
//! sampler states, and draws), each draw's facts, push bytes and parameter blocks, found and
//! filled slot by slot, equal a find and fill of every slot of what is bound, and its command
//! buffer holds those push bytes; a draw refused is refused as a find of every slot is. The
//! command buffer is never committed: some calls bind past a buffer's end.
//! - a draw pushes only the words its command buffer does not hold: the whole window at a
//! command buffer's first, the words an offset or a buffer bound changed, none at a change of
//! the pipeline state that changes no word (every pipeline has the device's one layout), and,
//! in a pass after a dispatch in the same command buffer, only the words of the window the
//! dispatch's push changed; every pixel reads the values its draw was bound.
//!
//! `llvm-as` assembles the fixtures; without it a device test skips visibly.
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod on_device {
use crate::tests::blit::on_device::settled;
use crate::tests::command::on_device::each_device;
use crate::tests::draw::on_device::{
examples, floats, library, pass, read, run, state, target, vertices, Buffers, SIDE,
};
use crate::{
Buffer, ColorAttachmentDescriptor, ComputePipelineDescriptor, Device, DispatchType, Error,
FunctionDescriptor, IndexClass, Library, LoadAction, Metrics, PixelFormat, PrimitiveType,
RenderPipelineDescriptor, RenderPipelineState, SamplerDescriptor, ScissorRect, StageSource,
Texture, TextureDescriptor, TextureType, TextureUsage,
};
use metal2vulkan::library::{FunctionConstantValue, FunctionConstantValues};
use metal2vulkan::metal::{DataType, VertexFormat};
use metal2vulkan::pipeline::{
VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor,
};
use metal2vulkan_devtools::{engine_dir, llvm_assemble_text, AssembleError};
/// A module of fragment functions, each `(name, buffers, textures, wide, swapped)`: each returns
/// (`b0[i]`, `b1[0]`, `b2[0]`, the sum of the other buffers' first words and of each texture's
/// first channel sampled at (0.5, 0.5) through sampler 0), `b0` and `b1` swapped where
/// `swapped`. A wide one reads `b0` at the index `b1`'s first word holds, a load the containment
/// check takes, and stores its sum into its last buffer's second word; any other reads `b0[0]`.
fn fragments(functions: &[(&str, u32, u32, bool, bool)]) -> String {
let mut text = String::from(
"; Owned synthetic fragment functions.\n\
target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\
target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\
declare { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)\n\n",
);
// Metadata 1 to 5 are shared: the versions, the colour output and its list, the position.
let mut meta = vec![
"!1 = !{i32 2, i32 8, i32 0}".to_owned(),
"!2 = !{!\"Metal\", i32 4, i32 0, i32 0}".to_owned(),
"!3 = !{!\"air.render_target\", i32 0, i32 0, !\"air.arg_type_name\", !\"float4\"}"
.to_owned(),
"!4 = !{!3}".to_owned(),
"!5 = !{i32 0, !\"air.position\", !\"air.center\", !\"air.no_perspective\", !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"pos\"}".to_owned(),
];
let mut next = 10;
let mut entries = Vec::new();
for &(name, buffers, textures, wide, swapped) in functions {
let mut params = vec!["<4 x float> %pos".to_owned()];
let mut args = vec!["!5".to_owned()];
let entry = next;
let list = next + 1;
next += 2;
for k in 0..buffers {
params.push(format!("ptr addrspace(1) %b{k}"));
let access = match wide && k == buffers - 1 {
true => "air.read_write",
false => "air.read",
};
meta.push(format!(
"!{next} = !{{i32 {}, !\"air.buffer\", !\"air.location_index\", i32 {k}, i32 1, !\"{access}\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"float\", !\"air.arg_name\", !\"b{k}\"}}",
k + 1
));
args.push(format!("!{next}"));
next += 1;
}
for t in 0..textures {
params.push(format!("ptr addrspace(1) %t{t}"));
meta.push(format!(
"!{next} = !{{i32 {}, !\"air.texture\", !\"air.location_index\", i32 {t}, i32 1, !\"air.sample\", !\"air.arg_type_name\", !\"texture2d<float, sample>\", !\"air.arg_name\", !\"t{t}\"}}",
buffers + 1 + t
));
args.push(format!("!{next}"));
next += 1;
}
if textures > 0 {
params.push("ptr addrspace(2) %s".to_owned());
meta.push(format!(
"!{next} = !{{i32 {}, !\"air.sampler\", !\"air.location_index\", i32 0, i32 1, !\"air.arg_type_name\", !\"sampler\", !\"air.arg_name\", !\"s\"}}",
buffers + 1 + textures
));
args.push(format!("!{next}"));
next += 1;
}
let mut body = String::new();
for k in 1..buffers {
body.push_str(&format!(
" %v{k} = load float, ptr addrspace(1) %b{k}, align 4\n"
));
}
match wide {
true => body.push_str(
" %i = load i32, ptr addrspace(1) %b1, align 4\n %iw = zext i32 %i to i64\n %p0 = getelementptr inbounds float, ptr addrspace(1) %b0, i64 %iw\n %v0 = load float, ptr addrspace(1) %p0, align 4\n",
),
false => body.push_str(" %v0 = load float, ptr addrspace(1) %b0, align 4\n"),
}
body.push_str(" %a2 = fadd float 0.000000e+00, 0.000000e+00\n");
let mut sum = 2;
for k in 3..buffers {
body.push_str(&format!(" %a{k} = fadd float %a{}, %v{k}\n", k - 1));
sum = k;
}
let mut total = format!("%a{sum}");
for t in 0..textures {
body.push_str(&format!(
" %r{t} = tail call {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1) %t{t}, ptr addrspace(2) %s, <2 x float> <float 5.000000e-01, float 5.000000e-01>, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0)\n %c{t} = extractvalue {{ <4 x float>, i8 }} %r{t}, 0\n %e{t} = extractelement <4 x float> %c{t}, i64 0\n %u{t} = fadd float {total}, %e{t}\n"
));
total = format!("%u{t}");
}
if wide {
body.push_str(&format!(
" %q = getelementptr inbounds float, ptr addrspace(1) %b{}, i64 1\n store float {total}, ptr addrspace(1) %q, align 4\n",
buffers - 1
));
}
let (x, y) = match swapped {
true => ("%v1", "%v0"),
false => ("%v0", "%v1"),
};
body.push_str(&format!(
" %o0 = insertelement <4 x float> undef, float {x}, i64 0\n %o1 = insertelement <4 x float> %o0, float {y}, i64 1\n %o2 = insertelement <4 x float> %o1, float %v2, i64 2\n %o3 = insertelement <4 x float> %o2, float {total}, i64 3\n ret <4 x float> %o3\n"
));
text.push_str(&format!(
"define <4 x float> @{name}({}) {{\nentry:\n{body}}}\n\n",
params.join(", ")
));
meta.push(format!("!{entry} = !{{ptr @{name}, !4, !{list}}}"));
meta.push(format!("!{list} = !{{{}}}", args.join(", ")));
entries.push(format!("!{entry}"));
}
text.push_str(&format!(
"!air.fragment = !{{{}}}\n!air.version = !{{!1}}\n!air.language_version = !{{!2}}\n\n{}\n",
entries.join(", "),
meta.join("\n")
));
text
}
/// The library of [`fragments`] of `functions`, or None where `llvm-as` is missing.
fn fragment_library(functions: &[(&str, u32, u32, bool, bool)]) -> Option<Library> {
match llvm_assemble_text(&fragments(functions)) {
Ok(bitcode) => Some(Library::from_air(&bitcode).expect("the library")),
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
None
}
Err(error) => panic!("the fragment functions: {error:?}"),
}
}
/// A pipeline state of `examples`' `colored_vertex` and `fragment`'s function `name`, into
/// one colour attachment of `color`.
fn colored(
device: &Device,
(examples, fragment): (&Library, &Library),
name: &str,
color: PixelFormat,
) -> RenderPipelineState {
let function = |library: &Library, name| {
StageSource::Function(FunctionDescriptor::new(
library.function(name).expect("the function"),
))
};
let mut d = RenderPipelineDescriptor::new(function(examples, "colored_vertex"));
d.fragment = Some(function(fragment, name));
d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(color));
state(name, device, &d)
}
/// A deterministic sequence (xorshift64*).
struct Sequence(u64);
impl Sequence {
/// The next value below `n`.
fn below(&mut self, n: usize) -> usize {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
(self.0.wrapping_mul(0x2545_f491_4f6c_dd1d) >> 33) as usize % n
}
}
/// Over 1,200 random calls of one encoder, every draw's facts and fields equal a find and fill
/// of every slot, and its command buffer holds its push bytes; a refused draw is refused alike.
#[test]
fn every_device_refills_only_what_its_binds_change() {
let Some(examples) = examples() else {
return;
};
let Some(fragment) = fragment_library(&[("wide_fragment", 30, 2, true, false), TWELVE[0]])
else {
return;
};
let Some(stage_in) = library(&engine_dir().join("fca_vertex_unread_attribute.ll")) else {
return;
};
// `fca_vertex_unread_attribute`'s two attributes from vertex binding 0, which reads
// buffer slot 0.
let constants = FunctionConstantValues::defaults()
.with_index(0, FunctionConstantValue::new(DataType::Bool, [1]));
let function = |name| {
let mut f = FunctionDescriptor::new(stage_in.function(name).expect("the function"));
f.constants = constants.clone();
f.specialized = true;
StageSource::Function(f)
};
let mut fetched = RenderPipelineDescriptor::new(function("fca_vertex_unread_attribute"));
fetched.fragment = Some(function("fca_fragment_unread_attribute"));
fetched.color_attachments[0] =
Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm));
let mut vertex = VertexDescriptor::new();
for a in 0..2 {
let attribute = VertexAttributeDescriptor::new(VertexFormat::Float4, 16 * a, 0);
vertex.attributes.insert(a, attribute);
}
vertex
.layouts
.insert(0, VertexBufferLayoutDescriptor::new(Some(32)));
fetched.vertex_descriptor = Some(vertex);
each_device("refill", |name, _, device| {
let libraries = (&examples, &fragment);
let format = PixelFormat::RGBA8Unorm;
let states = [
colored(&device, libraries, "wide_fragment", format),
colored(&device, libraries, "twelve_fragment", format),
state(name, &device, &fetched),
];
let spilled = &states[0].inner.compiled.draws.blocks;
assert!(
spilled[1].is_some(),
"{name}: the wide fragment function's fields spill into a parameter block"
);
let _textures = (device.grant_indices(IndexClass::Texture, 1, 3))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let _samplers = (device.grant_indices(IndexClass::Sampler, 1, 2))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let textures: Vec<Texture> = (1..=3)
.map(|index| {
let mut d =
TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, 4, 4);
d.usage = TextureUsage::SHADER_READ;
(device.new_texture(&d, Some(index)))
.unwrap_or_else(|error| panic!("{name}: {error}"))
})
.collect();
let samplers: Vec<_> = (1..=2)
.map(|index| {
(device.new_sampler_state(&SamplerDescriptor::new(), index))
.unwrap_or_else(|error| panic!("{name}: {error}"))
})
.collect();
let mut buffers = Buffers::new(&device);
let bound: Vec<Buffer> = (0..4u8).map(|k| buffers.of(&device, &[k; 256])).collect();
let color = target(&device, format, TextureUsage::RENDER_TARGET);
let queue = device.new_command_queue(4).expect("a queue");
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None)))
.unwrap_or_else(|error| panic!("{name}: {error}"));
// Offsets inside the buffers, one off every argument's alignment, one past their end.
const OFFSETS: [u64; 5] = [0, 16, 48, 2, 4096];
let mut sequence = Sequence(0x9e37_79b9_7f4a_7c15);
let (mut drawn, mut refused) = (0, 0);
let call = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}"));
call(encoder.set_render_pipeline_state(&states[0]));
for step in 0..1_200 {
let table = sequence.below(2);
match sequence.below(12) {
0 => call(encoder.set_render_pipeline_state(&states[sequence.below(3)])),
1..=3 => {
let slot = sequence.below(31) as u32;
let buffer = (sequence.below(8) != 0).then(|| &bound[sequence.below(4)]);
let offset = OFFSETS[sequence.below(5)];
call(match table {
0 => encoder.set_vertex_buffer(buffer, offset, slot % 3),
_ => encoder.set_fragment_buffer(buffer, offset, slot),
});
}
4 => {
// Refused where the slot holds no buffer, as Metal's.
let (slot, offset) =
(sequence.below(31) as u32, OFFSETS[sequence.below(5)]);
let _ = match table {
0 => encoder.set_vertex_buffer_offset(offset, slot % 3),
_ => encoder.set_fragment_buffer_offset(offset, slot),
};
}
5 => {
let slot = sequence.below(31) as u32;
let bytes = [step as u8; 96];
call(match table {
0 => encoder.set_vertex_bytes(&bytes, slot % 3),
_ => encoder.set_fragment_bytes(&bytes, slot),
});
}
6 => {
let texture = &textures[sequence.below(3)];
call(encoder.set_fragment_texture(Some(texture), sequence.below(2) as u32));
}
7 => call(
encoder.set_fragment_sampler_state(Some(&samplers[sequence.below(2)]), 0),
),
_ => {
let result = encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0);
let refilled = encoder.refilled();
match result {
Ok(()) => {
assert_eq!(
Ok(&refilled.slot_by_slot),
refilled.whole.as_ref(),
"{name}: step {step}: slot by slot and whole"
);
assert_eq!(
refilled.held.get(..refilled.push.len()),
Some(&refilled.push[..]),
"{name}: step {step}: the command buffer's push bytes"
);
drawn += 1;
}
Err(error) => {
assert_eq!(
refilled.whole.err(),
Some(format!("{error:?}")),
"{name}: step {step}: the refusal"
);
refused += 1;
}
}
}
}
}
assert!(
drawn > 100 && refused > 10,
"{name}: {drawn} drawn, {refused} refused"
);
encoder.end_encoding();
println!("{name}: {drawn} draws equal a whole find and fill, {refused} refused alike");
});
}
/// Fragment functions of twelve buffers, the second with `b0` and `b1` swapped: the same fields
/// in the same places, and a window longer than a dispatch's of three buffers.
const TWELVE: [(&str, u32, u32, bool, bool); 2] = [
("twelve_fragment", 12, 0, false, false),
("swapped_fragment", 12, 0, false, true),
];
/// The bytes a push of `push` records where the command buffer holds `held`: from the first
/// word that differs to the last, and every word past `held`.
fn changed(held: &[u8], push: &[u8]) -> u64 {
let held = &held[..held.len().min(push.len())];
let differs: Vec<usize> = (0..held.len())
.step_by(4)
.filter(|&at| held[at..at + 4] != push[at..at + 4])
.collect();
let first = differs.first().copied().unwrap_or(held.len());
let end = match push.len() > held.len() {
true => push.len(),
false => differs.last().map_or(0, |at| at + 4),
};
end.saturating_sub(first) as u64
}
/// Pushes recorded, pushes held and push bytes since `before`.
fn pushes(device: &Device, before: &Metrics) -> (u64, u64, u64) {
let after = device.counters().metrics();
(
after.pushes - before.pushes,
after.pushes_held - before.pushes_held,
after.push_bytes - before.push_bytes,
)
}
/// One command buffer: a pass whose first draw pushes its whole window, an offset change that
/// pushes the changed words alone, a change of pipeline state that changes no word and pushes
/// none, and a buffer bound that pushes the changed words alone; then a dispatch, and a pass
/// whose draw pushes only the words of the window the dispatch's push changed. A second
/// command buffer's first draw pushes the whole window again. Each draw writes its own
/// column, which reads the values it was bound, and the dispatch writes its words.
#[test]
fn every_device_pushes_only_the_words_its_command_buffer_lacks() {
let Some(examples) = examples() else {
return;
};
let Some(fragment) = fragment_library(&TWELVE) else {
return;
};
each_device("refill_push", |name, _, device| {
let format = PixelFormat::RGBA32Float;
let libraries = (&examples, &fragment);
let twelve = colored(&device, libraries, "twelve_fragment", format);
let swapped = colored(&device, libraries, "swapped_fragment", format);
let places = |state: &RenderPipelineState| {
let draws = &state.inner.compiled.draws;
(draws.push_len, draws.fields.len(), draws.blocks)
};
assert_eq!(
places(&twelve),
places(&swapped),
"{name}: the two states' push windows"
);
let scale = ComputePipelineDescriptor::new(StageSource::Function(
FunctionDescriptor::new(examples.function("scale_and_offset").expect("a kernel")),
));
let scale = (device
.new_compute_pipeline_state(&scale, crate::tests::no_constexpr_samplers))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let mut buffers = Buffers::new(&device);
let (positions, colors) = vertices(&device, &mut buffers);
let a = buffers.of(&device, &floats(&[0.25]));
let b = buffers.of(&device, &floats(&[0.5, 0.75]));
let c = buffers.of(&device, &floats(&[0.125]));
let d = buffers.of(&device, &floats(&[0.875]));
let e = buffers.of(&device, &floats(&[0.0625]));
let input = buffers.of(&device, &floats(&[1.0, 2.0, 3.0, 4.0]));
let output = buffers.of(&device, &[0; 16]);
let color = target(&device, format, TextureUsage::RENDER_TARGET);
let queue = device.new_command_queue(4).expect("a queue");
let call = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}"));
let column = |encoder: &mut crate::RenderCommandEncoder, x: u64| {
encoder.set_scissor_rect(ScissorRect {
x,
y: 0,
width: 1,
height: u64::from(SIDE),
});
call(encoder.draw_primitives(PrimitiveType::Triangle, 3, 3, 1, 0));
};
let loaded = || {
let mut d = pass(&color, None);
d.color_attachments[0].load_action = LoadAction::Load;
d
};
settled(&device);
let command_buffer = queue.command_buffer().expect("a command buffer");
let before = device.counters().metrics();
let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None)))
.unwrap_or_else(|error| panic!("{name}: {error}"));
call(encoder.set_render_pipeline_state(&twelve));
call(encoder.set_vertex_buffer(Some(&positions), 0, 0));
call(encoder.set_vertex_buffer(Some(&colors), 0, 1));
for (slot, buffer) in [&a, &b, &c].into_iter().chain([&e; 9]).enumerate() {
call(encoder.set_fragment_buffer(Some(buffer), 0, slot as u32));
}
// Each draw's bytes, against what the command buffer held before it.
let mut want = Vec::new();
let mut held = Vec::new();
for step in 0..4 {
match step {
1 => call(encoder.set_fragment_buffer_offset(4, 1)),
2 => call(encoder.set_render_pipeline_state(&swapped)),
3 => call(encoder.set_fragment_buffer(Some(&d), 0, 2)),
_ => {}
}
column(&mut encoder, step);
let refilled = encoder.refilled();
want.push(changed(&held, &refilled.push));
held = refilled.held;
}
let window = want[0];
assert_eq!(
window,
u64::from(twelve.inner.compiled.draws.push_len.next_multiple_of(4)),
"{name}: the first draw's whole window"
);
assert!(
(1..=8).contains(&want[1]) && (1..=8).contains(&want[3]),
"{name}: one address's words at a bind: {want:?}"
);
assert_eq!(
want[2], 0,
"{name}: a change of pipeline state that changes no word"
);
encoder.end_encoding();
assert_eq!(
pushes(&device, &before),
(3, 1, want.iter().sum()),
"{name}: the first pass's pushes, pushes held and bytes ({want:?})"
);
let before = device.counters().metrics();
let mut compute =
(command_buffer.compute_command_encoder(DispatchType::Serial)).expect("an encoder");
call(compute.set_compute_pipeline_state(&scale));
call(compute.set_buffer(Some(&input), 0, 0));
call(compute.set_buffer(Some(&output), 0, 1));
call(compute.set_bytes(&floats(&[2.0]), 2));
call(compute.dispatch_threads([4, 1, 1], [4, 1, 1]));
compute.end_encoding();
let (dispatched, _, _) = pushes(&device, &before);
assert_eq!(dispatched, 1, "{name}: the dispatch's push");
let before = device.counters().metrics();
let mut encoder = (command_buffer.render_command_encoder(&loaded()))
.unwrap_or_else(|error| panic!("{name}: {error}"));
call(encoder.set_render_pipeline_state(&swapped));
let after_dispatch = encoder.refilled().held;
call(encoder.set_vertex_buffer(Some(&positions), 0, 0));
call(encoder.set_vertex_buffer(Some(&colors), 0, 1));
for (slot, buffer) in [&a, &b, &d].into_iter().chain([&e; 9]).enumerate() {
let offset = if slot == 1 { 4 } else { 0 };
call(encoder.set_fragment_buffer(Some(buffer), offset, slot as u32));
}
column(&mut encoder, 4);
let refilled = encoder.refilled();
let after = changed(&after_dispatch, &refilled.push);
encoder.end_encoding();
assert_eq!(
pushes(&device, &before),
(1, 0, after),
"{name}: the pass after the dispatch"
);
assert!(
after > 0 && after < window,
"{name}: the words the dispatch changed, not the whole window: {after} of {window}"
);
run(name, &command_buffer);
let before = device.counters().metrics();
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut encoder = (command_buffer.render_command_encoder(&loaded()))
.unwrap_or_else(|error| panic!("{name}: {error}"));
call(encoder.set_render_pipeline_state(&swapped));
call(encoder.set_vertex_buffer(Some(&positions), 0, 0));
call(encoder.set_vertex_buffer(Some(&colors), 0, 1));
for (slot, buffer) in [&a, &b, &d].into_iter().chain([&e; 9]).enumerate() {
let offset = if slot == 1 { 4 } else { 0 };
call(encoder.set_fragment_buffer(Some(buffer), offset, slot as u32));
}
column(&mut encoder, 5);
encoder.end_encoding();
assert_eq!(
pushes(&device, &before),
(1, 0, window),
"{name}: the next command buffer's first draw"
);
run(name, &command_buffer);
// Each column's (b0 or b1, b1 or b0, b2, nine times 0.0625).
let rest = 9.0 * 0.0625;
let columns: [[f32; 4]; 8] = [
[0.25, 0.5, 0.125, rest],
[0.25, 0.75, 0.125, rest],
[0.75, 0.25, 0.125, rest],
[0.75, 0.25, 0.875, rest],
[0.75, 0.25, 0.875, rest],
[0.75, 0.25, 0.875, rest],
[0.0, 0.0, 0.0, 1.0],
[0.0, 0.0, 0.0, 1.0],
];
let texels = read(&color, 16);
for (at, texel) in texels.chunks(16).enumerate() {
let got: Vec<f32> = (texel.chunks(4))
.map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
.collect();
let x = at % SIDE as usize;
assert_eq!(got, columns[x], "{name}: pixel {at}, column {x}");
}
let contents = output.contents().expect("a Shared buffer");
// SAFETY: the words lie in the buffer, which is alive, and its work completed.
let words: Vec<f32> = (0..4)
.map(|i| unsafe { contents.as_ptr().cast::<f32>().add(i).read_unaligned() })
.collect();
assert_eq!(words, [2.0, 5.0, 8.0, 11.0], "{name}: the dispatch's words");
println!(
"{name}: pushes of {want:?} bytes, then {after} of {window} after a dispatch, then {window} in a new command buffer"
);
});
}
}
@@ -2700,6 +2700,7 @@ impl Backend for NewRuntime {
("submissions", metrics.submissions),
("pushes", metrics.pushes),
("pushes_held", metrics.pushes_held),
("push_bytes", metrics.push_bytes),
("passes", metrics.passes),
("barriers", metrics.barriers),
("bytes_copied", metrics.bytes_copied),
@@ -2438,6 +2438,7 @@ field metal2vulkan-rt::Metrics.pipeline_cache_lock_waits pub pipeline_cache_lock
field metal2vulkan-rt::Metrics.pipeline_cache_looks_skipped pub pipeline_cache_looks_skipped: u64
field metal2vulkan-rt::Metrics.pipelines_created pub pipelines_created: u64
field metal2vulkan-rt::Metrics.private_long_reuses pub private_long_reuses: u64
field metal2vulkan-rt::Metrics.push_bytes pub push_bytes: u64
field metal2vulkan-rt::Metrics.pushes pub pushes: u64
field metal2vulkan-rt::Metrics.pushes_held pub pushes_held: u64
field metal2vulkan-rt::Metrics.resolves pub resolves: u64
Can't render this file because it is too large.