🆕 Make, execute and reset indirect command buffers of draws on rt

The rt platform made no indirect command buffer: every
newIndirectCommandBufferWithDescriptor:maxCommandCount:options: answered nil,
counted rt-unbuilt-icb. rt now builds buffers of indexed draws that a shader
encodes on the GPU, and the platform hands the guest's paths to it.

What changes for the guest:
- The make answers a buffer for indexed draws that inherit the pipeline state,
  on a host GPU whose Vulkan driver has VK_EXT_device_generated_commands
  (NVIDIA's, RADV). Everywhere else it is still nil, now counted as rt's gap
  (rt-refused-gap), its kind named IndirectCommandBuffers-<kind> in the boot
  diagnostics: no extension (an Intel Iris Xe, the UHD 630 on Windows, a Mac
  host), other command types, commands of their own pipeline states,
  inherited buffers, more than 31 vertex or fragment buffers, no commands or
  more than the device runs at once.
- Its gpuResourceID is rt's device address of the commands, which the guest's
  argument encoder writes and its shaders encode commands through; its size is
  the count asked, its resourceIndex 0.
- A render encoder's executeCommandsInBuffer:withRange: and
  executeCommandsInBuffer:indirectBuffer:indirectBufferOffset: draw the
  commands with the encoder's pipeline state. A range past the commands, a
  range buffer's offset off a multiple of 4 or without 8 bytes after it, and
  no pipeline state set are Metal's refusals, counted rt-refused-metal. A
  state made without supportIndirectCommandBuffers is rt's gap, and so is one
  whose commands carry more buffer slots than rt takes: each slot word goes in
  the state's 256-byte push range, which holds 25 slots of a state whose
  vertex function reads 24 and fragment function 1 on every device (measured
  on an RTX 3090 and a Radeon RX 7900 XTX), past which it is DrawInput; and
  each takes a device token, past which (13 slots on lavapipe; NVIDIA's 29
  and RADV's 125 are never reached) it is Tokens. Each such execution draws
  nothing, and the encoder's later commands draw. Metal has no query of the
  limit, so the guest learns it only from what an execution draws.
- A blit's resetCommandsInBuffer:withRange: resets the commands, which draw
  nothing until a shader encodes them again; its optimize and a synchronize of
  the buffer record nothing; useResource: of it keeps its commands until the
  command buffer retires. A compute encoder's execution is Metal's refusal.
- Still unbuilt, each counted rt-unbuilt-icb: commands the CPU encodes
  (indirectRenderCommandAtIndex: and indirectComputeCommandAtIndex: answer
  nil), the CPU's resetWithRange:, a blit's copy between buffers, and a
  descriptor of a resource index.

For the host, the first log line of each kind of rt's refusals of an
execution names the buffer's vertex and fragment bind counts, the most slot
words a command takes, and the device's maxIndirectCommandsTokenCount: which
slots the state's functions read is rt's to know, which it does not answer yet.

The tests make a buffer and refuse each kind rt refuses, execute two
GPU-encoded indexed draws by a CPU range and by a range buffer, reset one, and
execute commands of 24 to 30 slots against the push range and the device's
tokens; on a device without the extension they check the make's refusal.
This commit is contained in:
Anees Iqbal committed 2026-11-21 04:38:28 -08:00
1 parent e3a3fc82eb
commit 16eee4db90
12 files changed
+848 -80

No files matched your search

+3 -1
View File
@@ -51,6 +51,7 @@ pub mod fault;
pub mod format;
pub mod gauge_log;
pub mod heap;
pub mod icb;
pub mod library;
pub mod pipeline;
pub mod queue;
@@ -91,6 +92,7 @@ pub use compute::RtComputeEncoder;
pub use descriptor::{PassFields, RateMapFields, TextureFields};
pub use device::RtDevice;
pub use heap::RtHeap;
pub use icb::RtIcb;
pub use library::{RtFunction, RtLibrary};
pub use pipeline::RtComputePipeline;
pub use queue::RtQueue;
@@ -418,7 +420,7 @@ impl Platform for RtPlatform {
type DynamicLibrary = Unmade<kinds::DynamicLibrary>;
type RenderPipeline = RtObj<RtRenderPipeline>;
type RateMap = Unmade<kinds::RateMap>;
type Icb = Unmade<kinds::Icb>;
type Icb = RtObj<RtIcb>;
type IndirectRenderCommand<'a> = Unmade<kinds::IndirectRenderCommand>;
type IndirectComputeCommand<'a> = Unmade<kinds::IndirectComputeCommand>;
type TextureDescriptor = RtObj<TextureFields>;
@@ -175,6 +175,9 @@ pub struct Facts {
pub linear_alignment_largest: u64,
/// rt's `minimumLinearTextureAlignmentForPixelFormat:` of BGRA8; none where rt refuses it.
pub linear_alignment_bgra8: Option<u64>,
/// rt's floor's `maxIndirectCommandsTokenCount`, where the device enables
/// `VK_EXT_device_generated_commands` (`super::icb`); none where it does not.
pub indirect_tokens: Option<u32>,
}
/// The registry ID the rt platform gives the device of `uuid`, its `deviceUUID`: its two halves'
@@ -413,6 +416,7 @@ pub(crate) mod tests {
},
linear_alignment_largest: 16,
linear_alignment_bgra8: Some(16),
indirect_tokens: Some(128),
}
}
@@ -18,11 +18,17 @@
//! - **Nothing to record**: `optimizeContentsFor{CPU,GPU}Access:` (rt lays a texture out one way,
//! and Metal's optimize changes no texel), and `invalidateCompressedTexture:` (rt keeps no
//! lossless compression whose contents an invalidate would drop).
//! - **Indirect command buffers** (`super::icb`): a reset of a range of commands
//! (`resetCommandsInBuffer:withRange:`) is rt's, each command then drawing nothing; an optimize
//! (`optimizeIndirectCommandBuffer:withRange:`) and a synchronize of one are rt's, which record
//! nothing. A range past the buffer's commands is rt's refusal of Metal's
//! (`Refusal::CommandRange`), counted (`rt-refused-metal`), and so is one past 32 bits.
//! - **Unbuilt**: a fill of a texture with bytes ([`Unbuilt::FillTexture`]); a fill of a
//! texture with a colour, a fill of a buffer with a 4-byte pattern of more than one byte value,
//! a copy between textures with blit options, and a copy between a buffer and a texture with
//! blit options other than one plane's (`MTLBlitOptionRowLinearPVRTC`, as rt makes no PVRTC
//! texture, or more than one option) ([`Unbuilt::Blit`]). Each encodes nothing, counted.
//! texture, or more than one option) ([`Unbuilt::Blit`]); a copy between indirect command
//! buffers ([`Unbuilt::Icb`]). Each encodes nothing, counted.
//! - **The guest's RAM** is copied by no blit: the device copies none
//! (`GpuDevice::copies_guest_ram`), so each copy of it answers false.
//!
@@ -659,12 +665,17 @@ fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Resul
counts,
)?;
}
BlitCmd::CopyIndirectCommandBuffer { source, .. } => source.unreachable(),
BlitCmd::CopyIndirectCommandBuffer { .. } => return Err(Stop::Unbuilt(Unbuilt::Icb)),
BlitCmd::OptimizeIndirectCommandBuffer {
indirect_command_buffer,
..
} => indirect_command_buffer.unreachable(),
BlitCmd::ResetCommandsInBuffer { buffer, .. } => buffer.unreachable(),
range,
} => {
let range = super::icb::commands(range)?;
e.optimize_indirect_command_buffer(indirect_command_buffer.rt(), range)?;
}
BlitCmd::ResetCommandsInBuffer { buffer, range } => {
e.reset_commands_in_buffer(buffer.rt(), super::icb::commands(range)?)?;
}
BlitCmd::FillBufferPattern4 {
buffer,
range,
@@ -701,7 +712,9 @@ fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Resul
Some(ResourceRef::Texture(texture)) => {
e.synchronize_resource(rt::Resource::Texture(texture.rt()))?;
}
Some(ResourceRef::Icb(icb)) => icb.unreachable(),
Some(ResourceRef::Icb(icb)) => {
e.synchronize_resource(rt::Resource::IndirectCommandBuffer(icb.rt()))?;
}
},
BlitCmd::SynchronizeTexture { texture, .. } => {
e.synchronize_resource(rt::Resource::Texture(texture.rt()))?;
@@ -94,7 +94,8 @@
//! submissions itself, so `set_completion_joins_next` keeps the trait's default: never marked.
//! A command buffer is kept whole ([`KeptWhole`], in its order) while an encoder is open, under
//! protection options or once an encoder was made under them, once it signals an event as it
//! is scheduled, and once committed. rt builds no indirect command buffer, rate map, residency
//! is scheduled, and once committed. rt's indirect command buffers are read by the GPU as an
//! execution runs, whichever part holds it (`super::icb`), and rt builds no rate map, residency
//! or command predication, so no other reason holds; and it notes no way Metal's GPU fails a
//! command buffer from an encoder on, so `commit_part` never answers [`PartCut::Fails`] and
//! `fold`, the Vulkan platform's with nothing noted, lets the later part go. The guest buffer's
@@ -762,7 +763,8 @@ impl RtCommandBuffer {
KeptWhole::ProtectionOptions => protection,
KeptWhole::ScheduledSignal => scheduled_signal,
KeptWhole::Committed => committed,
// rt builds no indirect command buffer, rate map, residency or command predication.
// The GPU reads rt's indirect command buffers as an execution runs, and rt builds no
// rate map, residency or command predication.
KeptWhole::Execution | KeptWhole::Progress | KeptWhole::Predication => false,
};
KeptWhole::ALL.into_iter().find(|&reason| holds(reason))
@@ -150,14 +150,12 @@ impl RtComputeEncoder {
ComputeCmd::EndEncoding
| ComputeCmd::CompressedTextureReinterpretationFlush
| ComputeCmd::SetImageblockWidth { .. } => {}
ComputeCmd::ExecuteCommandsIndirect {
indirect_commandbuffer,
..
} => indirect_commandbuffer.unreachable(),
ComputeCmd::ExecuteCommandsInBuffer {
indirect_command_buffer,
..
} => indirect_command_buffer.unreachable(),
ComputeCmd::ExecuteCommandsIndirect { .. }
| ComputeCmd::ExecuteCommandsInBuffer { .. } => {
return Err(Stop::Metal(
"an indirect command buffer of draws executed in a compute encoder",
));
}
ComputeCmd::MemoryBarrierWithResources { .. }
| ComputeCmd::MemoryBarrierWithScope { .. } => e.memory_barrier(),
ComputeCmd::SetBufferOffset { offset, index }
@@ -342,7 +340,7 @@ pub(super) fn declared<'r>(
kept.reads().note(t.index_use());
rt::Resource::Texture(t.rt())
}
ResourceRef::Icb(icb) => icb.unreachable(),
ResourceRef::Icb(icb) => rt::Resource::IndirectCommandBuffer(icb.rt()),
}
}
@@ -596,6 +596,7 @@ fn facts(
linear_alignment_bgra8: device
.minimum_linear_texture_alignment(rt::PixelFormat::BGRA8Unorm)
.ok(),
indirect_tokens: floor.indirect_commands.map(|limits| limits.tokens),
}
}
@@ -1162,8 +1163,9 @@ impl GpuDevice<RtPlatform> for RtObj<RtDevice> {
/// Textures' (type 0) and sampler states' (type 1) indices as rt's grants of their class
/// ([`grant`]), each also kept from the platform's own ([`OwnIndices::reserve`]);
/// indirect command buffers' (type 5) are unbuilt ([`Unbuilt::Icb`]), and those of another
/// type ([`Unbuilt::ResourceType`]): each reserves nothing. Never a raise.
/// indirect command buffers' (type 5) are unbuilt ([`Unbuilt::Icb`]: rt gives a buffer no
/// index), and those of another type ([`Unbuilt::ResourceType`]): each reserves nothing.
/// Never a raise.
fn reserve_resource_indices(&self, resource_type: u64, indices: &[u64]) -> RaiseResult<()> {
let recorded_call = crate::recorder::rec_call!(
"reserveResourceIndicesForResourceType:indices:indexCount:",
@@ -1351,7 +1353,7 @@ impl GpuDevice<RtPlatform> for RtObj<RtDevice> {
recorded_answer
}
/// Unbuilt: nil ([`Unbuilt::Icb`]).
/// rt's buffer (`super::icb`); nil where rt refuses it, counted.
fn new_indirect_command_buffer(
&self,
desc: &IcbDesc,
@@ -1367,12 +1369,8 @@ impl GpuDevice<RtPlatform> for RtObj<RtDevice> {
);
let recorded_answer =
crate::recorder::run(|| -> RaiseResult<Option<<RtPlatform as Platform>::Icb>> {
let _ = (desc, max_count, options);
refuse_create(
Unbuilt::Icb,
"newIndirectCommandBufferWithDescriptor:maxCommandCount:options:",
);
Ok(None)
let _ = options;
Ok(super::icb::make(self, desc, max_count))
});
crate::recorder::rec_done!(recorded_call, recorded_answer);
recorded_answer
@@ -952,6 +952,12 @@ pub const SURFACE_PLANE_COPY_BYTES_CODE: &str = "rt-surface-plane-copy-bytes";
/// The refusals of rt's gaps by kind.
static GAPS: Mutex<BTreeMap<String, u64>> = Mutex::new(BTreeMap::new());
/// For the tests: the refusals of rt's gaps counted under `name` ([`refusal_name`]).
#[cfg(test)]
pub(crate) fn gaps_named(name: &str) -> u64 {
GAPS.lock().get(name).copied().unwrap_or(0)
}
/// The refusals of Metal's that rt answers, its limits, and the translator's refusals, by variant.
static REFUSALS: Mutex<BTreeMap<String, u64>> = Mutex::new(BTreeMap::new());
@@ -969,11 +975,12 @@ pub fn refusal(error: &rt::Error) {
*map.lock().entry(name).or_insert(0) += 1;
}
/// The kind [`refusal`] counts rt's `error` under: a gap's kind, a draw's `Draw-<kind>`, a
/// refusal of Metal's `Refused-<variant>`, a limit `Limit-<variant>`, and the translator's
/// `Translation-<feature>`, the variant of the feature it refused, or of its error where it
/// refused no feature (`Translation-InvalidInput`); `None` for any other error. Each is a variant's
/// name alone, no name of the guest's.
/// The kind [`refusal`] counts rt's `error` under: a gap's kind, a draw's `Draw-<kind>`, a linear
/// plane pass's `LinearPlanePass-<kind>`, an indirect command buffer's
/// `IndirectCommandBuffers-<kind>`, a refusal of Metal's `Refused-<variant>`, a limit
/// `Limit-<variant>`, and the translator's `Translation-<feature>`, the variant of the feature it
/// refused, or of its error where it refused no feature (`Translation-InvalidInput`); `None` for
/// any other error. Each is a variant's name alone, no name of the guest's.
pub fn refusal_name(error: &rt::Error) -> Option<String> {
use metal2vulkan::error::Error as Translator;
Some(match error {
@@ -981,6 +988,9 @@ pub fn refusal_name(error: &rt::Error) -> Option<String> {
rt::Error::Unsupported(rt::Gap::LinearPlanePass { kind }) => {
format!("LinearPlanePass-{kind:?}")
}
rt::Error::Unsupported(rt::Gap::IndirectCommandBuffers { kind }) => {
format!("IndirectCommandBuffers-{kind:?}")
}
rt::Error::Unsupported(gap) => variant(&format!("{gap:?}")).to_owned(),
rt::Error::Refused(r) => format!("Refused-{}", variant(&format!("{r:?}"))),
rt::Error::Limit(l) => format!("Limit-{}", variant(&format!("{l:?}"))),
@@ -2761,10 +2771,10 @@ mod tests {
assert!(line.contains(shown), "{line}");
}
/// A gap is counted by its kind, a draw's by its draw kind and a linear plane pass's by its
/// shape, a refusal of Metal's and a limit by their variant, and the translator's by the
/// feature it refused, else its error's variant, with no name of the guest's; another error is
/// not.
/// A gap is counted by its kind, a draw's by its draw kind, a linear plane pass's by its shape
/// and an indirect command buffer's by its kind, a refusal of Metal's and a limit by their
/// variant, and the translator's by the feature it refused, else its error's variant, with no
/// name of the guest's; another error is not.
#[test]
fn refusals_count_by_kind() {
use metal2vulkan::error::{
@@ -2777,6 +2787,9 @@ mod tests {
refusal(&rt::Error::Unsupported(rt::Gap::LinearPlanePass {
kind: rt::LinearPlanePassKind::DepthStencil,
}));
refusal(&rt::Error::Unsupported(rt::Gap::IndirectCommandBuffers {
kind: rt::IndirectCommandsKind::Tokens,
}));
refusal(&rt::Error::Refused(rt::Refusal::BufferTooLong {
length: 8,
max: 4,
@@ -2803,6 +2816,10 @@ mod tests {
gaps.get("LinearPlanePass-DepthStencil")
.is_some_and(|&n| n >= 1)
);
assert!(
gaps.get("IndirectCommandBuffers-Tokens")
.is_some_and(|&n| n >= 1)
);
drop(gaps);
let refusals = REFUSALS.lock();
assert!(
@@ -0,0 +1,274 @@
//! The rt platform's indirect command buffers ([`RtIcb`]): rt's, of indexed draw commands that
//! draw with the executing encoder's pipeline state and bind their own buffers, which a kernel or
//! a vertex function encodes on the GPU through the buffer's `gpuResourceID`.
//!
//! - **Its make** (`newIndirectCommandBufferWithDescriptor:maxCommandCount:options:`, [`make`]) is
//! rt's, of the descriptor's command types, `inheritPipelineState`, `inheritBuffers` and vertex,
//! fragment and kernel buffer bind counts, each count past 32 bits handed to rt as `u32::MAX`,
//! which rt refuses as past its own bound. The descriptor's other properties have no field of
//! rt's: the commands draw with the executing encoder's render states, whatever the `inherit*`
//! properties say, as rt documents an M4's commands do. The options are not read: rt keeps the
//! records in Private memory, which no CPU encode reaches. Each of rt's refusals answers nil,
//! counted under its kind (`rt-refused-gap` for `Gap::IndirectCommandBuffers`, its kind named in
//! the boot diagnostics, `IndirectCommandBuffers-<kind>`, and in the first line of each kind):
//! `Extension` on a device without `VK_EXT_device_generated_commands` (an Intel Iris Xe, the UHD
//! 630 on Windows, a Mac host's Vulkan), `CommandTypes` for types other than indexed draws alone,
//! `CommandPipelines` for commands that set their own pipeline state, `InheritedBuffers`,
//! `BindCount` past 31 vertex or fragment buffers, and `Capacity` for no commands or more than
//! the device runs in one execution. A descriptor of a resource index (`setResourceIndex:`) is
//! unbuilt ([`Unbuilt::Icb`]): nil, counted.
//! - **Its answers.** `gpuResourceID` is rt's, the device address of the records' header: the
//! guest's argument encoder writes it into an argument buffer's `command_buffer` member, and a
//! shader's encodes reach the records through it. `size` is rt's, the command count asked;
//! `resourceIndex` is 0 (rt gives the buffer no index); `uniqueIdentifier` is one of the pipeline
//! states' process-wide count from 1 (`super::pipeline`).
//! - **Its commands** are the GPU's to encode. A render encoder's executions are rt's, of a range
//! the CPU gives and of one a buffer holds (`super::render`); a blit's reset and optimize are
//! rt's, and so is a synchronize of the buffer, which records nothing (`super::blit`); a
//! `useResource:` of it is rt's, the command buffer keeping its records until it retires
//! (`super::compute`'s `declared`). Every buffer of rt's holds draws alone, so a compute
//! encoder's execution of one is Metal's refusal, counted (`rt-refused-metal`).
//! - **The commands' slots.** An execution of a pipeline state carries each buffer slot its
//! vertex and fragment functions read below the buffer's bind counts as a slot word of rt's
//! push range, which the two functions share, 256 bytes on every device: a command of more
//! slots than it holds is rt's refusal (`IndirectCommandBuffers-DrawInput`, `rt-refused-gap`).
//! It holds 25 of a state whose vertex function reads all but one of them and whose fragment
//! function reads one, of which a vertex function of 28 slots keeps its first 24 (measured on
//! an RTX 3090 and a Radeon RX 7900 XTX). Each slot word also takes a token of the device's,
//! and three more (the sequence, the index buffer and the draw), at most its
//! `maxIndirectCommandsTokenCount`: 16 on lavapipe, 32 on NVIDIA's driver and 128 on RADV, so
//! the push range binds first but on lavapipe, which refuses a command of more than 13 slots
//! (`IndirectCommandBuffers-Tokens`). Metal has no query of either, and the guest is told
//! nothing of them: a buffer's bind counts are Metal's, at most 31 each. Either refusal is at
//! the execution: it draws nothing, and the encoder's later commands draw. The first line of
//! each kind names the buffer's bind counts and the device's tokens ([`ExecutionDetail`]): which
//! slots the state's functions read is rt's to know. A state made without
//! `supportIndirectCommandBuffers` is refused there too
//! (`IndirectCommandBuffers-UnflaggedState`), and so is one that reads what else a command
//! cannot carry (`IndirectCommandBuffers-DrawInput`).
//! - **Unbuilt** ([`Unbuilt::Icb`]), each counted: commands the CPU encodes
//! (`indirectRenderCommandAtIndex:`, `indirectComputeCommandAtIndex:`), which answer nil, so
//! each of the guest's records of a CPU encode is refused; a CPU `resetWithRange:`, which resets
//! nothing; and a blit's copy between buffers (`copyIndirectCommandBuffer:...`), which encodes
//! nothing.
use std::ops::Range;
use metal2vulkan_runtime as rt;
use crate::core::platform::Platform;
use crate::core::platform::icb::IndirectCommandBuffer;
use crate::core::platform::types::NsRange;
use crate::core::platform::values::IcbDesc;
use crate::core::raise::RaiseResult;
use super::blit::Stop;
use super::pipeline::next_identifier;
use super::unbuilt::{Unbuilt, refuse, refuse_create, rt_refused_create};
use super::{RtDevice, RtObj, RtPlatform};
/// The creator's selector.
const MAKE: &str = "newIndirectCommandBufferWithDescriptor:maxCommandCount:options:";
/// `id<MTLIndirectCommandBuffer>` on metal2vulkan-runtime: rt's buffer.
pub struct RtIcb {
rt: rt::IndirectCommandBuffer,
unique_identifier: u64,
/// What a refused execution's first line names of it ([`ExecutionDetail`]).
detail: ExecutionDetail,
}
impl RtIcb {
/// rt's buffer.
pub fn rt(&self) -> &rt::IndirectCommandBuffer {
&self.rt
}
/// What an execution of it asks of rt, for the process's first line of each kind of rt's
/// refusals of one.
pub(super) fn detail(&self) -> &ExecutionDetail {
&self.detail
}
}
/// What an execution asked of rt, for the process's first line of each kind of rt's refusals of
/// it (`super::unbuilt::refusal_detail`): its buffer's vertex and fragment buffer bind counts as
/// rt took them, the most slot words one of its commands takes, and the device's
/// `maxIndirectCommandsTokenCount`. Which slots below the bind counts the state's functions read,
/// the slot words a command takes, and which of them its push range holds are rt's to know, which
/// no call of rt's answers here, so the line says so.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct ExecutionDetail {
/// The buffer's vertex and fragment buffer bind counts.
pub(super) binds: (u32, u32),
/// The device's `maxIndirectCommandsTokenCount`, rt's floor's.
pub(super) tokens: Option<u32>,
}
impl std::fmt::Display for ExecutionDetail {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (vertex, fragment) = self.binds;
write!(
f,
"an execution of a buffer of {vertex} vertex and {fragment} fragment buffer slots a \
command, at most {} slot words a command (which of them its state's functions read \
is not known here), ",
vertex.saturating_add(fragment)
)?;
match self.tokens {
Some(tokens) => write!(
f,
"on a device of {tokens} indirect command tokens, {} slot words a command",
tokens.saturating_sub(3)
),
None => f.write_str("on a device of no indirect command tokens"),
}
}
}
/// A count of the guest's as rt takes it: one past 32 bits as `u32::MAX`, which rt refuses as
/// past its own bound.
fn count(value: u64) -> u32 {
u32::try_from(value).unwrap_or(u32::MAX)
}
/// The commands of `range` as rt's: one past 32 bits is past every buffer's commands, Metal's
/// refusal.
pub(super) fn commands(range: NsRange) -> Result<Range<u32>, Stop> {
let end = range.location.checked_add(range.length);
let end = end.and_then(|end| u32::try_from(end).ok());
match (u32::try_from(range.location), end) {
(Ok(start), Some(end)) => Ok(start..end),
_ => Err(Stop::Metal("a range of commands past 32 bits")),
}
}
/// `newIndirectCommandBufferWithDescriptor:maxCommandCount:options:` of `desc` and `max_count` on
/// `device` (the module's docs); nil where rt refuses it, or of a resource index, counted.
pub(super) fn make(device: &RtDevice, desc: &IcbDesc, max_count: u64) -> Option<RtObj<RtIcb>> {
if desc.resource_index.is_some() {
refuse_create(Unbuilt::Icb, MAKE);
return None;
}
let mut d = rt::IndirectCommandBufferDescriptor::new();
d.command_types = rt::IndirectCommandType::from_bits(desc.command_types);
d.inherit_pipeline_state = desc.inherit_pipeline_state;
d.inherit_buffers = desc.inherit_buffers;
d.max_vertex_buffer_bind_count = count(desc.max_vertex_buffer_bind_count);
d.max_fragment_buffer_bind_count = count(desc.max_fragment_buffer_bind_count);
d.max_kernel_buffer_bind_count = count(desc.max_kernel_buffer_bind_count);
let detail = ExecutionDetail {
binds: (
d.max_vertex_buffer_bind_count,
d.max_fragment_buffer_bind_count,
),
tokens: device.facts().indirect_tokens,
};
let made = device
.rt()
.new_indirect_command_buffer(&d, count(max_count));
match made {
Ok(made) => Some(RtObj::new(RtIcb {
rt: made,
unique_identifier: next_identifier(),
detail,
})),
Err(error) => {
rt_refused_create(MAKE, &error);
None
}
}
}
impl IndirectCommandBuffer<RtPlatform> for RtObj<RtIcb> {
/// rt's: the records' header's device address.
fn gpu_resource_id(&self) -> u64 {
crate::recorder::plain_resource_id(self, || self.rt.gpu_resource_id())
}
/// Unbuilt: nil ([`Unbuilt::Icb`]).
fn compute_command(
&self,
_command_index: u64,
) -> RaiseResult<Option<<RtPlatform as Platform>::IndirectComputeCommand<'_>>> {
refuse(Unbuilt::Icb, "indirectComputeCommandAtIndex:");
Ok(None)
}
/// Unbuilt: nil ([`Unbuilt::Icb`]).
fn render_command(
&self,
_command_index: u64,
) -> RaiseResult<Option<<RtPlatform as Platform>::IndirectRenderCommand<'_>>> {
refuse(Unbuilt::Icb, "indirectRenderCommandAtIndex:");
Ok(None)
}
/// Unbuilt: resets nothing ([`Unbuilt::Icb`]).
fn reset_with_range(&self, _location: u64, _length: u64) -> RaiseResult<()> {
refuse(Unbuilt::Icb, "resetWithRange:");
Ok(())
}
/// 0: rt gives the buffer no index.
fn resource_index(&self) -> u64 {
0
}
/// rt's: the command count asked.
fn size(&self) -> u64 {
u64::from(self.rt.size())
}
/// One of the pipeline states' process-wide count from 1.
fn unique_identifier(&self) -> u64 {
self.unique_identifier
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A range of commands is rt's as it is; one whose start or end is past 32 bits is Metal's
/// refusal.
#[test]
fn a_range_of_commands_past_32_bits_is_metal_s_refusal() {
assert!(matches!(commands(NsRange::new(1, 2)), Ok(range) if range == (1..3)));
let past = [
NsRange::new(u64::from(u32::MAX), 1),
NsRange::new(1 << 32, 0),
NsRange::new(u64::MAX, 2),
];
for range in past {
assert!(matches!(commands(range), Err(Stop::Metal(_))), "{range:?}");
}
}
/// A refused execution's detail names its buffer's bind counts, the most slot words a command
/// takes, and the device's tokens and the slot words they leave a command, or that the
/// device has none.
#[test]
fn a_refused_execution_s_detail_names_the_bind_counts_and_the_device_s_tokens() {
let detail = ExecutionDetail {
binds: (29, 1),
tokens: Some(32),
};
assert_eq!(
detail.to_string(),
"an execution of a buffer of 29 vertex and 1 fragment buffer slots a command, at most \
30 slot words a command (which of them its state's functions read is not known \
here), on a device of 32 indirect command tokens, 29 slot words a command"
);
let detail = ExecutionDetail {
binds: (2, 0),
tokens: None,
};
assert_eq!(
detail.to_string(),
"an execution of a buffer of 2 vertex and 0 fragment buffer slots a command, at most 2 \
slot words a command (which of them its state's functions read is not known here), on \
a device of no indirect command tokens"
);
}
}
@@ -20,6 +20,19 @@
//! `setVertexBuffers:offsets:attributeStrides:withRange:`) bind as the calls without them: only a
//! layout of `MTLBufferLayoutStrideDynamic` reads a stride, and rt refuses such a state as it is
//! made.
//! - **Executions of an indirect command buffer** (`executeCommandsInBuffer:withRange:`, and
//! `executeCommandsInBuffer:indirectBuffer:indirectBufferOffset:` of a range the GPU reads from
//! the buffer as the execution runs) are rt's (`super::icb`): each command draws with the
//! encoder's pipeline state and render states and the buffers the command's encoding bound, and
//! the command buffer keeps the buffer's records, and a range buffer, until it retires. Without
//! a pipeline state set it is Metal's refusal, as a draw is; rt refuses a range past the
//! buffer's commands and a range buffer's offset that is not a multiple of 4 or without 8
//! bytes after it (`Refusal::CommandRange`), counted (`rt-refused-metal`), and a state made
//! without `supportIndirectCommandBuffers` or one whose commands carry more buffer slots than
//! rt's push range holds or the device's tokens take (`Gap::IndirectCommandBuffers`, the
//! module `super::icb`'s "The commands' slots"), counted (`rt-refused-gap`), each drawing
//! nothing. The first line of each kind of rt's refusals of an execution names the buffer's
//! bind counts and the device's tokens (`super::icb::ExecutionDetail`).
//! - **`useResources:`** in each form is rt's `use_resource` of each resource it names but nil, as
//! the compute encoder's is (`super::compute`): the command buffer keeps the resource until it
//! retires, and rt records nothing. A tiled texture it names is a use of it (`super::tiled`), and
@@ -57,8 +70,9 @@
//! - **Metal's refusals**, each encoding nothing, counted (`rt-refused-metal`): a draw with no
//! pipeline state set, or with nil set since; a value no Metal enumeration has (a primitive,
//! index or fill type, a cull mode, a winding, a depth clip mode, a store action, a visibility
//! result mode, a resource usage); an index, a count or a base past rt's 32 bits; a list of
//! another length than its range; and a command after `endEncoding`.
//! result mode, a resource usage); an index, a count or a base past rt's 32 bits, and a range
//! of commands past them; a list of another length than its range; and a command after
//! `endEncoding`.
//!
//! A command rt refuses encodes nothing, counted under the refusal's kind; in a list, the entries
//! before the refused one are bound.
@@ -396,12 +410,21 @@ impl RtRenderEncoder {
| RenderCmd::SetTileTextures { .. } => {}
RenderCmd::ExecuteCommandsIndirect {
indirect_commandbuffer,
..
} => indirect_commandbuffer.unreachable(),
indirect_range_buffer,
indirect_buffer_offset,
} => {
set(*pipeline)?;
let (commands, ranges) = (indirect_commandbuffer.rt(), indirect_range_buffer.rt());
e.execute_commands_in_buffer_with_range(commands, ranges, indirect_buffer_offset)?;
}
RenderCmd::ExecuteCommandsInBuffer {
indirect_command_buffer,
..
} => indirect_command_buffer.unreachable(),
execution_range,
} => {
set(*pipeline)?;
let range = super::icb::commands(execution_range)?;
e.execute_commands_in_buffer(indirect_command_buffer.rt(), range)?;
}
RenderCmd::MemoryBarrierWithScope { .. } => e.memory_barrier()?,
RenderCmd::SetBlendColorRed {
red,
@@ -647,6 +670,22 @@ fn drawn_primitive(cmd: &RenderCmd<'_, RtPlatform>) -> Option<u64> {
}
}
/// What an execution `cmd` asks of rt ([`super::icb::ExecutionDetail`]), for the process's first
/// line of each kind of rt's refusals of one; none for a command other than an execution.
fn execution(cmd: &RenderCmd<'_, RtPlatform>) -> Option<super::icb::ExecutionDetail> {
match cmd {
RenderCmd::ExecuteCommandsInBuffer {
indirect_command_buffer: icb,
..
}
| RenderCmd::ExecuteCommandsIndirect {
indirect_commandbuffer: icb,
..
} => Some(*icb.detail()),
_ => None,
}
}
/// What a draw asked of rt, for the process's first line of each kind of rt's refusals of it
/// (`super::unbuilt::refusal_detail`), as structure alone: its primitive type (Metal's number;
/// none for a command other than a draw of one) and the rasterization fields of the pipeline
@@ -877,6 +916,7 @@ impl RenderEncoder<RtPlatform> for RtObj<RtRenderEncoder> {
let ending = matches!(cmd, RenderCmd::EndEncoding);
note_copies(self.kept.copies(), &cmd);
let primitive = drawn_primitive(&cmd);
let execution = execution(&cmd);
let mut open = self.open.lock();
if let Some(names) = open.naming.names() {
note_names(names, &cmd);
@@ -893,6 +933,17 @@ impl RenderEncoder<RtPlatform> for RtObj<RtRenderEncoder> {
_ => {}
}
}
let icb_gap = |error: &rt::Error| {
matches!(
error,
rt::Error::Unsupported(rt::Gap::IndirectCommandBuffers { .. })
)
};
if let (Some(Stop::Rt(error)), Some(what)) = (&stopped, &execution)
&& icb_gap(error)
{
super::unbuilt::refusal_detail(sel, error, Some(what));
}
if ending && let Some(e) = open.rt.take() {
e.end_encoding();
self.mark.end();
@@ -925,18 +976,23 @@ mod tests {
use crate::core::num::ToU64 as _;
use crate::core::platform::Platform as _;
use crate::core::platform::blit::ResourceRef;
use crate::core::platform::blit::{BlitCmd, BlitEncoder as _};
use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _};
use crate::core::platform::compute::{ComputeCmd, ComputeEncoder as _};
use crate::core::platform::descriptor::RenderPassDescriptor as _;
use crate::core::platform::device::GpuDevice as _;
use crate::core::platform::icb::IndirectCommandBuffer as _;
use crate::core::platform::resource::{Buffer as _, Library as _, Texture as _};
use crate::core::platform::types::{ClearColor, CommandBufferStatus, MtlSize, NsRange};
use crate::core::platform::values::IcbDesc;
use crate::core::platform::values::{
AttributeDesc, BufferLayoutDesc, ColorAttachmentDesc, ColorAttachmentSet,
FullRenderPipelineDesc, PassSet, TextureDesc, VertexDesc,
};
use crate::rt_platform::unbuilt::RtRefusal;
use crate::rt_platform::{PassFields, RtCommandBuffer, RtDevice, RtFunction, RtTexture};
use crate::rt_platform::{
PassFields, RtCommandBuffer, RtComputePipeline, RtDevice, RtFunction, RtIcb, RtTexture,
};
/// A vertex function fed through a vertex descriptor: attribute 0 a `float2` position, 1 a
/// normalized `uchar4` colour.
@@ -958,6 +1014,16 @@ mod tests {
/// A kernel that writes each texel of texture 0 its grid reaches (`tex_write`).
const TEXWRITE: &[u8] = include_bytes!("../../../../tests/shaders/compute_texwrite.metallib");
/// Kernels that encode indexed triangles into the indirect command buffer whose
/// `gpuResourceID` buffer 0 holds, command `tid` drawing the three 16-bit indices of buffer 3
/// from `3 * tid` with the `float4` positions of buffer 1 at vertex buffer 0 and its own
/// `float4` colour of buffer 2 at fragment buffer 0 (`icb_encode`), and at vertex buffers 0 to
/// 28 (`icb_encode_wide`); vertex functions that place each vertex at its position read from
/// vertex buffer 0 (`icb_vertex`) or as the sum of buffers 0 to 27 (`icb_vertex_28`) or 0 to
/// 28 (`icb_vertex_29`); and a fragment function that returns the colour at fragment buffer 0
/// (`icb_fragment`).
const ICB: &[u8] = include_bytes!("../../../../tests/shaders/icb_indexed.metallib");
/// `MTLPrimitiveTypeTriangle`.
const TRIANGLE: u64 = 3;
@@ -1927,4 +1993,425 @@ mod tests {
}
eprintln!("the pixel formats a declared write refused draws after: {refused:?}");
}
/// `MTLIndirectCommandTypeDrawIndexed`.
const DRAW_INDEXED: u64 = 2;
/// A descriptor of indexed draws that inherit the pipeline state and bind `vertex` vertex
/// buffers and one fragment buffer each.
fn icb_desc(vertex: u64) -> IcbDesc {
IcbDesc {
command_types: DRAW_INDEXED,
inherit_pipeline_state: true,
max_vertex_buffer_bind_count: vertex,
max_fragment_buffer_bind_count: 1,
..IcbDesc::default()
}
}
/// `device`'s `maxIndirectCommandsTokenCount`, rt's floor's reading of it; `None` on a device
/// without `VK_EXT_device_generated_commands`.
fn tokens(device: &RtObj<RtDevice>) -> Option<u32> {
device.facts().indirect_tokens
}
/// The state of `vertex` and `icb_fragment` on `device` into one `RGBA8Unorm` colour
/// attachment, made for indirect command buffers where `flagged`.
fn icb_state(device: &RtObj<RtDevice>, vertex: &str, flagged: bool) -> RtObj<RtRenderPipeline> {
let vertex = function(device, ICB, vertex);
let fragment = function(device, ICB, "icb_fragment");
let mut desc = FullRenderPipelineDesc::new(&vertex, Some(&fragment));
desc.colors = vec![(
0,
ColorAttachmentDesc {
pixel_format: 70,
..ColorAttachmentDesc::default()
},
)];
desc.support_indirect_command_buffers = flagged;
let state = device.new_render_pipeline_state_full(&desc);
state.expect("a render state").expect("a render state")
}
/// The buffers a kernel of [`ICB`] encodes commands of: for each of `colours`, a triangle over
/// the whole of a target, (-1, -1), (3, -1), (-1, 3), as three `float4` positions, its three
/// 16-bit indices and its colour as a `float4`.
struct IcbScene {
positions: RtObj<RtBuffer>,
colours: RtObj<RtBuffer>,
indices: RtObj<RtBuffer>,
}
impl IcbScene {
fn new(device: &RtObj<RtDevice>, colours: &[[f32; 4]]) -> IcbScene {
let floats = |values: &[f32]| -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
};
let corner = [
[-1.0f32, -1.0, 0.0, 1.0],
[3.0, -1.0, 0.0, 1.0],
[-1.0, 3.0, 0.0, 1.0],
];
let positions: Vec<f32> = (colours.iter())
.flat_map(|_| corner.iter().flatten().copied())
.collect();
let indices: Vec<u8> = (0..3 * colours.len())
.flat_map(|i| u16::try_from(i).expect("a 16-bit index").to_le_bytes())
.collect();
let colours: Vec<f32> = colours.iter().flatten().copied().collect();
IcbScene {
positions: shared(device, &floats(&positions)),
colours: shared(device, &floats(&colours)),
indices: shared(device, &indices),
}
}
/// `count` threads of `kernel` encode commands 0 to `count` of `icb`, declared written,
/// in a command buffer `made` that completes.
fn encode(
&self,
(device, made): (&RtObj<RtDevice>, &RtObj<RtCommandBuffer>),
kernel: &RtObj<RtComputePipeline>,
icb: &RtObj<RtIcb>,
count: u64,
) {
let on = OnFault::Return;
let arguments = shared(device, &icb.gpu_resource_id().to_le_bytes());
let encoder = made.compute_encoder(on).expect("never a raise");
let encoder = encoder.expect("a compute encoder");
let buffers = [
Some(&arguments),
Some(&self.positions),
Some(&self.colours),
Some(&self.indices),
];
let declared = [Some(ResourceRef::Icb(icb))];
let cmds = [
ComputeCmd::SetComputePipelineState {
state: Some(kernel),
},
ComputeCmd::SetBuffers {
buffers: &buffers,
offsets: &[0; 4],
range: NsRange::new(0, 4),
},
ComputeCmd::UseResources {
resources: &declared,
usage: 2,
},
ComputeCmd::DispatchThreads {
threads_per_grid: MtlSize::new(count, 1, 1),
threads_per_threadgroup: MtlSize::new(count, 1, 1),
},
ComputeCmd::EndEncoding,
];
for cmd in cmds {
assert_eq!(encoder.encode(on, cmd), Ok(()));
}
assert_eq!(made.commit(on), Ok(()));
assert_eq!(made.wait_until_completed(on), Ok(()));
assert_eq!(made.status(), CommandBufferStatus::COMPLETED);
}
}
/// The commands that set `state` and execute commands `location` to `location + length` of
/// `icb`.
fn executed<'a>(
state: &'a RtObj<RtRenderPipeline>,
icb: &'a RtObj<RtIcb>,
(location, length): (u64, u64),
) -> Vec<RenderCmd<'a, RtPlatform>> {
vec![
RenderCmd::SetRenderPipelineState {
pipeline_state: Some(state),
},
RenderCmd::ExecuteCommandsInBuffer {
indirect_command_buffer: icb,
execution_range: NsRange::new(location, length),
},
]
}
/// Indirect command buffers are rt's (`super::super::icb`): a buffer of indexed draws that
/// inherit the pipeline state is made with Metal's answers, a kernel encodes its commands
/// through its `gpuResourceID`, and an execution of a range the CPU gives or a buffer holds
/// draws those commands with the encoder's pipeline state, the last drawn on top; an empty
/// range draws nothing. A blit's reset of a command leaves it drawing nothing until a kernel
/// encodes it again, and an optimize and a synchronize record nothing. A range past the
/// commands, a range buffer's offset off a multiple of 4 or without 8 bytes after it, and an
/// execution with no pipeline state set or in a compute encoder are Metal's refusals; a state
/// made without `supportIndirectCommandBuffers` and a buffer of other commands, of commands
/// that set their own pipeline state, of 32 vertex buffers or of no commands are rt's gaps;
/// the CPU's encodes, reset and copies and a buffer of a resource index are unbuilt; each is
/// counted and draws or makes nothing. On a device without
/// `VK_EXT_device_generated_commands` the make answers nil, rt's gap, which the test prints
/// and stops at.
#[test]
fn indirect_command_buffers_on_vulkan() {
let platform = RtPlatform::new();
let device = (platform.system_default_device()).expect("an rt device on the GPU it holds");
let on = OnFault::Return;
let queue = device.new_command_queue().expect("a command queue");
let made = || {
let made = queue.command_buffer(on).expect("never a raise");
made.expect("a command buffer")
};
let done = CommandBufferStatus::COMPLETED;
let (metal, gap) = (RtRefusal::Refused.code(), RtRefusal::Gap.code());
let unbuilt = Unbuilt::Icb.code();
let before = (counted(metal), counted(gap), counted(unbuilt));
let make = |desc: &IcbDesc, count: u64| {
let made = device.new_indirect_command_buffer(desc, count, 0);
made.expect("never a raise")
};
let Some(icb) = make(&icb_desc(1), 2) else {
assert_eq!(
tokens(&device),
None,
"a device of the extension made no buffer"
);
assert_eq!(counted(gap), before.1 + 1);
println!("no VK_EXT_device_generated_commands: the make answers nil, rt's gap");
return;
};
assert_eq!(icb.size(), 2);
assert_ne!(icb.gpu_resource_id(), 0);
assert_eq!(icb.resource_index(), 0);
let other = make(&icb_desc(1), 1).expect("a second buffer");
assert!(other.unique_identifier() > icb.unique_identifier());
// Draws of no index buffer, commands that set their own pipeline state, 32 vertex
// buffers and no commands: rt's gaps. A resource index: unbuilt.
let drawing = IcbDesc {
command_types: 1,
..icb_desc(1)
};
let own_states = IcbDesc {
inherit_pipeline_state: false,
..icb_desc(1)
};
let indexed = IcbDesc {
resource_index: Some(0),
..icb_desc(1)
};
for (desc, count) in [(&drawing, 2), (&own_states, 2), (&icb_desc(32), 2)] {
assert!(make(desc, count).is_none());
}
assert!(make(&icb_desc(1), 0).is_none());
assert!(make(&indexed, 2).is_none());
assert_eq!(counted(gap), before.1 + 4);
assert_eq!(counted(unbuilt), before.2 + 1);
let target = device.new_texture(
on,
&platform.texture_descriptor(&TextureDesc {
width: 4,
height: 4,
usage: 5,
..TextureDesc::default()
}),
);
let target = target.expect("never a raise").expect("a render target");
// The texels of a pass of its own that clears the target to opaque red, then `cmds`.
let drawn = |cmds| {
assert_eq!(run(&made(), &pass(&target, 2), cmds), done);
let mut texels = [0u8; 64];
target.read_pixels(&mut texels, 16);
texels
};
let every = |texel: [u8; 4]| -> [u8; 64] { std::array::from_fn(|i| texel[i % 4]) };
let (red, green, blue) = ([255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255]);
// Command 0 a green triangle over the target, command 1 a blue one.
let scene = IcbScene::new(&device, &[[0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]]);
let kernel = function(&device, ICB, "icb_encode");
let kernel = device.new_compute_pipeline_state_for_function(Some(&kernel));
let kernel = kernel.expect("a compute state").expect("a compute state");
scene.encode((&device, &made()), &kernel, &icb, 2);
let state = &icb_state(&device, "icb_vertex", true);
assert_eq!(drawn(executed(state, &icb, (0, 2))), every(blue));
assert_eq!(drawn(executed(state, &icb, (0, 1))), every(green));
assert_eq!(drawn(executed(state, &icb, (1, 1))), every(blue));
assert_eq!(drawn(executed(state, &icb, (0, 0))), every(red));
// A word no execution reads, then the ranges (0, 1) at byte 4 and (1, 1) at byte 12.
let ranges = &shared(&device, &words(&[0xeeee_eeee, 0, 1, 1, 1]));
let ranged = |offset: u64| {
vec![
RenderCmd::SetRenderPipelineState {
pipeline_state: Some(state),
},
RenderCmd::ExecuteCommandsIndirect {
indirect_commandbuffer: &icb,
indirect_range_buffer: ranges,
indirect_buffer_offset: offset,
},
]
};
assert_eq!(drawn(ranged(4)), every(green));
assert_eq!(drawn(ranged(12)), every(blue));
assert_eq!(counted(metal), before.0);
assert_eq!(counted(gap), before.1 + 4);
// Metal's refusals: a range past the commands and one past 32 bits, a range buffer's
// offset off a multiple of 4 and one 4 bytes before its end, no pipeline state set.
assert_eq!(drawn(executed(state, &icb, (1, 2))), every(red));
assert_eq!(drawn(executed(state, &icb, (u64::MAX, 2))), every(red));
assert_eq!(drawn(ranged(2)), every(red));
assert_eq!(drawn(ranged(16)), every(red));
let unset = executed(state, &icb, (0, 2)).split_off(1);
assert_eq!(drawn(unset), every(red));
assert_eq!(counted(metal), before.0 + 5);
// rt's gap: a state made without `supportIndirectCommandBuffers`.
let unflagged = &icb_state(&device, "icb_vertex", false);
assert_eq!(drawn(executed(unflagged, &icb, (0, 2))), every(red));
assert_eq!(counted(gap), before.1 + 5);
// A blit's reset of command 1, an optimize and a synchronize: command 0 draws alone.
let blit = |cmds: Vec<BlitCmd<'_, RtPlatform>>| {
let commands = made();
let encoder = commands.blit_encoder(on).expect("never a raise");
let encoder = encoder.expect("a blit encoder");
for cmd in cmds {
assert_eq!(encoder.encode(on, cmd), Ok(()));
}
assert_eq!(encoder.encode(on, BlitCmd::EndEncoding), Ok(()));
assert_eq!(commands.commit(on), Ok(()));
assert_eq!(commands.wait_until_completed(on), Ok(()));
assert_eq!(commands.status(), done);
};
blit(vec![
BlitCmd::ResetCommandsInBuffer {
buffer: &icb,
range: NsRange::new(1, 1),
},
BlitCmd::OptimizeIndirectCommandBuffer {
indirect_command_buffer: &icb,
range: NsRange::new(0, 2),
},
BlitCmd::SynchronizeResource {
resource: Some(ResourceRef::Icb(&icb)),
},
]);
assert_eq!(drawn(executed(state, &icb, (0, 2))), every(green));
assert_eq!(drawn(executed(state, &icb, (1, 1))), every(red));
// A reset past the commands: Metal's refusal. A copy between buffers: unbuilt.
blit(vec![
BlitCmd::ResetCommandsInBuffer {
buffer: &icb,
range: NsRange::new(1, 2),
},
BlitCmd::CopyIndirectCommandBuffer {
source: &icb,
source_range: NsRange::new(0, 1),
destination: &icb,
destination_index: 1,
},
]);
assert_eq!(counted(metal), before.0 + 6);
assert_eq!(counted(unbuilt), before.2 + 2);
// The kernel encodes command 1 again.
scene.encode((&device, &made()), &kernel, &icb, 2);
assert_eq!(drawn(executed(state, &icb, (0, 2))), every(blue));
// The CPU's encodes and reset: unbuilt.
assert!(matches!(icb.render_command(0), Ok(None)));
assert!(matches!(icb.compute_command(0), Ok(None)));
assert_eq!(icb.reset_with_range(0, 2), Ok(()));
assert_eq!(counted(unbuilt), before.2 + 5);
assert_eq!(drawn(executed(state, &icb, (0, 2))), every(blue));
// An execution in a compute encoder: Metal's refusal.
let commands = made();
let encoder = commands.compute_encoder(on).expect("never a raise");
let encoder = encoder.expect("a compute encoder");
let execution = ComputeCmd::ExecuteCommandsInBuffer {
indirect_command_buffer: &icb,
execution_range: NsRange::new(0, 2),
};
assert_eq!(encoder.encode(on, execution), Ok(()));
assert_eq!(encoder.encode(on, ComputeCmd::EndEncoding), Ok(()));
assert_eq!(commands.commit(on), Ok(()));
assert_eq!(commands.wait_until_completed(on), Ok(()));
assert_eq!(commands.status(), done);
assert_eq!(counted(metal), before.0 + 7);
assert_eq!(counted(gap), before.1 + 5);
}
/// The most buffer slots of a command whose state's vertex function reads all but one of them
/// and whose fragment function reads one that rt's push range holds: the slot words of the
/// state's 256-byte push range, on every device (measured on an RTX 3090 and a Radeon RX 7900
/// XTX).
const PUSHED_SLOTS: u32 = 25;
/// An execution carries each buffer slot its state's functions read below the buffer's bind
/// counts as a slot word of rt's push range, and takes a token of the device's for each and
/// three more: one of a state of more slots than the push range holds is rt's gap
/// (`IndirectCommandBuffers` of `DrawInput`), and one of more than the device's
/// `maxIndirectCommandsTokenCount` leaves is too (of `Tokens`); each draws nothing and is
/// counted. Commands of 24 to 30 slots (`icb_vertex_23` to `icb_vertex_29`, and the fragment
/// function's one), each executed on its own: those of at most [`PUSHED_SLOTS`] draw where the
/// device's tokens take them.
#[test]
fn an_execution_of_more_slots_than_rt_carries_draws_nothing_on_vulkan() {
let platform = RtPlatform::new();
let device = (platform.system_default_device()).expect("an rt device on the GPU it holds");
let on = OnFault::Return;
let queue = device.new_command_queue().expect("a command queue");
let made = || {
let made = queue.command_buffer(on).expect("never a raise");
made.expect("a command buffer")
};
let Some(tokens) = tokens(&device) else {
println!("no VK_EXT_device_generated_commands: no execution to measure");
return;
};
let gap = RtRefusal::Gap.code();
let made_icb = device.new_indirect_command_buffer(&icb_desc(29), 1, 0);
let icb = made_icb
.expect("never a raise")
.expect("a buffer of 29 vertex buffers");
let scene = IcbScene::new(&device, &[[0.0, 1.0, 0.0, 1.0]]);
let kernel = function(&device, ICB, "icb_encode_wide");
let kernel = device.new_compute_pipeline_state_for_function(Some(&kernel));
let kernel = kernel.expect("a compute state").expect("a compute state");
scene.encode((&device, &made()), &kernel, &icb, 1);
let target = device.new_texture(
on,
&platform.texture_descriptor(&TextureDesc {
width: 4,
height: 4,
usage: 5,
..TextureDesc::default()
}),
);
let target = target.expect("never a raise").expect("a render target");
let kinds = ["DrawInput", "Tokens"].map(|kind| format!("IndirectCommandBuffers-{kind}"));
let named = || (kinds.each_ref()).map(|name| crate::rt_platform::diag::gaps_named(name));
let (mut seen, mut wanted) = (Vec::new(), Vec::new());
for vertex in 23..=29u32 {
let slots = vertex + 1;
let state = icb_state(&device, &format!("icb_vertex_{vertex}"), true);
let before = (counted(gap), named());
let cmds = executed(&state, &icb, (0, 1));
assert_eq!(
run(&made(), &pass(&target, 2), cmds),
CommandBufferStatus::COMPLETED
);
let mut texels = [0u8; 64];
target.read_pixels(&mut texels, 16);
let after = named();
let drawn = texels.chunks(4).all(|texel| texel == [0, 255, 0, 255]);
let red = texels.chunks(4).all(|texel| texel == [255, 0, 0, 255]);
let kinds = [after[0] - before.1[0], after[1] - before.1[1]];
seen.push((slots, drawn, red, counted(gap) - before.0, kinds));
let pushed = slots <= PUSHED_SLOTS;
let taken = slots + 3 <= tokens;
let kinds = [u64::from(!pushed), u64::from(pushed && !taken)];
let fits = pushed && taken;
wanted.push((slots, fits, !fits, u64::from(!fits), kinds));
}
// Each: slots, drawn, nothing drawn, gaps, and gaps of DrawInput and of Tokens.
println!("{tokens} tokens: {seen:?}");
assert_eq!(seen, wanted, "{tokens} tokens");
}
}
@@ -12,7 +12,8 @@
//! (`rt-refused-metal`). So does a function made unspecialized that declares function constants,
//! as a compute state's kernel does. The display's value is its two functions and colour 0's
//! format. Its label is not rt's, and neither is its resource index, which a state answers only
//! where it supports indirect command buffers, which rt's states never do.
//! where it supports indirect command buffers: rt's commands set no pipeline state of their own
//! (`super::icb`).
//! - **A layout the value does not set is none**: the guest's bundle sends a vertex descriptor's
//! layouts of a stride other than 0, Metal's default, and an attribute of a buffer with none is
//! Metal's assertion ("references a buffer ... that has no stride"), which the translator
@@ -420,7 +421,8 @@ fn make(
}
impl RenderPipeline for RtObj<RtRenderPipeline> {
/// 0: rt makes no state for indirect command buffers.
/// 0: rt's indirect commands set no pipeline state of their own (`super::icb`), so no shader
/// reaches a state through it.
fn gpu_resource_id(&self) -> u64 {
crate::recorder::plain_resource_id(self, || 0)
}
@@ -98,8 +98,11 @@ pub enum Unbuilt {
/// Rasterization rate maps, their descriptors and layers: rt has none. A layer's creation
/// answers nil, and a descriptor keeps no layer.
RateMap,
/// Indirect command buffers, and the reservation of their resource indices (type 5): rt has
/// none. A creation answers nil.
/// What of indirect command buffers rt does not build (`super::icb`): commands the CPU
/// encodes (`indirectRenderCommandAtIndex:`, `indirectComputeCommandAtIndex:`), which answer
/// nil; a CPU reset (`resetWithRange:`), which resets nothing; a blit's copy between buffers,
/// which encodes nothing; a buffer of a resource index, which answers nil; and the
/// reservation of their resource indices (type 5), which reserves nothing.
Icb,
/// Dynamic libraries (`newDynamicLibrary:error:`): rt has none. A creation answers nil.
DynamicLibrary,
@@ -175,7 +178,7 @@ impl Unbuilt {
Unbuilt::Blit => "a colour fill, a pattern fill or a copy with blit options",
Unbuilt::RenderPass => "a render pass's memory lengths, tiles or samples",
Unbuilt::RateMap => "a rasterization rate map",
Unbuilt::Icb => "an indirect command buffer",
Unbuilt::Icb => "an indirect command buffer's CPU encode, reset, copy or index",
Unbuilt::DynamicLibrary => "a dynamic library",
Unbuilt::ResourceType => "a reservation of resource indices of another type",
Unbuilt::TessellationFactorScale => "a tessellation factor scale other than 1",
@@ -70,8 +70,6 @@ pub mod kinds {
pub enum DynamicLibrary {}
/// `id<MTLRasterizationRateMap>`.
pub enum RateMap {}
/// `id<MTLIndirectCommandBuffer>`.
pub enum Icb {}
/// `id<MTLIndirectRenderCommand>`.
pub enum IndirectRenderCommand {}
/// `id<MTLIndirectComputeCommand>`.
@@ -99,36 +97,6 @@ impl<P: Platform> function_table::VisibleFunctionTable<P> for Unmade<kinds::Visi
}
}
impl<P: Platform> icb::IndirectCommandBuffer<P> for Unmade<kinds::Icb> {
fn gpu_resource_id(&self) -> u64 {
self.unreachable()
}
fn compute_command(
&self,
_command_index: u64,
) -> RaiseResult<Option<P::IndirectComputeCommand<'_>>> {
self.unreachable()
}
fn render_command(
&self,
_command_index: u64,
) -> RaiseResult<Option<P::IndirectRenderCommand<'_>>> {
self.unreachable()
}
fn reset_with_range(&self, _location: u64, _length: u64) -> RaiseResult<()> {
self.unreachable()
}
fn resource_index(&self) -> u64 {
self.unreachable()
}
fn size(&self) -> u64 {
self.unreachable()
}
fn unique_identifier(&self) -> u64 {
self.unreachable()
}
}
impl<P: Platform> icb::IndirectRenderCommand<P> for Unmade<kinds::IndirectRenderCommand> {
fn encode(&self, _cmd: IcbRenderCmd<'_, P>) -> RaiseResult<()> {
self.unreachable()