diff --git a/crates/metal2vulkan-conformance/src/cases/primitive_type_crossings.rs b/crates/metal2vulkan-conformance/src/cases/primitive_type_crossings.rs index e1c07cd23..c00bea714 100644 --- a/crates/metal2vulkan-conformance/src/cases/primitive_type_crossings.rs +++ b/crates/metal2vulkan-conformance/src/cases/primitive_type_crossings.rs @@ -323,8 +323,8 @@ impl Case for RestartIndices { } fn allowances(&self) -> Vec { - // **Nothing is loosened.** Every draw here is the direct indexed form, which reaches no - // bounds pass, and every texel of every cell still compares exactly. + // **Nothing is loosened.** Every draw here is the direct indexed form, and every texel of + // every cell still compares exactly. // // One kind is declared over the notices site. The vertex function writes // `[[point_size]]`, which a device whose largest point is below Metal's announces at the diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 6b81b8e70..a7fa9d46d 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -6d890ed70e7680ec72ea5a129d6c3331d67564a4e73d4dd51c45fcac649a17c4 +9052663b837f14f037ccc58cd8b61c3a412416b96ce89310e5ec80bb597c6473 diff --git a/crates/metal2vulkan/src/bind/graphics.rs b/crates/metal2vulkan/src/bind/graphics.rs index 43b6cf42f..705ba3fc9 100644 --- a/crates/metal2vulkan/src/bind/graphics.rs +++ b/crates/metal2vulkan/src/bind/graphics.rs @@ -202,8 +202,7 @@ //! reads anything for it. An indexed indirect draw's counts are in GPU memory, so where the //! device lacks `robustBufferAccess2` (or the index offset is at or past the buffer's length) it //! asks for its arguments on the CPU (`indirect_needs_arguments`), and the direct draw is bounded -//! as above. Where that is the only reason, `index_bounds_pass` says the GPU index bounds pass -//! may bound it instead (`bind::IndexBoundsPass`). +//! as above. //! - **Tessellation**. A tessellation pipeline's Metal stages are its evaluation stage (the vertex //! function, whose push range, bindings, and uses name `TESSELLATION_EVALUATION`) and its //! fragment stage; its synthesized vertex and control stages bind nothing of Metal's. The control @@ -459,11 +458,6 @@ pub struct DrawCommands { /// A direct indexed draw that reads indices past its index buffer: how `draw` /// treats those index positions. `None` for every other draw. pub index_overrun: Option, - /// An indexed indirect draw asks for its arguments on the CPU (`indirect_needs_arguments`) - /// only because nothing bounds its index fetch: the consumer may record the GPU index bounds - /// pass instead of the CPU read (`IndexBoundsPass`), which draws each position past the buffer - /// at index 0 plus the base vertex. - pub index_bounds_pass: bool, /// A plan that draws each vertex amplification as a draw of its own (`BindingPlan::variant`'s /// `amplification_draws`): one entry per amplification, in order, the push writes that make the /// next draw that amplification's (its id and its view mapping's offsets, in each stage that @@ -535,7 +529,6 @@ impl Default for DrawCommands { vertex_strides: Vec::new(), uses: Vec::new(), index_overrun: None, - index_bounds_pass: false, mesh_arguments: None, object_fold: None, discards_command_buffer: false, @@ -3533,7 +3526,6 @@ fn instantiate( vertex_strides, uses, index_overrun: overrun_out, - index_bounds_pass, amplifications: amplifications_out, specialization: specialization_out, mesh_arguments: mesh_arguments_out, @@ -3879,7 +3871,6 @@ fn instantiate( }); } *indirect_needs_arguments = arguments_elsewhere || index_unbounded; - *index_bounds_pass = index_unbounded && !arguments_elsewhere; *mesh_arguments_out = mesh_arguments; *object_fold_out = object_fold; *discards_out = discards; diff --git a/crates/metal2vulkan/src/bind/graphics/tests.rs b/crates/metal2vulkan/src/bind/graphics/tests.rs index 2f63122df..d9814e569 100644 --- a/crates/metal2vulkan/src/bind/graphics/tests.rs +++ b/crates/metal2vulkan/src/bind/graphics/tests.rs @@ -764,17 +764,15 @@ fn an_unbounded_indexed_indirect_draw_reads_its_arguments() { let t = template(robust, false); let cmds = instantiate(&t, &state, &indirect(at(8))).expect("indexed"); assert_eq!(cmds.indirect_needs_arguments, !robust); - // The index bound is the only reason: the GPU pass may bound it instead. - assert_eq!(cmds.index_bounds_pass, !robust); assert_eq!(cmds.index_overrun, None); let cmds = instantiate(&t, &state, &indirect(at(64))).expect("indexed past"); - assert!(cmds.indirect_needs_arguments && cmds.index_bounds_pass); + assert!(cmds.indirect_needs_arguments); let cmds = instantiate(&t, &state, &indirect(None)).expect("indirect"); - assert!(!cmds.indirect_needs_arguments && !cmds.index_bounds_pass); - // Another reason asks for the CPU read too: the pass does not stand in for it. + assert!(!cmds.indirect_needs_arguments); + // Another reason asks for the CPU read too. let t = template(robust, true); let cmds = instantiate(&t, &state, &indirect(at(8))).expect("indexed"); - assert!(cmds.indirect_needs_arguments && !cmds.index_bounds_pass); + assert!(cmds.indirect_needs_arguments); } } @@ -2081,7 +2079,7 @@ fn mesh_draws_specialize_their_threadgroup_within_the_device() { stride: 12, } ); - assert!(!cmds.indirect_needs_arguments && !cmds.index_bounds_pass); + assert!(!cmds.indirect_needs_arguments); assert_eq!(cmds.mesh_arguments, Some(MeshArgumentsForm::Mesh)); assert_eq!( cmds.uses, diff --git a/crates/metal2vulkan/src/bind/index_bounds.rs b/crates/metal2vulkan/src/bind/index_bounds.rs deleted file mode 100644 index 2e2212780..000000000 --- a/crates/metal2vulkan/src/bind/index_bounds.rs +++ /dev/null @@ -1,738 +0,0 @@ -//! The index bounds pass of an indexed indirect draw. -//! -//! Without `robustBufferAccess2` every index a Vulkan draw fetches must lie inside the bound -//! index range (`VUID-VkDrawIndexedIndirectCommand-robustBufferAccess2-08798`), and an index -//! offset at or past the buffer's length may lie past the `VkBuffer`, where it cannot be bound. -//! Metal draws each position inside the buffer at its index and each position past it at index 0 -//! plus the base vertex (measured from offset 0). An indexed indirect draw's counts are GPU memory, -//! so where nothing else asks for its arguments on the CPU (`DrawCommands::index_bounds_pass`) the -//! consumer may bound its fetch on the GPU instead of reading them: two dispatches before the -//! render pass instance, then two indirect draws in it where Metal has one. -//! -//! - **The plan** ([`index_bounds_plan_module`], one invocation) reads Metal's -//! `MTLDrawIndexedPrimitivesIndirectArguments` and writes both draws' arguments into the draw's -//! bounds words ([`IndexBoundsPass`]). A draw whose positions all lie inside the buffer's whole -//! indices from its offset is the first draw's, over the Metal index buffer as it is bound; the -//! second draws nothing. Any other draw of indices is the second's, over its reservation in the -//! command buffer's index pool, and the first draws nothing. Exactly one of the two carries the -//! primitives, so primitive assembly sees Metal's index stream. The plan reserves the second -//! draw's bytes from the pool's counter (the pool's first word, bytes from its index region's -//! start); a draw whose indices do not fit draws nothing, and the plan sets -//! [`StatusBits::INDEX_POOL_OVERFLOW`], which the consumer reports as the command buffer's error. -//! Nothing is drawn short silently. -//! - **The fill** ([`index_bounds_fill_module`], [`IndexBoundsFillModule::LOCAL_SIZE`] invocations -//! per workgroup, dispatched indirectly with the plan's group count) writes the reservation, -//! word by word: each position's index where it lies inside the buffer's whole indices, else 0. -//! A word of 16-bit indices holds two positions of one draw (a reservation is a whole number of -//! words); a half past the draw's count is 0. -//! -//! **The bounds words** (one `u32` array of [`IndexBoundsPass::BYTES`], a storage buffer to both -//! modules and the indirect source of the dispatch and both draws): -//! -//! | Words | Written by | Contents | -//! |---|---|---| -//! | 0 to 7 | the consumer | [`IndexBoundsPass::parameters`]: the arguments' first word in the bound arguments range, the index offset's byte in the bound indices range, the whole indices from the offset (saturated to `u32`), 1 for 32-bit indices, the pool's index bytes; then zeros | -//! | 8 to 12 | the plan | the first draw's `VkDrawIndexedIndirectCommand` | -//! | 13 to 17 | the plan | the second draw's | -//! | 18 to 20 | the plan | the fill's `VkDispatchIndirectCommand` | -//! | 21 to 23 | the plan | the fill's first pool word, first Metal position, and count | -//! -//! **The pool**: [`IndexBoundsPass::POOL_HEADER_BYTES`] of header (the counter in its first word, -//! 0 before the command buffer's first plan) and then its index bytes, which the second draw binds -//! as its index buffer from the header's end. Reservations are whole words. The plan reads and -//! writes only the header's counter, and the fill writes only index bytes, so a consumer may bind -//! the plan's pool and the fill's pool as two buffers: a header whose counter all of a command -//! buffer's plans share, and one whose bytes from its own header's end hold the indices (the -//! runtime binds a counter in host-written memory and a block of device memory). -//! -//! **Bindings** (set 0, storage buffers): the plan's [`IndexBoundsPlanModule::WORDS_BINDING`], -//! `ARGUMENTS_BINDING` ([`IndexBoundsPass::arguments_range`]), `POOL_BINDING` (the whole pool) and -//! `STATUS_BINDING` (the `ExecutionStatus` buffer); the fill's -//! [`IndexBoundsFillModule::WORDS_BINDING`], `INDICES_BINDING` -//! ([`IndexBoundsPass::indices_range`], or any 4 bytes where it is `None`: nothing reads them) and -//! `POOL_BINDING`. Every read of the arguments and indices is contained (an index past the bound -//! range reads 0), so a wrongly bound range can never make a pass fault. -//! -//! **Synchronization** (consumer): the arguments' and indices' writes → `SHADER_READ` in -//! `COMPUTE_SHADER`, and the upload of the parameters, before the plan; plans one after another -//! (each reads and writes the pool's counter; one invocation each, so a barrier between them is -//! all the counter needs); the plan's writes → `INDIRECT_COMMAND_READ` in `DRAW_INDIRECT` and -//! `SHADER_READ` in `COMPUTE_SHADER` before the fill; the fill's and plan's writes → -//! `INDEX_READ` in `INDEX_INPUT` and `INDIRECT_COMMAND_READ` in `DRAW_INDIRECT` before the draws. - -use std::sync::Arc; - -use crate::bind::instantiate::{BufferRange, IndirectRef}; -use crate::bind::status::{StatusBits, StatusWord}; -use crate::budget::{Budget, Meter}; -use crate::device::requirements::Requirements; -use crate::device::Device; -use crate::error::{Error, InternalError, InternalKind}; -use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, Symbol, SyntheticBinding}; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::BResult; -use crate::spirv::ids::{GlobalId, TypeId, Value}; -use crate::spirv::ir::{ - natural_layout, AtomicOp, BinOp, ExecMode, ExecModel, IoDir, LayoutRule, MemAccess, Scope, - Semantics, StorageClass, Type, TypedModule, UnOp, -}; - -/// One indexed indirect draw's index bounds pass: what the consumer binds and uploads for the -/// plan and the fill (the module docs say how). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct IndexBoundsPass { - /// The range of the Metal indirect buffer to bind at - /// [`IndexBoundsPlanModule::ARGUMENTS_BINDING`]: from the arguments' offset aligned down to - /// `minStorageBufferOffsetAlignment` (and to 4) through their 20 bytes. - pub arguments_range: BufferRange, - /// The range of the Metal index buffer to bind at [`IndexBoundsFillModule::INDICES_BINDING`]: - /// from the index offset aligned down likewise through the whole indices inside the buffer, - /// to a whole word (`word_range`); `None` when none lies inside it from the offset (the - /// fill then reads nothing). - pub indices_range: Option, - /// The bounds words' first [`IndexBoundsPass::PARAMETER_WORDS`] words, which the consumer - /// uploads before the plan. - pub parameters: [u32; IndexBoundsPass::PARAMETER_WORDS], -} - -impl IndexBoundsPass { - /// Bytes of the bounds words. - pub const BYTES: u64 = 96; - /// The consumer's parameter words at the bounds words' start. - pub const PARAMETER_WORDS: usize = 8; - /// The pool's header: its counter, then reserved bytes; its index bytes follow, where the - /// second draw binds the pool as its index buffer. - pub const POOL_HEADER_BYTES: u64 = 16; - /// Bytes of Metal's `MTLDrawIndexedPrimitivesIndirectArguments`. - const ARGUMENT_BYTES: u64 = 20; - - /// The pass of a draw whose arguments are at `arguments`, drawing indices of `index_size` - /// bytes (2 or 4) from `index_offset` of an index buffer whose bytes end at `index_end` (its - /// length, in the same terms as the offset; its `VkBuffer` holds the bytes to `index_end` - /// rounded up to 4 there, as the padding does), with ranges bound at offsets aligned to - /// `alignment` (`minStorageBufferOffsetAlignment`) over at most `max_range` bytes - /// (`maxStorageBufferRange`), into a pool of `pool_bytes` index bytes (a multiple of 4). - /// `None` when the arguments' offset is not a multiple of 4, the index size is neither 2 nor - /// 4, the index offset is not a multiple of it, the pool's bytes are not a multiple of 4, or a - /// range overflows or exceeds `max_range`. - pub fn new( - arguments: IndirectRef, - index_size: u64, - index_offset: u64, - index_end: u64, - alignment: u64, - max_range: u32, - pool_bytes: u32, - ) -> Option { - if !arguments.offset.is_multiple_of(4) - || !matches!(index_size, 2 | 4) - || !index_offset.is_multiple_of(index_size) - || !pool_bytes.is_multiple_of(4) - { - return None; - } - let aligned = |offset: u64, end: u64| word_range(offset, end, alignment, max_range); - let arguments_end = arguments.offset.checked_add(Self::ARGUMENT_BYTES)?; - let (arguments_range, arguments_residual) = aligned(arguments.offset, arguments_end)?; - let inside = index_end.saturating_sub(index_offset) / index_size; - let (indices_range, indices_residual) = if inside == 0 { - (None, 0) - } else { - let end = index_offset.checked_add(inside.checked_mul(index_size)?)?; - let (range, residual) = aligned(index_offset, end)?; - (Some(range), residual) - }; - let mut parameters = [0; Self::PARAMETER_WORDS]; - parameters[Parameter::ArgumentsWord as usize] = - u32::try_from(arguments_residual / 4).ok()?; - parameters[Parameter::IndicesByte as usize] = u32::try_from(indices_residual).ok()?; - parameters[Parameter::Inside as usize] = u32::try_from(inside).unwrap_or(u32::MAX); - parameters[Parameter::Wide as usize] = u32::from(index_size == 4); - parameters[Parameter::PoolBytes as usize] = pool_bytes; - Some(IndexBoundsPass { - arguments_range, - indices_range, - parameters, - }) - } -} - -/// The consumer's parameter words, by index into the bounds words. -#[derive(Clone, Copy)] -enum Parameter { - ArgumentsWord = 0, - IndicesByte = 1, - Inside = 2, - Wide = 3, - PoolBytes = 4, -} - -/// The plan's words in the bounds words, by index. -#[derive(Clone, Copy)] -enum Output { - FirstDraw = 8, - SecondDraw = 13, - FillDispatch = 18, - FillPoolWord = 21, - FillStart = 22, - FillCount = 23, -} - -/// The crate-owned plan module of one device, validated like any output. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct IndexBoundsPlanModule { - /// SPIR-V 1.5 words, entry point `main`, bindings numbered as below in set 0. - pub spirv: Arc<[u32]>, - /// What the module needs from the device (within every Vulkan 1.2 device). - pub requirements: Requirements, -} - -impl IndexBoundsPlanModule { - /// Descriptor set of every binding. - pub const SET: u32 = 0; - /// The draw's bounds words, a storage buffer. - pub const WORDS_BINDING: u32 = 0; - /// The Metal indirect buffer, a storage buffer. - pub const ARGUMENTS_BINDING: u32 = 1; - /// The command buffer's index pool, a storage buffer. - pub const POOL_BINDING: u32 = 2; - /// The command buffer's `ExecutionStatus` buffer, a storage buffer. - pub const STATUS_BINDING: u32 = 3; -} - -/// The crate-owned fill module of one device, validated like any output. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct IndexBoundsFillModule { - /// SPIR-V 1.5 words, entry point `main`, bindings numbered as below in set 0. - pub spirv: Arc<[u32]>, - /// What the module needs from the device (within every Vulkan 1.2 device). - pub requirements: Requirements, -} - -impl IndexBoundsFillModule { - /// Descriptor set of every binding. - pub const SET: u32 = 0; - /// The draw's bounds words, a storage buffer. - pub const WORDS_BINDING: u32 = 0; - /// The Metal index buffer, a storage buffer. - pub const INDICES_BINDING: u32 = 1; - /// The command buffer's index pool, a storage buffer. - pub const POOL_BINDING: u32 = 2; - /// Invocations of one workgroup, along x: each writes one word of the reservation. - pub const LOCAL_SIZE: u32 = 64; -} - -/// The bounds words' binding symbol in both typed modules. -pub const WORDS: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 0, -}; -/// The plan's arguments binding symbol ([`IndexBoundsPlanModule::ARGUMENTS_BINDING`]); the -/// fill's indices binding symbol ([`IndexBoundsFillModule::INDICES_BINDING`]). -pub const SOURCE: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 1, -}; -/// The pool's binding symbol in both typed modules. -pub const POOL: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 2, -}; -/// The status buffer's binding symbol in the plan ([`IndexBoundsPlanModule::STATUS_BINDING`]). -pub const STATUS: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Synthetic(SyntheticBinding::ExecutionStatus), - index: 0, -}; - -/// A `Block { u32 words[]; }` storage buffer bound at `sym`. -fn words_buffer(b: &mut ModuleBuilder, sym: ResourceSlot, u32_: TypeId) -> BResult { - let rta = b.ty(Type::RuntimeArray { - elem: u32_, - stride: Some(4), - })?; - let layout = natural_layout(b.types(), LayoutRule::Std430, true, &[rta])?; - let block = b.ty(Type::Struct { - members: [rta].into(), - layout: Some(layout), - })?; - b.resource(sym, StorageClass::StorageBuffer, block) -} - -fn k(f: &mut FunctionBuilder<'_>, v: u32) -> BResult { - let c = f.u32_const(v)?; - f.module().const_value(c) -} - -/// Word `index` of the runtime array of `buffer`. -fn word_ptr(f: &mut FunctionBuilder<'_>, buffer: Value, index: Value) -> BResult { - let zero = k(f, 0)?; - f.access_chain(buffer, &[zero, index]) -} - -fn load_word(f: &mut FunctionBuilder<'_>, buffer: Value, index: u32) -> BResult { - let i = k(f, index)?; - let p = word_ptr(f, buffer, i)?; - f.load(p, MemAccess::default()) -} - -fn store_word(f: &mut FunctionBuilder<'_>, buffer: Value, index: Value, v: Value) -> BResult<()> { - let p = word_ptr(f, buffer, index)?; - f.store(p, v, MemAccess::default()) -} - -/// A draw's bounds words: the words buffer, and where a run's slot starts in it (`None` for a -/// pass's own words, from word 0). -#[derive(Clone, Copy)] -struct Words { - buffer: Value, - slot: Option, -} - -impl Words { - /// The index into the buffer of the draw's word `index`. - fn at(self, f: &mut FunctionBuilder<'_>, index: u32) -> BResult { - let i = k(f, index)?; - match self.slot { - None => Ok(i), - Some(first) => f.binary(BinOp::IAdd, first, i), - } - } - - /// The draw's word `index`. - fn load(self, f: &mut FunctionBuilder<'_>, index: u32) -> BResult { - let i = self.at(f, index)?; - let p = word_ptr(f, self.buffer, i)?; - f.load(p, MemAccess::default()) - } - - /// Store `v` as the draw's word `index`. - fn store(self, f: &mut FunctionBuilder<'_>, index: u32, v: Value) -> BResult<()> { - let i = self.at(f, index)?; - store_word(f, self.buffer, i, v) - } -} - -/// The range of a buffer that a pass binds as a storage buffer of words to read the bytes from -/// `offset` to `end` (in the `VkBuffer`'s offsets), and `offset`'s byte in it: from `offset` -/// aligned down to `alignment` (`minStorageBufferOffsetAlignment`, and to 4) through `end` -/// rounded up to a whole word, which the `VkBuffer` holds (the padding). A range of no whole words -/// would leave its last bytes out of every word the pass reads (`OpArrayLength` rounds down), so -/// the last index of an odd count of 16-bit indices from a multiple of 4, or of an even count from -/// 2 past one, would read 0; the bytes past `end` in the last word are never taken as an index. -/// `None` where the range overflows or exceeds `max_range` (`maxStorageBufferRange`). -pub(crate) fn word_range( - offset: u64, - end: u64, - alignment: u64, - max_range: u32, -) -> Option<(BufferRange, u64)> { - let a = alignment.max(4); - let start = offset - offset % a; - let range = end.checked_next_multiple_of(4)?.checked_sub(start)?; - if range > u64::from(max_range) { - return None; - } - Some(( - BufferRange { - offset: start, - range, - }, - offset - start, - )) -} - -/// Word `index` of `buffer` where it lies inside the buffer's bound range, else 0 (contained). -fn contained_word(f: &mut FunctionBuilder<'_>, buffer: Value, index: Value) -> BResult { - let zero = k(f, 0)?; - let len = f.array_length(buffer, 0)?; - let inb = f.binary(BinOp::ULessThan, index, len)?; - let safe = f.select(inb, index, zero)?; - let p = word_ptr(f, buffer, safe)?; - let loaded = f.load(p, MemAccess::default())?; - f.select(inb, loaded, zero) -} - -/// The plan as a typed module, before serialization: the module [`index_bounds_plan_module`] -/// serializes, which the CPU interpreter runs. Its bindings are the symbols [`WORDS`], [`SOURCE`] -/// (the arguments), [`POOL`], and [`STATUS`]. -pub fn plan_typed_module() -> BResult { - plan_module_of(false) -} - -/// The plan of a run of draws (`run`) or of one draw, as a typed module: one invocation, which -/// plans a run's draws one after another, each from its slot (`run::IndexBoundsRun`). -pub(crate) fn plan_module_of(run: bool) -> BResult { - let mut b = ModuleBuilder::new(); - let u32_ = b.ty(Type::Int { - width: 32, - signed: false, - })?; - let words = words_buffer(&mut b, WORDS, u32_)?; - let arguments = words_buffer(&mut b, SOURCE, u32_)?; - let pool = words_buffer(&mut b, POOL, u32_)?; - let status = words_buffer(&mut b, STATUS, u32_)?; - let void = b.ty(Type::Void)?; - let mut f = b.function(void)?; - let words = f.module().global_value(words)?; - let arguments = f.module().global_value(arguments)?; - let pool = f.module().global_value(pool)?; - let status = f.module().global_value(status)?; - let sources = (arguments, pool, status); - match run { - false => plan_draw( - &mut f, - Words { - buffer: words, - slot: None, - }, - sources, - )?, - true => run::plan_run(&mut f, u32_, words, sources)?, - } - f.ret(None)?; - let id = f.finish()?; - b.entry( - ExecModel::GLCompute, - id, - vec![ExecMode::LocalSize { x: 1, y: 1, z: 1 }], - )?; - b.finalize() -} - -/// The plan of the draw whose bounds words are `words`, over the arguments, pool and status. -fn plan_draw( - f: &mut FunctionBuilder<'_>, - words: Words, - (arguments, pool, status): (Value, Value, Value), -) -> BResult<()> { - let zero = k(f, 0)?; - let one = k(f, 1)?; - let two = k(f, 2)?; - let three = k(f, 3)?; - let four = k(f, 4)?; - - let first = words.load(f, Parameter::ArgumentsWord as u32)?; - let inside = words.load(f, Parameter::Inside as u32)?; - let wide = words.load(f, Parameter::Wide as u32)?; - let pool_bytes = words.load(f, Parameter::PoolBytes as u32)?; - // Metal's arguments: indexCount, instanceCount, indexStart, baseVertex, baseInstance. - let mut argument = Vec::with_capacity(5); - for i in 0..5 { - let i = k(f, i)?; - let index = f.binary(BinOp::IAdd, first, i)?; - argument.push(contained_word(f, arguments, index)?); - } - let (count, instances, start, base, base_instance) = ( - argument[0], - argument[1], - argument[2], - argument[3], - argument[4], - ); - - // Inside: every position from `start` lies among the whole indices from the offset. - let fits_count = f.binary(BinOp::ULessThanEqual, count, inside)?; - let room_inside = f.binary(BinOp::ISub, inside, count)?; - let starts_inside = f.binary(BinOp::ULessThanEqual, start, room_inside)?; - let in_range = f.binary(BinOp::LogicalAnd, fits_count, starts_inside)?; - let not_in_range = f.unary(UnOp::LogicalNot, in_range)?; - let any = f.binary(BinOp::UGreaterThan, count, zero)?; - let over = f.binary(BinOp::LogicalAnd, not_in_range, any)?; - - // The reservation, in bytes from the pool's index region (the counter never passes its size). - let is_wide = f.binary(BinOp::INotEqual, wide, zero)?; - let size = f.select(is_wide, four, two)?; - let counter_index = zero; - let counter_ptr = word_ptr(f, pool, counter_index)?; - let reserved = f.load(counter_ptr, MemAccess::default())?; - let room = f.binary(BinOp::ISub, pool_bytes, reserved)?; - let room_indices = f.binary(BinOp::UDiv, room, size)?; - let fits_pool = f.binary(BinOp::ULessThanEqual, count, room_indices)?; - let place = f.binary(BinOp::LogicalAnd, over, fits_pool)?; - let not_fits = f.unary(UnOp::LogicalNot, fits_pool)?; - let overflow = f.binary(BinOp::LogicalAnd, over, not_fits)?; - // Whole words: `count * size` rounded up to 4 (no overflow where it fits the pool). - let index_bytes = f.binary(BinOp::IMul, count, size)?; - let padded = f.binary(BinOp::IAdd, index_bytes, three)?; - let word_count = f.binary(BinOp::ShiftRightLogical, padded, two)?; - let taken = f.binary(BinOp::ShiftLeftLogical, word_count, two)?; - let advanced = f.binary(BinOp::IAdd, reserved, taken)?; - let counter = f.select(place, advanced, reserved)?; - f.store(counter_ptr, counter, MemAccess::default())?; - - // The first draw: Metal's where every position lies inside, else none. - let first_count = f.select(in_range, count, zero)?; - let first_start = f.select(in_range, start, zero)?; - // The second: the reservation where it was placed, else none. - let second_count = f.select(place, count, zero)?; - let reserved_index = f.binary(BinOp::UDiv, reserved, size)?; - let second_start = f.select(place, reserved_index, zero)?; - for (at, draw_count, draw_start) in [ - (Output::FirstDraw as u32, first_count, first_start), - (Output::SecondDraw as u32, second_count, second_start), - ] { - for (i, v) in [draw_count, instances, draw_start, base, base_instance] - .into_iter() - .enumerate() - { - words.store(f, at + i as u32, v)?; - } - } - // The fill: a workgroup per LOCAL_SIZE words of the reservation. - let fill_words = f.select(place, word_count, zero)?; - let local = k(f, IndexBoundsFillModule::LOCAL_SIZE - 1)?; - let rounded = f.binary(BinOp::IAdd, fill_words, local)?; - let local_size = k(f, IndexBoundsFillModule::LOCAL_SIZE)?; - let groups = f.binary(BinOp::UDiv, rounded, local_size)?; - let reserved_word = f.binary(BinOp::ShiftRightLogical, reserved, two)?; - let header_words = k(f, (IndexBoundsPass::POOL_HEADER_BYTES / 4) as u32)?; - let pool_word = f.binary(BinOp::IAdd, header_words, reserved_word)?; - for (at, v) in [ - (Output::FillDispatch as u32, groups), - (Output::FillDispatch as u32 + 1, one), - (Output::FillDispatch as u32 + 2, one), - (Output::FillPoolWord as u32, pool_word), - (Output::FillStart as u32, start), - (Output::FillCount as u32, second_count), - ] { - words.store(f, at, v)?; - } - // A draw of indices the pool cannot hold draws nothing and says so. - let word = k(f, StatusWord::Status.index())?; - let bit = k(f, StatusBits::INDEX_POOL_OVERFLOW.0)?; - let then: ArmFn<'_, ()> = Box::new(move |fb, _| { - let p = word_ptr(fb, status, word)?; - fb.atomic(AtomicOp::Or, p, Scope::Device, Semantics::RELAXED, bit)?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - f.if_(&mut (), overflow, then, None)?; - Ok(()) -} - -/// The fill as a typed module, before serialization: the module [`index_bounds_fill_module`] -/// serializes, which the CPU interpreter runs. Its bindings are the symbols [`WORDS`], [`SOURCE`] -/// (the indices), and [`POOL`]. -pub fn fill_typed_module() -> BResult { - fill_module_of(false) -} - -/// The fill of a run of draws (`run`) or of one draw, as a typed module: a run's workgroup fills -/// its part of the draw whose fill groups hold it (`run::IndexBoundsRun`). -pub(crate) fn fill_module_of(run: bool) -> BResult { - let mut b = ModuleBuilder::new(); - let u32_ = b.ty(Type::Int { - width: 32, - signed: false, - })?; - let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; - let words = words_buffer(&mut b, WORDS, u32_)?; - let indices = words_buffer(&mut b, SOURCE, u32_)?; - let pool = words_buffer(&mut b, POOL, u32_)?; - let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?; - let void = b.ty(Type::Void)?; - let mut f = b.function(void)?; - let words = f.module().global_value(words)?; - let indices = f.module().global_value(indices)?; - let pool = f.module().global_value(pool)?; - let invocation = f.module().global_value(invocation)?; - let invocation = f.load(invocation, MemAccess::default())?; - let w = f.composite_extract(invocation, &[0])?; - let row = f.composite_extract(invocation, &[1])?; - match run { - false => fill_draw( - &mut f, - Words { - buffer: words, - slot: None, - }, - (indices, pool), - w, - )?, - true => run::fill_run(&mut f, u32_, words, (indices, pool), (w, row))?, - } - f.ret(None)?; - let id = f.finish()?; - b.entry( - ExecModel::GLCompute, - id, - vec![ExecMode::LocalSize { - x: IndexBoundsFillModule::LOCAL_SIZE, - y: 1, - z: 1, - }], - )?; - b.finalize() -} - -/// The fill of word `w` of the reservation of the draw whose bounds words are `words`, from the -/// indices into the pool. -fn fill_draw( - f: &mut FunctionBuilder<'_>, - words: Words, - (indices, pool): (Value, Value), - w: Value, -) -> BResult<()> { - let zero = k(f, 0)?; - let one = k(f, 1)?; - let sixteen = k(f, 16)?; - - let first_byte = words.load(f, Parameter::IndicesByte as u32)?; - let inside = words.load(f, Parameter::Inside as u32)?; - let wide = words.load(f, Parameter::Wide as u32)?; - let pool_word = words.load(f, Output::FillPoolWord as u32)?; - let start = words.load(f, Output::FillStart as u32)?; - let count = words.load(f, Output::FillCount as u32)?; - let is_wide = f.binary(BinOp::INotEqual, wide, zero)?; - // Words of the reservation: one per 32-bit index, one per two 16-bit ones. - let plus_one = f.binary(BinOp::IAdd, count, one)?; - let halves = f.binary(BinOp::ShiftRightLogical, plus_one, one)?; - let word_count = f.select(is_wide, count, halves)?; - let listed = f.binary(BinOp::ULessThan, w, word_count)?; - - // The index at Metal position `p`, where it lies inside the whole indices (and `p` did not - // wrap past `start`), else 0; 4 bytes each where `wide`, else 2. - let fetch = move |f: &mut FunctionBuilder<'_>, p: Value, wide: bool| -> BResult { - let zero = k(f, 0)?; - let unwrapped = f.binary(BinOp::UGreaterThanEqual, p, start)?; - let below = f.binary(BinOp::ULessThan, p, inside)?; - let valid = f.binary(BinOp::LogicalAnd, unwrapped, below)?; - let size_shift = k(f, if wide { 2 } else { 1 })?; - let offset = f.binary(BinOp::ShiftLeftLogical, p, size_shift)?; - let byte = f.binary(BinOp::IAdd, first_byte, offset)?; - let two = k(f, 2)?; - let word = f.binary(BinOp::ShiftRightLogical, byte, two)?; - let safe = f.select(valid, word, zero)?; - let loaded = contained_word(f, indices, safe)?; - let value = if wide { - loaded - } else { - let three = k(f, 3)?; - let half = f.binary(BinOp::BitwiseAnd, byte, two)?; - let shift = f.binary(BinOp::ShiftLeftLogical, half, three)?; - let shifted = f.binary(BinOp::ShiftRightLogical, loaded, shift)?; - let mask = k(f, 0xFFFF)?; - f.binary(BinOp::BitwiseAnd, shifted, mask)? - }; - f.select(valid, value, zero) - }; - let fill: ArmFn<'_, ()> = Box::new(move |f, _| { - // 32-bit: position start + w. - let p32 = f.binary(BinOp::IAdd, start, w)?; - let v32 = fetch(f, p32, true)?; - // 16-bit: positions start + 2w and the next, the second past the count 0. - let twice = f.binary(BinOp::ShiftLeftLogical, w, one)?; - let lo_p = f.binary(BinOp::IAdd, start, twice)?; - let hi_p = f.binary(BinOp::IAdd, lo_p, one)?; - let lo = fetch(f, lo_p, false)?; - let hi = fetch(f, hi_p, false)?; - let hi_position = f.binary(BinOp::IAdd, twice, one)?; - let counted = f.binary(BinOp::ULessThan, hi_position, count)?; - let hi = f.select(counted, hi, zero)?; - let high = f.binary(BinOp::ShiftLeftLogical, hi, sixteen)?; - let v16 = f.binary(BinOp::BitwiseOr, lo, high)?; - let v = f.select(is_wide, v32, v16)?; - let at = f.binary(BinOp::IAdd, pool_word, w)?; - let len = f.array_length(pool, 0)?; - let inb = f.binary(BinOp::ULessThan, at, len)?; - let write: ArmFn<'_, ()> = Box::new(move |f, _| { - store_word(f, pool, at, v)?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - f.if_(&mut (), inb, write, None)?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - f.if_(&mut (), listed, fill, None)?; - Ok(()) -} - -/// The fixed binding numbers of the plan's symbols. -fn plan_binding_of(sym: &Symbol) -> Option { - match sym { - Symbol::DescriptorSet(_) => Some(IndexBoundsPlanModule::SET), - Symbol::Binding(s) if *s == WORDS => Some(IndexBoundsPlanModule::WORDS_BINDING), - Symbol::Binding(s) if *s == SOURCE => Some(IndexBoundsPlanModule::ARGUMENTS_BINDING), - Symbol::Binding(s) if *s == POOL => Some(IndexBoundsPlanModule::POOL_BINDING), - Symbol::Binding(s) if *s == STATUS => Some(IndexBoundsPlanModule::STATUS_BINDING), - _ => None, - } -} - -/// The fixed binding numbers of the fill's symbols. -fn fill_binding_of(sym: &Symbol) -> Option { - match sym { - Symbol::DescriptorSet(_) => Some(IndexBoundsFillModule::SET), - Symbol::Binding(s) if *s == WORDS => Some(IndexBoundsFillModule::WORDS_BINDING), - Symbol::Binding(s) if *s == SOURCE => Some(IndexBoundsFillModule::INDICES_BINDING), - Symbol::Binding(s) if *s == POOL => Some(IndexBoundsFillModule::POOL_BINDING), - _ => None, - } -} - -/// `m` checked by the owned verifier against `device`'s profile (requirements included), -/// serialized, and numbered with `binding_of`; `what` names it in an internal error. -pub(crate) fn finished( - device: &Device, - m: TypedModule, - binding_of: fn(&Symbol) -> Option, - what: &str, -) -> Result<(Arc<[u32]>, Requirements), Error> { - let profile = device.profile(); - let mut meter = Meter::new(&Budget::default()); - crate::spirv::verify::verify(&m, profile, &mut meter)?; - let r = crate::spirv::serialize::serialize(m)?; - profile.check(&r.requirements).map_err(|c| { - Error::Internal(InternalError::new( - InternalKind::RequirementsExceedProfile, - format!("{what} needs {c:?}"), - )) - })?; - let words = crate::spirv::serialize::relocate(&r, &binding_of)?; - Ok((words.into(), r.requirements)) -} - -/// The index bounds plan module of `device`: built with the typed builder, verified, serialized, -/// and numbered with the fixed bindings of [`IndexBoundsPlanModule`]. -pub fn index_bounds_plan_module(device: &Device) -> Result { - let (spirv, requirements) = finished( - device, - plan_typed_module()?, - plan_binding_of, - "the index bounds plan", - )?; - Ok(IndexBoundsPlanModule { - spirv, - requirements, - }) -} - -/// The index bounds fill module of `device`: built with the typed builder, verified, serialized, -/// and numbered with the fixed bindings of [`IndexBoundsFillModule`]. -pub fn index_bounds_fill_module(device: &Device) -> Result { - let (spirv, requirements) = finished( - device, - fill_typed_module()?, - fill_binding_of, - "the index bounds fill", - )?; - Ok(IndexBoundsFillModule { - spirv, - requirements, - }) -} - -mod run; -pub use run::{ - index_bounds_fill_run_module, index_bounds_plan_run_module, BoundsRunDraw, IndexBoundsRun, -}; - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/bind/index_bounds/run.rs b/crates/metal2vulkan/src/bind/index_bounds/run.rs deleted file mode 100644 index f875e3945..000000000 --- a/crates/metal2vulkan/src/bind/index_bounds/run.rs +++ /dev/null @@ -1,365 +0,0 @@ -//! A run of the index bounds pass: indexed indirect draws over one arguments buffer and one index -//! buffer, planned by one dispatch of one invocation and filled by one dispatch for all of them, -//! where a draw's own pass takes two dispatches between three barriers. Each draw's plan and fill -//! are its own pass's, over its slot of the run's words, so its two draws and its reservation are -//! the ones its own pass makes, the plans reserving one after another as passes recorded in turn -//! do. -//! -//! - **The words** ([`IndexBoundsRun::words`], at both modules' `WORDS_BINDING`): -//! [`IndexBoundsRun::HEADER_WORDS`] words of header, then one slot of -//! [`IndexBoundsRun::SLOT_WORDS`] words per draw. -//! -//! | Header word | Written by | Contents | -//! |---|---|---| -//! | 0 | the consumer | the run's draws | -//! | 1 to 3 | the plan | the fill's `VkDispatchIndirectCommand` ([`IndexBoundsRun::DISPATCH_OFFSET`]): the run's fill workgroups, at most word 4's along x and as few along y as hold them | -//! | 4 | the consumer | the most workgroups of a dispatch along x (`maxComputeWorkGroupCount[0]`) | -//! | 5 to 7 | nobody | zero | -//! -//! A slot's words 0 to 23 are a pass's bounds words (the parent module's table), its two draws -//! at its words 8 and 13; its word -//! 24, which the plan writes, is the draw's first fill workgroup (the fill workgroups of the -//! draws before it). -//! - **The plan** ([`index_bounds_plan_run_module`]) plans each draw in turn, then writes the -//! fill's dispatch; **the fill** ([`index_bounds_fill_run_module`]) finds its workgroup's draw -//! (the last whose first fill workgroup is at or before it; workgroup `(x, y)` is the run's -//! `y · width + x`, `width` the dispatch's along x) and fills its words. The draws' fill -//! workgroups summed may pass what one dispatch takes along x where each draw's alone does not, -//! so the dispatch spreads them over y; a workgroup past the last draw's fills nothing. -//! - **Bindings**: a pass's, the arguments and the indices the run's bytes -//! ([`IndexBoundsRun::arguments_range`], [`IndexBoundsRun::indices_range`]), so one binding -//! serves every draw. -//! - **Synchronization** (consumer): a pass's, the run's plan and fill in place of a pass's. - -use super::{ - fill_binding_of, fill_draw, fill_module_of, finished, k, load_word, plan_binding_of, plan_draw, - plan_module_of, store_word, word_ptr, word_range, IndexBoundsFillModule, IndexBoundsPass, - IndexBoundsPlanModule, Output, Parameter, Words, -}; -use crate::bind::index_rewrite::{for_range, when}; -use crate::bind::instantiate::{BufferRange, IndirectRef}; -use crate::device::Device; -use crate::error::Error; -use crate::spirv::builder::FunctionBuilder; -use crate::spirv::error::BResult; -use crate::spirv::ids::{TypeId, Value}; -use crate::spirv::ir::{BinOp, MemAccess}; - -/// A run of indexed indirect draws of the index bounds pass (the module docs). -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct IndexBoundsRun { - /// The bound arguments bytes. - arguments: BufferRange, - /// The bound index bytes, and their end. - indices: Option<(BufferRange, u64)>, - alignment: u64, - max_range: u32, - /// The most workgroups of a dispatch along x. - max_groups: u32, - pool_bytes: u32, - /// Each draw's slot. - slots: Vec<[u32; IndexBoundsRun::SLOT_WORDS as usize]>, -} - -/// One draw of a run: where its Metal arguments lie (in the bound arguments buffer's offsets), -/// its index size (2 or 4), its index offset, and the end of the bytes its fetch reads (in the -/// bound index buffer's offsets). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct BoundsRunDraw { - /// The offset of the draw's `MTLDrawIndexedPrimitivesIndirectArguments`. - pub arguments_offset: u64, - /// The draw's index size in bytes. - pub index_size: u64, - /// The draw's index offset: a multiple of its index size. - pub index_offset: u64, - /// Where the draw's fetch stops reading bytes: a position from there on reads index 0. - pub index_end: u64, -} - -/// A slot's word past a pass's bounds words: the draw's first fill workgroup. -const FIRST_GROUP: u32 = 24; - -impl IndexBoundsRun { - /// Words of the header. - pub const HEADER_WORDS: u32 = 8; - /// Words of a draw's slot: a pass's bounds words and the draw's first fill workgroup, - /// rounded up to 16 bytes. - pub const SLOT_WORDS: u32 = 28; - /// Bytes of a draw's slot. - pub const SLOT_BYTES: u64 = 4 * Self::SLOT_WORDS as u64; - /// The fill's `VkDispatchIndirectCommand` in the words. - pub const DISPATCH_OFFSET: u64 = 4; - - /// An empty run of draws whose arguments lie in the bytes from `arguments_start` to - /// `arguments_end` of a buffer, and with `indices` the bytes of an index buffer it binds - /// (`None` where none lies inside it), each bound at an offset aligned to `alignment` - /// (`minStorageBufferOffsetAlignment`) over at most `max_range` bytes - /// (`maxStorageBufferRange`), into a pool of `pool_bytes` index bytes, its fill dispatched - /// over at most `max_groups` workgroups along x (`maxComputeWorkGroupCount[0]`). `None` where - /// the arguments' bytes are none, where bytes are past `max_range`, and where `max_groups` is - /// 0. - pub fn new( - (arguments_start, arguments_end): (u64, u64), - indices: Option<(u64, u64)>, - (alignment, max_range, max_groups): (u64, u32, u32), - pool_bytes: u32, - ) -> Option { - if arguments_end <= arguments_start || max_groups == 0 { - return None; - } - let (arguments, _) = word_range(arguments_start, arguments_end, alignment, max_range)?; - let indices = match indices { - Some((start, end)) if end > start => { - let (range, _) = word_range(start, end, alignment, max_range)?; - Some((range, range.offset + range.range)) - } - _ => None, - }; - Some(IndexBoundsRun { - arguments, - indices, - alignment, - max_range, - max_groups, - pool_bytes, - slots: Vec::new(), - }) - } - - /// Add `draw` to the run: its slot. `None` where the run cannot take it, and is as before: - /// where its own pass would not be made ([`IndexBoundsPass::new`]), and where its arguments or - /// the indices it reads lie outside the run's bound bytes. - pub fn push(&mut self, draw: BoundsRunDraw) -> Option { - let slot = u32::try_from(self.slots.len()).ok()?; - let pass = IndexBoundsPass::new( - IndirectRef::new(0, draw.arguments_offset), - draw.index_size, - draw.index_offset, - draw.index_end, - self.alignment, - self.max_range, - self.pool_bytes, - )?; - let mut parameters = pass.parameters; - // Its arguments and indices within the run's bound bytes: their words there. - let arguments_end = draw.arguments_offset.checked_add(20)?; - if draw.arguments_offset < self.arguments.offset - || arguments_end > self.arguments.offset + self.arguments.range - { - return None; - } - parameters[Parameter::ArgumentsWord as usize] = - u32::try_from((draw.arguments_offset - self.arguments.offset) / 4).ok()?; - if pass.indices_range.is_some() { - let inside = u64::from(parameters[Parameter::Inside as usize]); - let end = draw - .index_offset - .checked_add(inside.checked_mul(draw.index_size)?)?; - let (range, bound_end) = self.indices?; - if draw.index_offset < range.offset || end > bound_end { - return None; - } - parameters[Parameter::IndicesByte as usize] = - u32::try_from(draw.index_offset - range.offset).ok()?; - } - let mut words = [0; Self::SLOT_WORDS as usize]; - words[..IndexBoundsPass::PARAMETER_WORDS].copy_from_slice(¶meters); - self.slots.push(words); - Some(slot) - } - - /// The run's draws. - pub fn len(&self) -> usize { - self.slots.len() - } - - /// Whether the run has no draw. - pub fn is_empty(&self) -> bool { - self.slots.is_empty() - } - - /// The range of the indirect buffer to bind at [`IndexBoundsPlanModule::ARGUMENTS_BINDING`]. - pub fn arguments_range(&self) -> BufferRange { - self.arguments - } - - /// The range of the index buffer to bind at [`IndexBoundsFillModule::INDICES_BINDING`]: the - /// bytes [`new`](Self::new) names, aligned down, through a whole word; `None` where they are - /// none (the fill then reads nothing). - pub fn indices_range(&self) -> Option { - self.indices.map(|(range, _)| range) - } - - /// The words to upload: the header, then each draw's slot in turn. - pub fn words(&self) -> Vec { - let mut header = [0; Self::HEADER_WORDS as usize]; - header[0] = self.slots.len() as u32; - header[4] = self.max_groups; - header - .iter() - .chain(self.slots.iter().flatten()) - .flat_map(|w| w.to_le_bytes()) - .collect() - } -} - -/// The first word of the slot of draw `d`. -fn slot_word(f: &mut FunctionBuilder<'_>, d: Value) -> BResult { - let per = k(f, IndexBoundsRun::SLOT_WORDS)?; - let header = k(f, IndexBoundsRun::HEADER_WORDS)?; - let at = f.binary(BinOp::IMul, d, per)?; - f.binary(BinOp::IAdd, header, at) -} - -/// The plan of a run: each draw's plan in turn over its slot, each draw's first fill workgroup -/// the fill workgroups before it, then the fill's dispatch of all of them. -pub(super) fn plan_run( - f: &mut FunctionBuilder<'_>, - u32_: TypeId, - words: Value, - sources: (Value, Value, Value), -) -> BResult<()> { - let zero = k(f, 0)?; - let one = k(f, 1)?; - let draws = load_word(f, words, 0)?; - let total_var = f.local_var(u32_, None)?; - let total = f.var_ptr(total_var)?; - f.store(total, zero, MemAccess::default())?; - for_range(f, u32_, (zero, draws, one), move |f, d| { - let first = slot_word(f, d)?; - let slot = Words { - buffer: words, - slot: Some(first), - }; - plan_draw(f, slot, sources)?; - let groups = slot.load(f, Output::FillDispatch as u32)?; - let before = f.load(total, MemAccess::default())?; - slot.store(f, FIRST_GROUP, before)?; - let after = f.binary(BinOp::IAdd, before, groups)?; - f.store(total, after, MemAccess::default()) - })?; - // As few workgroups along y as hold them at most the widest along x, then as few along x - // as they need: none of either where there are none. - let total = f.load(total, MemAccess::default())?; - let widest = load_word(f, words, 4)?; - let rows = divided_up(f, total, widest)?; - let some = f.binary(BinOp::ULessThan, zero, rows)?; - let divisor = f.select(some, rows, one)?; - let width = divided_up(f, total, divisor)?; - for (at, v) in [(1, width), (2, rows), (3, one)] { - let at = k(f, at)?; - store_word(f, words, at, v)?; - } - Ok(()) -} - -/// `n / d` rounded up, for `d` above 0: without `n + d - 1`, which a `u32` may not hold. -fn divided_up(f: &mut FunctionBuilder<'_>, n: Value, d: Value) -> BResult { - let zero = k(f, 0)?; - let one = k(f, 1)?; - let whole = f.binary(BinOp::UDiv, n, d)?; - let rest = f.binary(BinOp::UMod, n, d)?; - let partial = f.binary(BinOp::INotEqual, rest, zero)?; - let extra = f.select(partial, one, zero)?; - f.binary(BinOp::IAdd, whole, extra) -} - -/// The fill of a run at global invocation `(global, row)`: its workgroup's draw, the last whose -/// first fill workgroup is at or before it (the first's being 0), fills its word. Workgroup -/// `(x, row)` is the run's `row · width + x`, `width` the dispatch's workgroups along x. -pub(super) fn fill_run( - f: &mut FunctionBuilder<'_>, - u32_: TypeId, - words: Value, - sources: (Value, Value), - (global, row): (Value, Value), -) -> BResult<()> { - let zero = k(f, 0)?; - let one = k(f, 1)?; - let local = k(f, IndexBoundsFillModule::LOCAL_SIZE)?; - let column = f.binary(BinOp::UDiv, global, local)?; - let width = load_word(f, words, 1)?; - let before = f.binary(BinOp::IMul, row, width)?; - let group = f.binary(BinOp::IAdd, before, column)?; - let lin = f.binary(BinOp::UMod, global, local)?; - let draws = load_word(f, words, 0)?; - // Each step halves `[lo, hi)`; 32 steps end every search a `u32` counts. - let lo_var = f.local_var(u32_, None)?; - let lo = f.var_ptr(lo_var)?; - f.store(lo, zero, MemAccess::default())?; - let hi_var = f.local_var(u32_, None)?; - let hi = f.var_ptr(hi_var)?; - f.store(hi, draws, MemAccess::default())?; - let steps = k(f, 32)?; - for_range(f, u32_, (zero, steps, one), move |f, _| { - let l = f.load(lo, MemAccess::default())?; - let h = f.load(hi, MemAccess::default())?; - let span = f.binary(BinOp::ISub, h, l)?; - let one = k(f, 1)?; - let wide = f.binary(BinOp::UGreaterThan, span, one)?; - when(f, wide, move |f| { - let sum = f.binary(BinOp::IAdd, l, h)?; - let one = k(f, 1)?; - let mid = f.binary(BinOp::ShiftRightLogical, sum, one)?; - let first = slot_word(f, mid)?; - let at = k(f, FIRST_GROUP)?; - let at = f.binary(BinOp::IAdd, first, at)?; - let p = word_ptr(f, words, at)?; - let first_group = f.load(p, MemAccess::default())?; - let before = f.binary(BinOp::ULessThanEqual, first_group, group)?; - let l2 = f.select(before, mid, l)?; - let h2 = f.select(before, h, mid)?; - f.store(lo, l2, MemAccess::default())?; - f.store(hi, h2, MemAccess::default()) - }) - })?; - let any = f.binary(BinOp::ULessThan, zero, draws)?; - when(f, any, move |f| { - let found = f.load(lo, MemAccess::default())?; - let first = slot_word(f, found)?; - let slot = Words { - buffer: words, - slot: Some(first), - }; - let first_group = slot.load(f, FIRST_GROUP)?; - let local = k(f, IndexBoundsFillModule::LOCAL_SIZE)?; - let groups_in = f.binary(BinOp::ISub, group, first_group)?; - let w = f.binary(BinOp::IMul, groups_in, local)?; - let w = f.binary(BinOp::IAdd, w, lin)?; - fill_draw(f, slot, sources, w) - }) -} - -/// The index bounds plan module of a run ([`IndexBoundsRun`]) for `device`, as -/// [`index_bounds_plan_module`](super::index_bounds_plan_module)'s is made, with its bindings. -pub fn index_bounds_plan_run_module(device: &Device) -> Result { - let (spirv, requirements) = finished( - device, - plan_module_of(true)?, - plan_binding_of, - "the index bounds plan run", - )?; - Ok(IndexBoundsPlanModule { - spirv, - requirements, - }) -} - -/// The index bounds fill module of a run ([`IndexBoundsRun`]) for `device`, as -/// [`index_bounds_fill_module`](super::index_bounds_fill_module)'s is made, with its bindings, -/// dispatched indirectly from the words' [`IndexBoundsRun::DISPATCH_OFFSET`]. -pub fn index_bounds_fill_run_module(device: &Device) -> Result { - let (spirv, requirements) = finished( - device, - fill_module_of(true)?, - fill_binding_of, - "the index bounds fill run", - )?; - Ok(IndexBoundsFillModule { - spirv, - requirements, - }) -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/bind/index_bounds/run/tests.rs b/crates/metal2vulkan/src/bind/index_bounds/run/tests.rs deleted file mode 100644 index 10c88be50..000000000 --- a/crates/metal2vulkan/src/bind/index_bounds/run/tests.rs +++ /dev/null @@ -1,309 +0,0 @@ -//! A run of the index bounds pass: both run modules valid on every committed profile (L3, -//! `G-val`), and, on the CPU interpreter, a run's one plan and one fill leave each draw the two -//! draws, the pool and the status its own pass leaves when the passes record one after another: -//! draws inside the buffer, past it, from an offset past it, of no position, and past the pool's -//! room, of either index size, in either invocation order; and a run refuses what it cannot take. - -use super::super::{fill_typed_module, plan_typed_module, POOL, SOURCE, STATUS, WORDS}; -use super::*; -use crate::bind::status::ExecutionStatus; -use crate::spirv::interp::{run as interpret, Buffer, Config, Order, Resources}; -use crate::spirv::ir::TypedModule; -use crate::spirv::testing::{assert_valid, committed_profiles}; - -/// The storage buffer offset alignment of these tests. -const ALIGNMENT: u64 = 16; -/// The pool's index bytes in these tests. -const POOL_BYTES: u32 = 96; - -fn words(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|c| u32::from_le_bytes(*c)) - .collect() -} - -fn bytes(words: &[u32]) -> Vec { - words.iter().flat_map(|w| w.to_le_bytes()).collect() -} - -/// `module` over `buffers` (at `WORDS`, `SOURCE`, `POOL` and, for the plan, `STATUS`) with -/// `workgroups` along x and y, in both invocation orders, which must agree: the buffers after. -fn dispatch(module: &TypedModule, buffers: Vec>, workgroups: [u32; 2]) -> Vec> { - let mut after = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let res = Resources { - buffers: [WORDS, SOURCE, POOL, STATUS] - .into_iter() - .zip(buffers.clone()) - .map(|(slot, bytes)| Buffer { - slot: Some(slot), - address: None, - bytes, - }) - .collect(), - push: Vec::new(), - spec: Default::default(), - }; - let cfg = Config { - order, - workgroups: [workgroups[0], workgroups[1], 1], - ..Config::default() - }; - after.push(interpret(module, &cfg, res).expect("run").buffers); - } - assert_eq!(after[0], after[1], "order independent"); - after.swap_remove(0) -} - -/// `range` of `buffer`, as Vulkan binds it. -fn bound(buffer: &[u8], range: Option) -> Vec { - match range { - Some(range) => { - buffer[range.offset as usize..(range.offset + range.range) as usize].to_vec() - } - None => vec![0xCC; 4], - } -} - -/// What the draws left: each draw's two commands, the pool's words and the status bytes. -type Left = (Vec<[u32; 10]>, Vec, Vec); - -/// The draws' own passes, one after another over one pool: what they left. -fn passes(draws: &[BoundsRunDraw], arguments: &[u8], indices: &[u8]) -> Left { - let header = (IndexBoundsPass::POOL_HEADER_BYTES / 4) as usize; - let mut pool = bytes(&vec![0; header + (POOL_BYTES / 4) as usize]); - let mut status = ExecutionStatus::initial().to_vec(); - let (plan, fill) = ( - plan_typed_module().expect("plan"), - fill_typed_module().expect("fill"), - ); - let mut commands = Vec::new(); - for draw in draws { - let pass = IndexBoundsPass::new( - IndirectRef::new(0, draw.arguments_offset), - draw.index_size, - draw.index_offset, - draw.index_end, - ALIGNMENT, - u32::MAX, - POOL_BYTES, - ) - .expect("pass"); - let mut words_of = pass.parameters.to_vec(); - words_of.resize((IndexBoundsPass::BYTES / 4) as usize, 0); - let after = dispatch( - &plan, - vec![ - bytes(&words_of), - bound(arguments, Some(pass.arguments_range)), - pool, - status, - ], - [1, 1], - ); - let planned = words(&after[0]); - (pool, status) = (after[2].clone(), after[3].clone()); - let groups = planned[Output::FillDispatch as usize]; - if groups > 0 { - let filled = dispatch( - &fill, - vec![after[0].clone(), bound(indices, pass.indices_range), pool], - [groups, 1], - ); - pool = filled[2].clone(); - } - let at = (super::super::tests::FIRST_DRAW / 4) as usize; - commands.push(planned[at..at + 10].try_into().expect("commands")); - } - (commands, words(&pool), status) -} - -/// The draws as one run whose fill takes at most `widest` workgroups along x: what its plan and -/// fill left, and its fill's workgroups along x and y and in all. -fn run_of( - draws: &[BoundsRunDraw], - (arguments, indices): (&[u8], &[u8]), - widest: u32, -) -> (Left, [u32; 3]) { - let mut run = IndexBoundsRun::new( - (0, arguments.len() as u64), - Some((0, indices.len() as u64)), - (ALIGNMENT, u32::MAX, widest), - POOL_BYTES, - ) - .expect("run"); - for (i, draw) in draws.iter().enumerate() { - assert_eq!(run.push(*draw), Some(i as u32)); - } - let header = (IndexBoundsPass::POOL_HEADER_BYTES / 4) as usize; - let pool = bytes(&vec![0; header + (POOL_BYTES / 4) as usize]); - let after = dispatch( - &plan_module_of(true).expect("plan"), - vec![ - run.words(), - bound(arguments, Some(run.arguments_range())), - pool, - ExecutionStatus::initial().to_vec(), - ], - [1, 1], - ); - let planned = words(&after[0]); - let at = (IndexBoundsRun::DISPATCH_OFFSET / 4) as usize; - let (width, rows) = (planned[at], planned[at + 1]); - assert_eq!(planned[at + 2], 1); - let mut pool = after[2].clone(); - if width * rows > 0 { - let filled = dispatch( - &fill_module_of(true).expect("fill"), - vec![after[0].clone(), bound(indices, run.indices_range()), pool], - [width, rows], - ); - pool = filled[2].clone(); - } - // The draws' fill workgroups in all: the last draw's first, and its own. - let last = (IndexBoundsRun::HEADER_WORDS - + (draws.len() as u32 - 1) * IndexBoundsRun::SLOT_WORDS) as usize; - let total = - planned[last + FIRST_GROUP as usize] + planned[last + Output::FillDispatch as usize]; - let commands = (0..draws.len() as u32) - .map(|slot| { - let at = (IndexBoundsRun::HEADER_WORDS + slot * IndexBoundsRun::SLOT_WORDS) as usize - + (super::super::tests::FIRST_DRAW / 4) as usize; - planned[at..at + 10].try_into().expect("commands") - }) - .collect(); - ( - (commands, words(&pool), after[3].clone()), - [width, rows, total], - ) -} - -#[test] -fn both_run_modules_are_valid_on_every_committed_profile() { - for (_, p) in committed_profiles().expect("profiles") { - assert_valid(plan_module_of(true).expect("plan"), &p); - assert_valid(fill_module_of(true).expect("fill"), &p); - } -} - -/// A run's draws are their own passes' draws, reservations and status, in turn, its fill -/// dispatched along x alone or spread over y. -#[test] -fn a_run_leaves_what_its_draws_passes_leave() { - for size in [2u64, 4] { - // 37 indices after 4 bytes of 0xAB, padded to whole words of 0xCC. - let mut indices = vec![0xAB; 4]; - for i in 0..37u32 { - let value = (i * 7 + 3) % 50 + 100 * (size as u32 - 2); - match size { - 4 => indices.extend(value.to_le_bytes()), - _ => indices.extend((value as u16).to_le_bytes()), - } - } - let end = indices.len() as u64; - indices.resize(indices.len().next_multiple_of(16), 0xCC); - // Each draw's arguments: count, instances, first index, base vertex, base instance. - let calls: [(u64, [u32; 5]); 8] = [ - // Inside the buffer. - (4, [6, 1, 0, 3, 0]), - // Past it, reserved and filled. - (4, [10, 2, 30, 0, 1]), - // From an offset past the buffer. - (end.next_multiple_of(size) + 4 * size, [5, 1, 0, 0, 0]), - // No position. - (4, [0, 1, 3, 0, 0]), - // Inside, from an offset. - (4 + 10 * size, [9, 1, 2, 0, 0]), - // Past the pool's room by now. - (4, [40, 1, 0, 0, 0]), - // Past the buffer again, after the overflow. - (4 + 2 * size, [7, 1, 31, 5, 0]), - // Inside, last. - (4, [3, 1, 33, 0, 0]), - ]; - let mut arguments = vec![0xEE; 12]; - let mut draws = Vec::new(); - for (index_offset, call) in calls { - draws.push(BoundsRunDraw { - arguments_offset: arguments.len() as u64, - index_size: size, - index_offset, - index_end: end, - }); - arguments.extend(bytes(&call)); - } - let want = passes(&draws, &arguments, &indices); - let mut spread = false; - for widest in [u32::MAX, 2, 1] { - let (got, [width, rows, total]) = run_of(&draws, (&arguments, &indices), widest); - let case = format!("{size}-byte indices, at most {widest} along x"); - assert_eq!(got.0, want.0, "{case}: the draws"); - assert_eq!(got.1, want.1, "{case}: the pool"); - assert_eq!(got.2, want.2, "{case}: the status"); - // The dispatch holds every workgroup within the widest, and fewer than a row more. - assert!(width <= widest && width * rows >= total && width * (rows - 1) < total); - spread |= rows > 1 && width * rows > total; - // The overflow happened, and both kinds of draw are among them. - let report = ExecutionStatus::decode( - &got.2[..ExecutionStatus::BYTES].try_into().expect("status"), - ); - assert!(report.index_pool_overflow, "{case}: no overflow"); - assert!(got.0.iter().any(|c| c[0] > 0) && got.0.iter().any(|c| c[5] > 0)); - } - // Some dispatch spread over y, with a workgroup past the last draw's. - assert!(spread, "{size}-byte indices: no spread dispatch"); - } -} - -/// A run takes no draw whose own pass would not be made, nor one whose arguments or indices lie -/// outside its bound bytes. -#[test] -fn a_run_refuses_what_it_cannot_take() { - let draw = |arguments_offset, index_offset| BoundsRunDraw { - arguments_offset, - index_size: 2, - index_offset, - index_end: 128, - }; - let mut run = IndexBoundsRun::new((64, 128), Some((64, 128)), (ALIGNMENT, u32::MAX, 65535), 64) - .expect("run"); - assert_eq!(run.push(draw(64, 64)), Some(0)); - assert_eq!(run.push(draw(66, 64)), None, "arguments off a word"); - assert_eq!( - run.push(draw(32, 64)), - None, - "arguments before the bound bytes" - ); - assert_eq!( - run.push(draw(112, 64)), - None, - "arguments past the bound bytes" - ); - assert_eq!(run.push(draw(64, 65)), None, "an odd index offset"); - assert_eq!( - run.push(draw(64, 32)), - None, - "indices before the bound bytes" - ); - assert_eq!( - run.push(BoundsRunDraw { - index_end: 256, - ..draw(64, 64) - }), - None, - "indices past the bound bytes" - ); - assert_eq!(run.len(), 1); - assert_eq!( - IndexBoundsRun::new((8, 8), None, (ALIGNMENT, u32::MAX, 65535), 64), - None - ); - assert_eq!( - IndexBoundsRun::new((8, 64), None, (ALIGNMENT, u32::MAX, 0), 64), - None, - "no workgroup along x" - ); -} diff --git a/crates/metal2vulkan/src/bind/index_bounds/tests.rs b/crates/metal2vulkan/src/bind/index_bounds/tests.rs deleted file mode 100644 index 6134b1d51..000000000 --- a/crates/metal2vulkan/src/bind/index_bounds/tests.rs +++ /dev/null @@ -1,486 +0,0 @@ -//! The index bounds pass: both modules valid on every committed profile (L3, `G-val`), and, on -//! the CPU interpreter, the plan and the fill together draw Metal's vertices (each position -//! inside the buffer's whole indices at its index, each past them at index 0, plus the base -//! vertex) through exactly one of the two draws, every fetch inside its bound range; the pool's -//! counter advances by whole words, and a draw the pool cannot hold draws nothing and sets -//! `INDEX_POOL_OVERFLOW`. - -use super::*; -use crate::bind::status::{ExecutionStatus, StatusReport}; -use crate::spirv::interp::{run, Buffer, Config, Order, Resources}; -use crate::spirv::testing::{assert_valid, committed_profiles}; - -/// The byte of the bounds words at which the first draw's `VkDrawIndexedIndirectCommand` lies -/// (words 8 to 12 of the module's table). -pub(super) const FIRST_DRAW: u64 = 32; -/// The byte of the second draw's (words 13 to 17). -const SECOND_DRAW: u64 = 52; - -/// The pool's index bytes in these tests. -const POOL_BYTES: u32 = 64; - -fn words(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|c| u32::from_le_bytes(*c)) - .collect() -} - -fn bytes(words: &[u32]) -> Vec { - words.iter().flat_map(|w| w.to_le_bytes()).collect() -} - -/// Index buffer bytes of `indices`, 4 bytes each where `wide`, else 2. -fn index_bytes(indices: &[u32], wide: bool) -> Vec { - indices - .iter() - .flat_map(|&i| { - if wide { - i.to_le_bytes().to_vec() - } else { - (i as u16).to_le_bytes().to_vec() - } - }) - .collect() -} - -/// The two modules' run over one draw: what both draws read, and the pool and status after. -struct Ran { - words: Vec, - pool: Vec, - report: StatusReport, -} - -/// Run the plan of `pass` over `arguments` (bound whole) with a pool whose counter is `counter`, -/// then the fill over `indices` (bound as `pass.indices_range` says, from offset 0 of `indices`), -/// each in both invocation orders. -fn ran(pass: &IndexBoundsPass, arguments: &[u32], indices: &[u8], counter: u32) -> Ran { - let mut bounds = pass.parameters.to_vec(); - bounds.resize((IndexBoundsPass::BYTES / 4) as usize, 0xEEEE_EEEE); - let header = (IndexBoundsPass::POOL_HEADER_BYTES / 4) as usize; - let mut pool = vec![0xDDDD_DDDD; header + (POOL_BYTES / 4) as usize]; - pool[0] = counter; - let plan = plan_typed_module().expect("plan"); - let mut planned = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let res = Resources { - buffers: vec![ - Buffer { - slot: Some(WORDS), - address: None, - bytes: bytes(&bounds), - }, - Buffer { - slot: Some(SOURCE), - address: None, - bytes: bytes(arguments), - }, - Buffer { - slot: Some(POOL), - address: None, - bytes: bytes(&pool), - }, - Buffer { - slot: Some(STATUS), - address: None, - bytes: ExecutionStatus::initial().to_vec(), - }, - ], - push: Vec::new(), - spec: Default::default(), - }; - let cfg = Config { - order, - ..Config::default() - }; - planned.push(run(&plan, &cfg, res).expect("plan run").buffers); - } - assert_eq!(planned[0], planned[1], "order independent"); - let after = &planned[0]; - let bounds = words(&after[0]); - let mut pool = words(&after[2]); - let status: [u8; ExecutionStatus::BYTES] = after[3].as_slice().try_into().expect("status"); - let report = ExecutionStatus::decode(&status); - let groups = bounds[Output::FillDispatch as usize]; - if groups > 0 { - // The indices as bound: the range `pass` names, or 4 bytes nothing reads. - let bound = match pass.indices_range { - Some(range) => { - indices[range.offset as usize..(range.offset + range.range) as usize].to_vec() - } - None => vec![0xCC; 4], - }; - let fill = fill_typed_module().expect("fill"); - let mut filled = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let res = Resources { - buffers: vec![ - Buffer { - slot: Some(WORDS), - address: None, - bytes: bytes(&bounds), - }, - Buffer { - slot: Some(SOURCE), - address: None, - bytes: bound.clone(), - }, - Buffer { - slot: Some(POOL), - address: None, - bytes: bytes(&pool), - }, - ], - push: Vec::new(), - spec: Default::default(), - }; - let cfg = Config { - order, - workgroups: [groups, 1, 1], - ..Config::default() - }; - filled.push(run(&fill, &cfg, res).expect("fill run").buffers); - } - assert_eq!(filled[0], filled[1], "order independent"); - pool = words(&filled[0][2]); - } - Ran { - words: bounds, - pool, - report, - } -} - -/// A `VkDrawIndexedIndirectCommand` at `offset` of the bounds words. -fn command(words: &[u32], offset: u64) -> [u32; 5] { - let at = (offset / 4) as usize; - words[at..at + 5].try_into().expect("command") -} - -/// The vertices the two draws draw, as Vulkan fetches them without `robustBufferAccess2`: the -/// first from `indices` bound at `index_offset` (whose bytes run to `vk_end`, the `VkBuffer`'s -/// end), the second from the pool's index bytes; every fetch must lie inside its bound range. -fn drawn(r: &Ran, indices: &[u8], index_offset: u64, vk_end: u64, wide: bool) -> Vec { - let size = if wide { 4 } else { 2 }; - let read = |bytes: &[u8], at: usize| -> u32 { - if wide { - u32::from_le_bytes(bytes[at..at + 4].try_into().expect("index")) - } else { - u32::from(u16::from_le_bytes( - bytes[at..at + 2].try_into().expect("index"), - )) - } - }; - let first = command(&r.words, FIRST_DRAW); - let second = command(&r.words, SECOND_DRAW); - assert!( - first[0] == 0 || second[0] == 0, - "one draw carries the primitives: {first:?} {second:?}" - ); - let mut out = Vec::new(); - for i in 0..u64::from(first[0]) { - let at = index_offset + (u64::from(first[2]) + i) * size; - assert!(at + size <= vk_end, "the first draw fetches past its range"); - out.push(i64::from(read(indices, at as usize)) + i64::from(first[3] as i32)); - } - let header = IndexBoundsPass::POOL_HEADER_BYTES as usize; - let pool = bytes(&r.pool); - for i in 0..u64::from(second[0]) { - let at = (u64::from(second[2]) + i) * size; - assert!( - at + size <= u64::from(POOL_BYTES), - "the second draw fetches past the pool" - ); - out.push(i64::from(read(&pool[header..], at as usize)) + i64::from(second[3] as i32)); - } - for draw in [first, second] { - assert_eq!(draw[1], 1, "instances"); - assert_eq!(draw[4], 0, "base instance"); - } - out -} - -/// Metal's vertices: position `start + i` at its index where it lies among the `inside` whole -/// indices, else index 0, plus the base vertex. -fn metal(indices: &[u32], inside: u64, start: u32, count: u32, base: i32) -> Vec { - (0..u64::from(count)) - .map(|i| { - let p = u64::from(start) + i; - let index = if p < inside { indices[p as usize] } else { 0 }; - i64::from(index) + i64::from(base) - }) - .collect() -} - -/// Metal's arguments: indexCount, instanceCount, indexStart, baseVertex, baseInstance. -fn arguments(count: u32, start: u32, base: i32) -> [u32; 5] { - [count, 1, start, base as u32, 0] -} - -#[test] -fn both_modules_are_valid_on_every_committed_profile() { - for (_, p) in committed_profiles().expect("profiles") { - assert_valid(plan_typed_module().expect("plan"), &p); - assert_valid(fill_typed_module().expect("fill"), &p); - } -} - -/// The pass binds the arguments and the whole indices from aligned offsets, and states the -/// residuals, the whole indices, the index size and the pool; it refuses what Metal and Vulkan -/// do not take. -#[test] -fn the_pass_binds_aligned_ranges_and_states_its_parameters() { - let pass = IndexBoundsPass::new(IndirectRef::new(0, 68), 4, 8, 30, 64, 1 << 27, POOL_BYTES) - .expect("pass"); - assert_eq!( - pass.arguments_range, - BufferRange { - offset: 64, - range: 24 - } - ); - // Whole indices from offset 8 of 30 bytes: 5 (bytes 8 to 28). - assert_eq!( - pass.indices_range, - Some(BufferRange { - offset: 0, - range: 28 - }) - ); - assert_eq!(pass.parameters, [1, 8, 5, 1, POOL_BYTES, 0, 0, 0]); - let at_end = IndexBoundsPass::new(IndirectRef::new(0, 0), 2, 30, 30, 64, 1 << 27, POOL_BYTES) - .expect("at the end"); - assert_eq!(at_end.indices_range, None); - assert_eq!(at_end.parameters[2], 0); - let refused = |arguments: u64, size: u64, offset: u64, pool: u32, max_range: u32| { - IndexBoundsPass::new( - IndirectRef::new(0, arguments), - size, - offset, - 64, - 64, - max_range, - pool, - ) - .is_none() - }; - assert!(refused(2, 4, 0, POOL_BYTES, 1 << 27), "arguments at 2"); - assert!(refused(0, 8, 0, POOL_BYTES, 1 << 27), "8-byte indices"); - assert!( - refused(0, 4, 2, POOL_BYTES, 1 << 27), - "a misaligned index offset" - ); - assert!(refused(0, 4, 0, 6, 1 << 27), "a pool of part of a word"); - assert!( - refused(0, 4, 0, POOL_BYTES, 32), - "indices past maxStorageBufferRange" - ); -} - -/// Every position inside the whole indices draws through the first draw, from the Metal index -/// buffer as it is bound; the second draws nothing and the pool is untouched. -#[test] -fn a_draw_inside_the_buffer_draws_from_it() { - let indices = [1, 2, 3, 4]; - let buffer = index_bytes(&indices, true); - let pass = - IndexBoundsPass::new(IndirectRef::new(0, 0), 4, 0, 16, 64, 1 << 27, POOL_BYTES).unwrap(); - for (count, start) in [(4, 0), (3, 1), (1, 3), (0, 4), (0, 0)] { - let r = ran(&pass, &arguments(count, start, 100), &buffer, 0); - assert_eq!( - drawn(&r, &buffer, 0, 16, true), - metal(&indices, 4, start, count, 100), - "{count} from {start}" - ); - assert_eq!(command(&r.words, FIRST_DRAW)[0], count); - assert_eq!(r.pool[0], 0, "no reservation"); - assert!(!r.report.index_pool_overflow); - } -} - -/// A draw whose positions run past the buffer draws through the second draw: the positions -/// inside at their indices, those past at index 0, plus the base vertex, as Metal draws them; -/// the counter advances by whole words. -#[test] -fn a_draw_past_the_buffer_draws_metals_vertices_from_the_pool() { - for wide in [true, false] { - let indices = [5, 6, 7]; - let size = if wide { 4 } else { 2 }; - // From offset `size`: one whole index (6), then part of one (7's first bytes). - let mut buffer = index_bytes(&indices, wide); - buffer.truncate((3 * size - 1) as usize); - let end = buffer.len() as u64; - let inside = (end - size) / size; - let vk_end = end.next_multiple_of(16); - buffer.resize(vk_end as usize, 0x5A); - let pass = IndexBoundsPass::new( - IndirectRef::new(0, 0), - size, - size, - end, - 64, - 1 << 27, - POOL_BYTES, - ) - .unwrap(); - let after = &indices[1..]; - for (count, start, base) in [(4, 0, 100), (3, 1, -3), (5, 2, 0), (1, 2, 7), (3, 0, 9)] { - let r = ran(&pass, &arguments(count, start, base), &buffer, 8); - let want = metal(after, inside, start, count, base); - assert_eq!( - drawn(&r, &buffer, size, vk_end, wide), - want, - "{size}-byte indices: {count} from {start}" - ); - let first = command(&r.words, FIRST_DRAW); - let second = command(&r.words, SECOND_DRAW); - let past = u64::from(start) + u64::from(count) > inside; - assert_eq!((first[0] != 0, second[0] != 0), (!past, past)); - if past { - // The reservation starts at the counter (8 bytes) and takes whole words. - assert_eq!(second[2], 8 / size as u32); - let taken = (u64::from(count) * size).next_multiple_of(4) as u32; - assert_eq!(r.pool[0], 8 + taken); - } - assert!(!r.report.index_pool_overflow); - } - } -} - -/// A draw past the buffer reads the last whole index of a word the buffer's indices end inside, -/// not 0: an odd count of 16-bit indices from a multiple of 4 bytes, or an even count from 2 -/// past one. The indices' range ends at a whole word, and the bytes past their end in it (the -/// `VkBuffer`'s padding) are no position's index. -#[test] -fn a_draw_past_the_buffer_reads_the_last_index_of_a_partial_word() { - let indices = [1, 2, 3, 4, 5, 6]; - for (offset, whole) in [(0, 5), (2, 4), (2, 5), (4, 1)] { - let mut buffer = vec![0xAB; offset as usize]; - buffer.extend(index_bytes(&indices[..whole], false)); - let end = buffer.len() as u64; - let vk_end = end.next_multiple_of(16); - buffer.resize(vk_end as usize, 0x5A); - let pass = IndexBoundsPass::new( - IndirectRef::new(0, 0), - 2, - offset, - end, - 64, - 1 << 27, - POOL_BYTES, - ) - .unwrap(); - assert_eq!( - pass.indices_range.map(|r| r.range), - Some(end.next_multiple_of(4)), - "from {offset}: whole words" - ); - let inside = whole as u64; - for (count, start) in [(whole as u32 + 2, 0), (3, whole as u32 - 1)] { - let r = ran(&pass, &arguments(count, start, 100), &buffer, 0); - assert_eq!( - drawn(&r, &buffer, offset, vk_end, false), - metal(&indices[..whole], inside, start, count, 100), - "{whole} from byte {offset}: {count} from {start}" - ); - } - } -} - -/// From an index offset at or past the buffer's length every position is past it: index 0 plus -/// the base vertex at each, from the pool. -#[test] -fn an_offset_past_the_buffer_draws_index_zero_at_every_position() { - let indices = [1, 2, 3, 4]; - let buffer = index_bytes(&indices, true); - for offset in [16, 32] { - let pass = IndexBoundsPass::new( - IndirectRef::new(0, 0), - 4, - offset, - 16, - 64, - 1 << 27, - POOL_BYTES, - ) - .unwrap(); - let r = ran(&pass, &arguments(3, 1, 100), &buffer, 0); - assert_eq!(drawn(&r, &buffer, 0, 16, true), [100, 100, 100], "{offset}"); - let r = ran(&pass, &arguments(0, 0, 100), &buffer, 0); - assert_eq!(drawn(&r, &buffer, 0, 16, true), Vec::::new()); - assert_eq!(r.pool[0], 0, "a draw of no index reserves nothing"); - } -} - -/// A start whose positions wrap past `2^32` reads no index at the wrapped positions: they lie -/// past the buffer, as Metal's 64-bit positions do. -#[test] -fn positions_past_two_to_the_32_read_index_zero() { - let indices = [1, 2, 3, 4]; - let buffer = index_bytes(&indices, true); - let pass = - IndexBoundsPass::new(IndirectRef::new(0, 0), 4, 0, 16, 64, 1 << 27, POOL_BYTES).unwrap(); - let start = u32::MAX - 1; - let r = ran(&pass, &arguments(4, start, 100), &buffer, 0); - assert_eq!(drawn(&r, &buffer, 0, 16, true), [100; 4]); -} - -/// The arguments at a residual inside their bound range are read from there. -#[test] -fn the_arguments_are_read_at_their_residual() { - let indices = [1, 2, 3, 4]; - let buffer = index_bytes(&indices, true); - let pass = - IndexBoundsPass::new(IndirectRef::new(0, 12), 4, 0, 16, 16, 1 << 27, POOL_BYTES).unwrap(); - assert_eq!(pass.parameters[0], 3); - let mut bound = vec![0xBBBB_BBBB; 3]; - bound.extend(arguments(2, 3, 10)); - let r = ran(&pass, &bound, &buffer, 0); - assert_eq!(drawn(&r, &buffer, 0, 16, true), [14, 10]); -} - -/// A draw the pool cannot hold draws nothing, leaves the counter, and sets -/// `INDEX_POOL_OVERFLOW`; one that fits exactly is drawn. -#[test] -fn a_draw_the_pool_cannot_hold_draws_nothing_and_says_so() { - let indices = [1, 2, 3, 4]; - let buffer = index_bytes(&indices, true); - let pass = - IndexBoundsPass::new(IndirectRef::new(0, 0), 4, 0, 16, 64, 1 << 27, POOL_BYTES).unwrap(); - // 48 of 64 bytes taken: 4 32-bit indices fit, 5 do not. - let r = ran(&pass, &arguments(4, 2, 0), &buffer, 48); - assert_eq!(drawn(&r, &buffer, 0, 16, true), [3, 4, 0, 0]); - assert_eq!(r.pool[0], 64); - assert!(!r.report.index_pool_overflow); - let r = ran(&pass, &arguments(5, 2, 0), &buffer, 48); - assert_eq!(drawn(&r, &buffer, 0, 16, true), Vec::::new()); - assert_eq!(r.pool[0], 48, "the counter stays"); - assert!(r.report.index_pool_overflow); - assert!(!r.report.replay_fault); - let r = ran(&pass, &arguments(u32::MAX, 2, 0), &buffer, 0); - assert_eq!(drawn(&r, &buffer, 0, 16, true), Vec::::new()); - assert!(r.report.index_pool_overflow); -} - -/// The fill writes only its reservation's words: the pool's other bytes keep theirs. -#[test] -fn the_fill_writes_only_its_reservation() { - let indices = [1, 2, 3, 4]; - let buffer = index_bytes(&indices, false); - let pass = - IndexBoundsPass::new(IndirectRef::new(0, 0), 2, 0, 8, 64, 1 << 27, POOL_BYTES).unwrap(); - // Three 16-bit positions: two words, the second's high half 0. - let r = ran(&pass, &arguments(3, 3, 0), &buffer, 4); - let header = (IndexBoundsPass::POOL_HEADER_BYTES / 4) as usize; - assert_eq!(r.pool[header], 0xDDDD_DDDD, "before the reservation"); - assert_eq!(r.pool[header + 1], 4, "position 3, then position 4 (past)"); - assert_eq!( - r.pool[header + 2], - 0, - "position 5 (past), then a half past the count" - ); - assert_eq!(r.pool[header + 3], 0xDDDD_DDDD, "after it"); - assert_eq!(r.pool[0], 12); -} diff --git a/crates/metal2vulkan/src/bind/index_rewrite.rs b/crates/metal2vulkan/src/bind/index_rewrite.rs deleted file mode 100644 index 052d05297..000000000 --- a/crates/metal2vulkan/src/bind/index_rewrite.rs +++ /dev/null @@ -1,2040 +0,0 @@ -//! The index rewrite pass of a draw whose primitives Vulkan's input assembly does not form as -//! Metal does: one dispatch before the render pass instance reads the draw's Metal indices (or, -//! for an indirect draw without indices, its count) and writes the primitives Metal draws as a -//! list of 32-bit indices, which the draw then draws as a list over its arguments, with primitive -//! restart off. -//! -//! The programs ([`RewriteProgram`], a closed enum: another way of forming primitives from indices -//! is another arm of the same pass, not another pass): -//! -//! - an indexed strip after Apple's `setPrimitiveRestartEnabled:index:`, which restarts at the -//! call's index `k'` alone, where Vulkan restarts at the index type's all-ones index alone: the -//! strip's pieces between restarts, each triangle in Vulkan's strip order with its parity -//! counted from its piece's start (a line strip's segments as pairs), in order, so every -//! primitive keeps its winding, its provoking vertex and its place in `primitive_id`'s count, -//! which Metal counts on across a restart (probe 5's `prim_*`). The all-ones index, where it is -//! not `k'`, is drawn as a vertex; -//! - Apple's private primitive types 5 to 8, which Vulkan has no topology for: a line loop, a -//! triangle fan, quads and a quad strip, each the list [`RewriteProgram`]'s arms state, in the -//! order Metal draws it (Metal probes on the M3 Max, macOS 27.0.1): each list primitive's first -//! vertex is the one Metal's provoking vertex mode 0 takes its flat inputs from, its last the -//! one mode 1 takes them from, and its order the barycentric order Metal gives at either mode. -//! The line loop, fan and quads never restart, drawing every index as a vertex; the quad strip -//! restarts as the strips do, at `k'` (the consumer's restart index: the index type's all-ones -//! index where the encoder made no call), each piece pairing from its own start. Metal counts -//! one `primitive_id` per quad, where the list has two triangles: that count is the consumer's. -//! - a line or triangle list ([`RewriteProgram::LineList`], [`RewriteProgram::TriangleList`]), -//! which never restarts: its primitives in their own order, which a draw under Apple's -//! `setProvokingVertexMode:` with the last vertex writes in [`RewriteOrder::LastFirst`]. -//! -//! **The order** ([`RewriteOrder`], parameter word 14): each primitive in Metal's order at -//! provoking vertex mode 0, the first vertex (the default); in Metal's order at mode 1, the last -//! vertex, which differs only for a triangle strip's odd triangle, `(i + 1, i, i + 2)` where mode 0 -//! gives `(i, i + 2, i + 1)` (Metal probes on the M3 Max, macOS 27.0.1: the Vulkan -//! specification's last-vertex strip order); or in Metal's order at mode 1 with the last vertex -//! moved first, `(c, a, b)` of a triangle `(a, b, c)` and `(b, a)` of a line `(a, b)`, so a -//! first-vertex pipeline takes its flat inputs from Metal's provoking vertex. -//! -//! - **Three dispatches** ([`RewritePhase`]) of workgroups of [`IndexRewriteModule::LOCAL_SIZE`] -//! invocations. The draw's positions are split into one run per invocation of -//! [`IndexRewritePass::groups`] workgroups. A position completes a step where neither it nor -//! the [`RewriteProgram::span`] less one positions before it restarts (quads: at every fourth -//! position; a quad strip: at every second position of its piece), which a run decides from its -//! own positions and the three before it, so the runs are independent but for two sums over -//! the runs before each: its primitives (its first primitive's place in the output) and the -//! start of the piece it begins in (the position after the last restart before it, from which a -//! triangle's parity and a quad strip's pairs count). A quad strip's run counts its primitives -//! for both parities of its first piece's positions before it, and the sums take the one the -//! piece's start gives. [`RewritePhase::Count`] sums each group's runs; -//! [`RewritePhase::Place`], one workgroup, places each group, reserves the output and writes -//! the draw; [`RewritePhase::Write`] places each run within its group and writes its -//! primitives. Each run walks a few dozen positions of a million-position draw, so the walks -//! spread over the GPU: one workgroup walking every position (the first pass) took 56 ms for a -//! million positions on an M4. -//! - **Positions** are Metal's: from the arguments' first index, each position inside the -//! buffer's whole indices from the offset at its index, each past them at index 0, as the fetch -//! reads it, restart included. Past the buffer every position reads 0, so the walk stops -//! [`RewriteProgram::span`] positions past the last whole index inside; the rest of the draw's -//! positions either all restart (`k'` = 0 of a restarting program: no primitive) or complete -//! primitives of index 0 (a fan's of its first index and two 0s), written without a walk; a line -//! loop's last segment, from its last position to its first, follows them. A draw without -//! indices ([`RewriteSource::IndirectVertices`]) reads each position as its own index, walks -//! them all, and restarts nowhere. -//! - **The output** is either the draw's own region ([`RewriteOutput::Owned`], a direct draw: -//! its capacity [`RewriteProgram::capacity`] of its count, from index 0), or a reservation in -//! the command buffer's index pool ([`RewriteOutput::Pooled`], an indirect draw, whose count -//! only the GPU knows), shared with the index bounds pass (`index_bounds.rs`): the pool's -//! counter in its first word, bytes reserved from its index region, which starts -//! [`IndexRewritePass::POOL_HEADER_BYTES`] in. A draw whose primitives its output cannot hold -//! draws nothing and sets [`StatusBits::INDEX_POOL_OVERFLOW`], which the consumer reports as the -//! command buffer's error. Nothing is drawn short silently. Of a pooled output, the count -//! dispatch reads nothing, the place dispatch reads and writes only the counter, and the write -//! dispatch writes only index bytes, so a consumer may bind the counter for the first two and -//! another buffer of the pool's bytes for the write, as the index bounds pass's plan and fill -//! may. -//! -//! **The rewrite words** (one `u32` array of [`IndexRewritePass::BYTES`], a storage buffer, and -//! the indirect source of the draw): -//! -//! | Words | Written by | Contents | -//! |---|---|---| -//! | 0 to 7 | the consumer | [`IndexRewritePass::parameters`]: the arguments' first word in the bound arguments range plus 1 (0 for a direct draw), the index offset's byte in the bound indices range, the whole indices from the offset (saturated to `u32`), 1 for 32-bit indices, `k'`, the output's capacity in indices (owned) or the pool's index bytes (pooled), 1 where pooled, the groups | -//! | 8 to 12 | the consumer | a direct draw's Metal arguments (`MTLDrawIndexedPrimitivesIndirectArguments`: count, instances, first index 0, base vertex, base instance); 0 for an indirect draw, whose arguments are read from the Metal buffer | -//! | 13 | the consumer | 1 for a draw without indices, whose arguments are `MTLDrawPrimitivesIndirectArguments` (count, instances, vertex start, base instance), else 0 | -//! | 14 | the consumer | the order ([`RewriteOrder::word`]): 0 first, 1 last, 2 last first | -//! | 15 | the consumer | 1 for a list drawn in the private list form ([`IndexRewritePass::listed`]): Metal's base vertex in the word before the list, the draw without indices, else 0 | -//! | 16 to 20 | the place dispatch | the draw's `VkDrawIndexedIndirectCommand` ([`IndexRewritePass::DRAW_OFFSET`]), or in the private list form its `VkDrawIndirectCommand` (the list's indices, instances, its first index's word as first vertex, base instance) and a 0 | -//! | 21 | the place dispatch | the primitives written | -//! | 22 to 25 | the place dispatch | the output's first word, 1 where the draw is written, the primitives before those past the walk, and those past it | -//! | 32 on | the count and place dispatches | three words per group: its primitives (where its first piece's positions before it are even), then those before it; its primitives where they are odd, then the start of the piece it begins in (0 for none); the start of its last piece (0 for none) | -//! -//! **Bindings** (set 0, storage buffers): [`IndexRewriteModule::WORDS_BINDING`], -//! `ARGUMENTS_BINDING` ([`IndexRewritePass::arguments_range`], or any 4 bytes for a direct draw), -//! `INDICES_BINDING` ([`IndexRewritePass::indices_range`], or any 4 bytes where it is `None`), -//! `OUTPUT_BINDING` (the draw's region, or the whole pool from its counter) and `STATUS_BINDING` -//! (the `ExecutionStatus` buffer). Every read of the arguments and indices is contained (an index -//! past the bound range reads 0), and every write lies inside the output. -//! -//! **Synchronization** (consumer): the arguments' and indices' writes and the upload of the -//! words → `SHADER_READ` in `COMPUTE_SHADER` before the count dispatch; each dispatch's -//! `SHADER_WRITE` → `SHADER_READ` and `SHADER_WRITE` in `COMPUTE_SHADER` before the next; -//! passes and index bounds plans one after another (each reads and writes the pool's counter); -//! the write dispatch's writes (and the place dispatch's) → `INDEX_READ` in `INDEX_INPUT` and -//! `INDIRECT_COMMAND_READ` in `DRAW_INDIRECT` before the draw. -//! -//! **A run** ([`IndexRewriteRun`], [`index_rewrite_run_module`]): direct indexed draws of one -//! program, order and `k'` over one index buffer, each of one group, take one dispatch for all -//! of them, each draw's three phases in turn in a workgroup of its own, its words a slot of the -//! run's and its list a region of the run's output. - -use std::sync::Arc; - -use crate::bind::index_bounds::{finished, word_range, IndexBoundsPass}; -use crate::bind::instantiate::{BufferRange, IndirectRef}; -use crate::bind::replay::checked_mul; -use crate::bind::status::{StatusBits, StatusWord}; -use crate::device::requirements::Requirements; -use crate::device::Device; -use crate::error::Error; -use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, Symbol, SyntheticBinding}; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn, LoopFn, LoopSpec}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::BResult; -use crate::spirv::ids::{GlobalId, TypeId, Value}; -use crate::spirv::ir::{ - natural_layout, AtomicOp, BinOp, ConstBits, Constant, ExecMode, ExecModel, GlslOp, IoDir, - LayoutRule, MemAccess, MemoryOrder, Scope, Semantics, StorageClass, Type, TypedModule, UnOp, -}; - -/// How the pass forms a draw's primitives from its indices: one module each. -/// -/// Apple's private primitive types 5 to 8 are programs too, each a list in the order Metal draws -/// it (Metal probes on the M3 Max, macOS 27.0.1, every count from 0 to 12, 16- and 32-bit indices, -/// both provoking vertex modes): barycentric order the list's, the flat vertex its first vertex -/// at mode 0 and its last at mode 1. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum RewriteProgram { - /// A line strip restarting at `k'` alone: each segment of a piece as a pair. - LineStrip, - /// A triangle strip restarting at `k'` alone: each triangle of a piece in Vulkan's strip - /// order, its parity counted from the piece's start. - TriangleStrip, - /// Apple's line loop (primitive type 5): the segments `(i, i + 1)`, then `(last, first)` - /// where there are two positions or more. It never restarts: every index is a vertex. - LineLoop, - /// Apple's triangle fan (6): the triangles `(first, i + 1, i + 2)`. It never restarts. - TriangleFan, - /// Apple's quads (7): each four positions `a, b, c, d` the triangles `(a, b, d)` and - /// `(b, c, d)`, the positions past the last whole four none. It never restarts. - Quads, - /// Apple's quad strip (8): each pair `c, d` after a pair `a, b` of a piece the triangles - /// `(a, b, d)` and `(c, a, d)`, an odd last position none. It restarts at `k'` alone, as the - /// strips do, each piece pairing from its own start. - QuadStrip, - /// A line list: each two positions a segment, an odd last position none. It never restarts. - LineList, - /// A triangle list: each three positions a triangle, the positions past the last whole three - /// none. It never restarts. - TriangleList, -} - -impl RewriteProgram { - /// Every program. - pub const ALL: [RewriteProgram; 8] = [ - RewriteProgram::LineStrip, - RewriteProgram::TriangleStrip, - RewriteProgram::LineLoop, - RewriteProgram::TriangleFan, - RewriteProgram::Quads, - RewriteProgram::QuadStrip, - RewriteProgram::LineList, - RewriteProgram::TriangleList, - ]; - - /// The indices of one primitive of the output list: 2 for lines, 3 for triangles. - pub fn vertices(self) -> u32 { - match self { - RewriteProgram::LineStrip | RewriteProgram::LineLoop | RewriteProgram::LineList => 2, - _ => 3, - } - } - - /// The positions a step of the walk forms primitives over: the last `span` positions of a - /// piece, through the one that completes them. - pub fn span(self) -> u32 { - match self { - RewriteProgram::LineStrip | RewriteProgram::LineLoop | RewriteProgram::LineList => 2, - RewriteProgram::TriangleStrip - | RewriteProgram::TriangleFan - | RewriteProgram::TriangleList => 3, - RewriteProgram::Quads | RewriteProgram::QuadStrip => 4, - } - } - - /// The list primitives a completing position writes: a quad's two triangles, else one. - pub fn per_step(self) -> u32 { - match self { - RewriteProgram::Quads | RewriteProgram::QuadStrip => 2, - _ => 1, - } - } - - /// Whether the program's pieces end at `k'`: the strips', as Metal restarts them. A line - /// loop, a fan and quads draw every index as a vertex. - pub fn restarts(self) -> bool { - matches!( - self, - RewriteProgram::LineStrip | RewriteProgram::TriangleStrip | RewriteProgram::QuadStrip - ) - } - - /// The most indices the program writes for a draw of `count` positions: those of `count` - /// positions that no index restarts. - pub fn capacity(self, count: u64) -> u64 { - let primitives = match self { - RewriteProgram::LineStrip => count.saturating_sub(1), - RewriteProgram::TriangleStrip | RewriteProgram::TriangleFan => count.saturating_sub(2), - RewriteProgram::LineLoop if count >= 2 => count, - RewriteProgram::Quads => count / 4 * 2, - RewriteProgram::QuadStrip if count >= 4 => (count - 2) / 2 * 2, - RewriteProgram::LineList => count / 2, - RewriteProgram::TriangleList => count / 3, - RewriteProgram::LineLoop | RewriteProgram::QuadStrip => 0, - }; - primitives * u64::from(self.vertices()) - } - - /// The list Metal draws of `values` (each position's index, as the fetch reads it) under - /// this program, restarting at `restart` where the program restarts, each primitive in - /// `order`: what the pass writes, on the CPU (a direct draw without indices, whose positions - /// are its vertices from 0). - pub fn list(self, values: &[u32], restart: u32, order: RewriteOrder) -> Vec { - let mut out = Vec::with_capacity(self.capacity(values.len() as u64) as usize); - let mut put = |first: &[u32], last: &[u32]| out.extend(order.arrange(first, last)); - if self == RewriteProgram::LineLoop { - if let [first, .., last] = values { - for pair in values.windows(2) { - put(pair, pair); - } - put(&[*last, *first], &[*last, *first]); - } - return out; - } - let mut piece: Vec = Vec::new(); - for &x in values { - if self.restarts() && x == restart { - piece.clear(); - continue; - } - piece.push(x); - let n = piece.len(); - match self { - RewriteProgram::LineStrip if n >= 2 => { - let line = [piece[n - 2], piece[n - 1]]; - put(&line, &line); - } - RewriteProgram::TriangleStrip if n >= 3 => { - let (a, b, c) = (piece[n - 3], piece[n - 2], piece[n - 1]); - match (n - 3).is_multiple_of(2) { - true => put(&[a, b, c], &[a, b, c]), - false => put(&[a, c, b], &[b, a, c]), - } - } - RewriteProgram::TriangleFan if n >= 3 => { - let triangle = [piece[0], piece[n - 2], piece[n - 1]]; - put(&triangle, &triangle); - } - RewriteProgram::Quads if n.is_multiple_of(4) => { - let (a, b, c, d) = (piece[n - 4], piece[n - 3], piece[n - 2], piece[n - 1]); - put(&[a, b, d], &[a, b, d]); - put(&[b, c, d], &[b, c, d]); - } - RewriteProgram::QuadStrip if n >= 4 && n.is_multiple_of(2) => { - let (a, b, c, d) = (piece[n - 4], piece[n - 3], piece[n - 2], piece[n - 1]); - put(&[a, b, d], &[a, b, d]); - put(&[c, a, d], &[c, a, d]); - } - RewriteProgram::LineList if n.is_multiple_of(2) => { - let line = [piece[n - 2], piece[n - 1]]; - put(&line, &line); - } - RewriteProgram::TriangleList if n.is_multiple_of(3) => { - let triangle = [piece[n - 3], piece[n - 2], piece[n - 1]]; - put(&triangle, &triangle); - } - _ => {} - } - } - out - } - - /// [`list`](Self::list) of a draw without indices of `count` positions: of the positions - /// themselves, `0..count`, none of which restarts, each primitive in `order`. - pub fn sequential_list(self, count: u32, order: RewriteOrder) -> Vec { - let mut out = Vec::with_capacity(self.capacity(u64::from(count)) as usize); - let mut put = |first: &[u32], last: &[u32]| out.extend(order.arrange(first, last)); - let n = count; - match self { - RewriteProgram::LineStrip => (1..n).for_each(|q| put(&[q - 1, q], &[q - 1, q])), - RewriteProgram::TriangleStrip => (2..n).for_each(|q| match q % 2 { - 0 => put(&[q - 2, q - 1, q], &[q - 2, q - 1, q]), - _ => put(&[q - 2, q, q - 1], &[q - 1, q - 2, q]), - }), - RewriteProgram::LineLoop if n >= 2 => { - (1..n).for_each(|q| put(&[q - 1, q], &[q - 1, q])); - put(&[n - 1, 0], &[n - 1, 0]); - } - RewriteProgram::TriangleFan => (2..n).for_each(|q| put(&[0, q - 1, q], &[0, q - 1, q])), - RewriteProgram::Quads => (0..n / 4).map(|k| 4 * k).for_each(|a| { - put(&[a, a + 1, a + 3], &[a, a + 1, a + 3]); - put(&[a + 1, a + 2, a + 3], &[a + 1, a + 2, a + 3]); - }), - RewriteProgram::QuadStrip if n >= 4 => (0..(n - 2) / 2).map(|k| 2 * k).for_each(|a| { - put(&[a, a + 1, a + 3], &[a, a + 1, a + 3]); - put(&[a + 2, a, a + 3], &[a + 2, a, a + 3]); - }), - RewriteProgram::LineList => (0..n / 2).map(|k| 2 * k).for_each(|a| { - put(&[a, a + 1], &[a, a + 1]); - }), - RewriteProgram::TriangleList => (0..n / 3).map(|k| 3 * k).for_each(|a| { - put(&[a, a + 1, a + 2], &[a, a + 1, a + 2]); - }), - RewriteProgram::LineLoop | RewriteProgram::QuadStrip => {} - } - out - } -} - -/// The vertex order the pass writes each primitive in (the module docs say why): Metal's at -/// provoking vertex mode 0 ([`First`](Self::First), the default), Metal's at mode 1 -/// ([`Last`](Self::Last)), or Metal's at mode 1 with the last vertex first -/// ([`LastFirst`](Self::LastFirst)). A draw of a pipeline whose provoking vertex is the first -/// takes its flat inputs from each primitive's first vertex, and one of a pipeline whose provoking -/// vertex is the last (`VK_EXT_provoking_vertex`) from its last; each takes its barycentric order -/// from the order its vertices are listed in (the Vulkan specification's primitive topologies and -/// barycentric interpolation). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum RewriteOrder { - /// Metal's order at provoking vertex mode 0: its flat inputs from the first vertex. - #[default] - First, - /// Metal's order at provoking vertex mode 1: its flat inputs from the last vertex. A - /// triangle strip's odd triangle is `(i + 1, i, i + 2)`, every other primitive as in - /// [`First`](Self::First). - Last, - /// [`Last`](Self::Last) with each primitive's last vertex moved first: a triangle `(a, b, c)` - /// as `(c, a, b)`, which keeps its winding, and a line `(a, b)` as `(b, a)`, which runs the - /// other way. - LastFirst, -} - -impl RewriteOrder { - /// The order's parameter word (14). - pub const fn word(self) -> u32 { - match self { - RewriteOrder::First => 0, - RewriteOrder::Last => 1, - RewriteOrder::LastFirst => 2, - } - } - - /// A primitive whose vertices are `first` in Metal's order at mode 0 and `last` at mode 1, - /// in this order. - pub fn arrange(self, first: &[T], last: &[T]) -> Vec { - match self { - RewriteOrder::First => first.to_vec(), - RewriteOrder::Last => last.to_vec(), - RewriteOrder::LastFirst => match last.split_last() { - Some((lead, rest)) => std::iter::once(*lead).chain(rest.iter().copied()).collect(), - None => Vec::new(), - }, - } - } -} - -/// One of a pass's three dispatches, in the order the consumer records them (the module docs -/// say what each does): one module each, of each program. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum RewritePhase { - /// Over [`IndexRewritePass::groups`] workgroups: each sums its runs' primitives and finds - /// the start of its last piece. - Count, - /// One workgroup: places each group, reserves the output, and writes the draw. - Place, - /// Over the groups again: each places its runs and writes their primitives. - Write, -} - -impl RewritePhase { - /// The phases, in the order the consumer dispatches them. - pub const ALL: [RewritePhase; 3] = [ - RewritePhase::Count, - RewritePhase::Place, - RewritePhase::Write, - ]; - - /// The workgroups of the phase's dispatch for `pass`. - pub fn workgroups(self, pass: &IndexRewritePass) -> u32 { - match self { - RewritePhase::Place => 1, - RewritePhase::Count | RewritePhase::Write => pass.groups, - } - } -} - -/// Where a draw's Metal arguments are. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum RewriteSource { - /// A direct draw: its index count, instances, base vertex and base instance. - Direct { - /// Metal's index count. - count: u32, - /// Metal's instance count. - instances: u32, - /// Metal's base vertex. - base_vertex: i32, - /// Metal's base instance. - base_instance: u32, - }, - /// An indirect draw: Metal's `MTLDrawIndexedPrimitivesIndirectArguments` at `arguments`. - Indirect { - /// The arguments' place in the Metal indirect buffer. - arguments: IndirectRef, - }, - /// An indirect draw without indices: Metal's `MTLDrawPrimitivesIndirectArguments` at - /// `arguments`. Each position is its own index from 0, the draw's vertex start its base - /// vertex, and no position restarts. - IndirectVertices { - /// The arguments' place in the Metal indirect buffer. - arguments: IndirectRef, - }, -} - -/// Where the pass writes a draw's indices. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum RewriteOutput { - /// A region of the draw's own, of `capacity` indices, written from index 0. - Owned { - /// The region's indices. - capacity: u32, - }, - /// A reservation in the command buffer's index pool of `pool_bytes` index bytes (a multiple - /// of 4) behind its header. - Pooled { - /// The pool's index bytes. - pool_bytes: u32, - }, -} - -/// One draw's index rewrite pass: what the consumer binds and uploads (the module docs say how). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct IndexRewritePass { - /// The range of the Metal indirect buffer to bind at - /// [`IndexRewriteModule::ARGUMENTS_BINDING`]: from the arguments' offset aligned down to - /// `minStorageBufferOffsetAlignment` (and to 4) through their 20 bytes (16 without indices); - /// `None` for a direct draw. - pub arguments_range: Option, - /// The range of the Metal index buffer to bind at [`IndexRewriteModule::INDICES_BINDING`]: - /// from the index offset aligned down likewise through the whole indices inside the buffer, - /// to a whole word (`index_bounds::word_range`); `None` when none lies inside it from the - /// offset, and for a draw without indices. - pub indices_range: Option, - /// The words' first [`IndexRewritePass::PARAMETER_WORDS`] words, which the consumer uploads - /// before the pass. - pub parameters: [u32; IndexRewritePass::PARAMETER_WORDS], - /// The workgroups of the count and write dispatches ([`RewritePhase::workgroups`]): one per - /// [`IndexRewritePass::GROUP_POSITIONS`] positions the walk may take, from 1 to - /// [`IndexRewritePass::MAX_GROUPS`] (all of them for an indirect draw without indices, whose - /// count only the GPU knows). - pub groups: u32, -} - -impl IndexRewritePass { - /// Bytes of the rewrite words: through the groups' words of [`MAX_GROUPS`](Self::MAX_GROUPS). - pub const BYTES: u64 = - 4 * (Output::Groups as u64 + GROUP_WORDS as u64 * Self::MAX_GROUPS as u64); - /// The most workgroups of the count and write dispatches. - pub const MAX_GROUPS: u32 = 256; - /// The positions of a walk per workgroup of the count and write dispatches, below which a - /// draw takes fewer: 32 per invocation. - pub const GROUP_POSITIONS: u64 = 32 * IndexRewriteModule::LOCAL_SIZE as u64; - /// The most positions a walk takes past the buffer's whole indices: the most positions of a - /// program's step ([`RewriteProgram::span`]). - const WALK_PAST: u64 = 4; - /// The consumer's words at the rewrite words' start: the parameters and a direct draw's - /// arguments. - pub const PARAMETER_WORDS: usize = 16; - /// The draw's `VkDrawIndexedIndirectCommand` in the rewrite words. - pub const DRAW_OFFSET: u64 = 64; - /// The index pool's header, as the index bounds pass's: its counter, then reserved bytes. - pub const POOL_HEADER_BYTES: u64 = IndexBoundsPass::POOL_HEADER_BYTES; - /// Bytes of Metal's `MTLDrawIndexedPrimitivesIndirectArguments`. - const ARGUMENT_BYTES: u64 = 20; - /// Bytes of Metal's `MTLDrawPrimitivesIndirectArguments`. - const VERTEX_ARGUMENT_BYTES: u64 = 16; - - /// The pass of a draw from `source` restarting at `restart` (`k'`), drawing indices of - /// `index_size` bytes (2 or 4) from `index_offset` of an index buffer whose bytes end at - /// `index_end` (its length, in the same terms as the offset; its `VkBuffer` holds the bytes - /// to `index_end` rounded up to 4 there, as the padding does), into `output`, with ranges bound - /// at offsets aligned to `alignment` (`minStorageBufferOffsetAlignment`) over at most - /// `max_range` bytes (`maxStorageBufferRange`). A draw without indices - /// ([`RewriteSource::IndirectVertices`]) binds none: its index terms are 4, 0 and 0. `None` - /// when the arguments' offset is not a multiple of 4, the index size is neither 2 nor 4, the - /// index offset is not a multiple of it, a pool's bytes are not a multiple of 4, or a range - /// overflows or exceeds `max_range`. - pub fn new( - source: RewriteSource, - restart: u32, - (index_size, index_offset, index_end): (u64, u64, u64), - output: RewriteOutput, - alignment: u64, - max_range: u32, - ) -> Option { - if !matches!(index_size, 2 | 4) || !index_offset.is_multiple_of(index_size) { - return None; - } - let aligned = |offset: u64, end: u64| word_range(offset, end, alignment, max_range); - let mut parameters = [0; Self::PARAMETER_WORDS]; - let sequential = matches!(source, RewriteSource::IndirectVertices { .. }); - let arguments_range = match source { - RewriteSource::Direct { - count, - instances, - base_vertex, - base_instance, - } => { - parameters[Parameter::Arguments as usize] = count; - parameters[Parameter::Arguments as usize + 1] = instances; - parameters[Parameter::Arguments as usize + 3] = base_vertex as u32; - parameters[Parameter::Arguments as usize + 4] = base_instance; - None - } - RewriteSource::Indirect { arguments } - | RewriteSource::IndirectVertices { arguments } => { - if !arguments.offset.is_multiple_of(4) { - return None; - } - let bytes = match sequential { - true => Self::VERTEX_ARGUMENT_BYTES, - false => Self::ARGUMENT_BYTES, - }; - let end = arguments.offset.checked_add(bytes)?; - let (range, residual) = aligned(arguments.offset, end)?; - parameters[Parameter::ArgumentsWord as usize] = - u32::try_from(residual / 4 + 1).ok()?; - Some(range) - } - }; - let inside = match sequential { - true => 0, - false => index_end.saturating_sub(index_offset) / index_size, - }; - // The positions the walk may take: an indirect draw's count is the GPU's. - let walk = inside.saturating_add(Self::WALK_PAST); - let walk = match source { - RewriteSource::Direct { count, .. } => walk.min(u64::from(count)), - RewriteSource::Indirect { .. } => walk, - RewriteSource::IndirectVertices { .. } => u64::MAX, - }; - let groups = walk - .div_ceil(Self::GROUP_POSITIONS) - .clamp(1, u64::from(Self::MAX_GROUPS)) as u32; - let (indices_range, indices_residual) = if inside == 0 { - (None, 0) - } else { - let end = index_offset.checked_add(inside.checked_mul(index_size)?)?; - let (range, residual) = aligned(index_offset, end)?; - (Some(range), residual) - }; - let (capacity, pooled) = match output { - RewriteOutput::Owned { capacity } => (capacity, 0), - RewriteOutput::Pooled { pool_bytes } => { - if !pool_bytes.is_multiple_of(4) { - return None; - } - (pool_bytes, 1) - } - }; - parameters[Parameter::IndicesByte as usize] = u32::try_from(indices_residual).ok()?; - parameters[Parameter::Inside as usize] = u32::try_from(inside).unwrap_or(u32::MAX); - parameters[Parameter::Wide as usize] = u32::from(index_size == 4); - parameters[Parameter::Restart as usize] = restart; - parameters[Parameter::Capacity as usize] = capacity; - parameters[Parameter::Pooled as usize] = pooled; - parameters[Parameter::Groups as usize] = groups; - parameters[Parameter::Sequential as usize] = u32::from(sequential); - Some(IndexRewritePass { - arguments_range, - indices_range, - parameters, - groups, - }) - } - - /// The pass writing each primitive in `order` (the pass [`new`](Self::new) makes writes - /// [`RewriteOrder::First`]). - pub fn with_order(mut self, order: RewriteOrder) -> IndexRewritePass { - self.parameters[Parameter::Order as usize] = order.word(); - self - } - - /// The pass of a list drawn in the private list form (`VariantKey::private_list`): the - /// output holds Metal's base vertex (the draw's, its vertex start without indices) in the - /// word before the list's first index, which an owned output's capacity counts too, and the - /// draw at [`DRAW_OFFSET`](Self::DRAW_OFFSET) is a `VkDrawIndirectCommand` of the list's - /// positions, its first vertex the list's first index in the output (from the pool's index - /// region where pooled) and its first instance Metal's base instance. - pub fn listed(mut self) -> IndexRewritePass { - self.parameters[Parameter::Listed as usize] = 1; - self - } -} - -/// The consumer's words, by index into the rewrite words. -#[derive(Clone, Copy)] -enum Parameter { - ArgumentsWord = 0, - IndicesByte = 1, - Inside = 2, - Wide = 3, - Restart = 4, - Capacity = 5, - Pooled = 6, - Groups = 7, - Arguments = 8, - /// 1 for a draw without indices ([`RewriteSource::IndirectVertices`]). - Sequential = 13, - /// The order ([`RewriteOrder::word`]). - Order = 14, - /// 1 for a list drawn in the private list form ([`IndexRewritePass::listed`]). - Listed = 15, - /// A run's draw's: the first word of its region of the run's output - /// ([`IndexRewriteRun`]); a pass's draw writes from word 0 and reads no such word. - OwnedFirst = 26, -} - -/// The pass's words in the rewrite words, by index. -#[derive(Clone, Copy)] -enum Output { - Draw = 16, - Primitives = 21, - /// The output's first word. - Base = 22, - /// 1 where the draw is written. - Written = 23, - /// The primitives before those past the walk. - TailAt = 24, - /// The primitives past the walk. - Tail = 25, - /// The groups' words, [`GROUP_WORDS`] per group. - Groups = 32, -} - -/// The words of each group: its primitives where its first piece's positions before it are -/// even, and where they are odd (a quad strip's pairs count from its piece's start); and the -/// start of its last piece. The place dispatch turns the first two into the primitives before -/// the group and the start of the piece it begins in. -const GROUP_WORDS: u32 = 3; - -/// The crate-owned module of one program on one device, validated like any output. -#[non_exhaustive] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct IndexRewriteModule { - /// SPIR-V 1.5 words, entry point `main`, bindings numbered as below in set 0. - pub spirv: Arc<[u32]>, - /// What the module needs from the device (within every Vulkan 1.2 device). - pub requirements: Requirements, -} - -impl IndexRewriteModule { - /// Descriptor set of every binding. - pub const SET: u32 = 0; - /// The draw's rewrite words, a storage buffer. - pub const WORDS_BINDING: u32 = 0; - /// The Metal indirect buffer, a storage buffer. - pub const ARGUMENTS_BINDING: u32 = 1; - /// The Metal index buffer, a storage buffer. - pub const INDICES_BINDING: u32 = 2; - /// The draw's output: its region, or the command buffer's index pool, a storage buffer. - pub const OUTPUT_BINDING: u32 = 3; - /// The command buffer's `ExecutionStatus` buffer, a storage buffer. - pub const STATUS_BINDING: u32 = 4; - /// Invocations of each workgroup, along x: Vulkan's least `maxComputeWorkGroupSize[0]` - /// and `maxComputeWorkGroupInvocations`, so every device takes it. - pub const LOCAL_SIZE: u32 = 128; -} - -/// The words' binding symbol in the typed module. -pub const WORDS: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 0, -}; -/// The arguments' binding symbol ([`IndexRewriteModule::ARGUMENTS_BINDING`]). -pub const ARGUMENTS: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 1, -}; -/// The indices' binding symbol ([`IndexRewriteModule::INDICES_BINDING`]). -pub const INDICES: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 2, -}; -/// The output's binding symbol ([`IndexRewriteModule::OUTPUT_BINDING`]). -pub const OUTPUT: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Buffer, - index: 3, -}; -/// The status buffer's binding symbol ([`IndexRewriteModule::STATUS_BINDING`]). -pub const STATUS: ResourceSlot = ResourceSlot { - stage: Stage::Kernel, - kind: ResourceKind::Synthetic(SyntheticBinding::ExecutionStatus), - index: 0, -}; - -/// A `Block { u32 words[]; }` storage buffer bound at `sym`. -fn words_buffer(b: &mut ModuleBuilder, sym: ResourceSlot, u32_: TypeId) -> BResult { - let rta = b.ty(Type::RuntimeArray { - elem: u32_, - stride: Some(4), - })?; - let layout = natural_layout(b.types(), LayoutRule::Std430, true, &[rta])?; - let block = b.ty(Type::Struct { - members: [rta].into(), - layout: Some(layout), - })?; - b.resource(sym, StorageClass::StorageBuffer, block) -} - -fn k(f: &mut FunctionBuilder<'_>, v: u32) -> BResult { - let c = f.u32_const(v)?; - f.module().const_value(c) -} - -/// The `bool` constant `v`. -fn boolean(f: &mut FunctionBuilder<'_>, v: bool) -> BResult { - let ty = f.bool_ty(1)?; - let c = f.module().constant(Constant::Scalar { - ty, - bits: ConstBits(u64::from(v)), - })?; - f.module().const_value(c) -} - -/// The pointer to word `index` of `buffer`'s runtime array. -fn word_ptr(f: &mut FunctionBuilder<'_>, buffer: Value, index: Value) -> BResult { - let zero = k(f, 0)?; - f.access_chain(buffer, &[zero, index]) -} - -fn load(f: &mut FunctionBuilder<'_>, buffer: Value, index: Value) -> BResult { - let p = word_ptr(f, buffer, index)?; - f.load(p, MemAccess::default()) -} - -fn store(f: &mut FunctionBuilder<'_>, buffer: Value, index: Value, v: Value) -> BResult<()> { - let p = word_ptr(f, buffer, index)?; - f.store(p, v, MemAccess::default()) -} - -/// Word `index` of `buffer` where it lies inside the buffer's bound range, else 0 (contained). -fn contained(f: &mut FunctionBuilder<'_>, buffer: Value, index: Value) -> BResult { - let zero = k(f, 0)?; - let len = f.array_length(buffer, 0)?; - let inside = f.binary(BinOp::ULessThan, index, len)?; - let safe = f.select(inside, index, zero)?; - let loaded = load(f, buffer, safe)?; - f.select(inside, loaded, zero) -} - -/// Store `v` at word `index` of `buffer` where it lies inside the buffer's bound range. -fn contained_store( - f: &mut FunctionBuilder<'_>, - buffer: Value, - index: Value, - v: Value, -) -> BResult<()> { - let len = f.array_length(buffer, 0)?; - let inside = f.binary(BinOp::ULessThan, index, len)?; - when(f, inside, move |f| store(f, buffer, index, v)) -} - -/// `a + b`, or `u32::MAX` where it wraps. -fn saturating_add(f: &mut FunctionBuilder<'_>, a: Value, b: Value) -> BResult { - let sum = f.binary(BinOp::IAdd, a, b)?; - let wrapped = f.binary(BinOp::ULessThan, sum, a)?; - let max = k(f, u32::MAX)?; - f.select(wrapped, max, sum) -} - -/// `a - b`, or 0 where `b` is larger. -fn saturating_sub(f: &mut FunctionBuilder<'_>, a: Value, b: Value) -> BResult { - let diff = f.binary(BinOp::ISub, a, b)?; - let over = f.binary(BinOp::UGreaterThan, b, a)?; - let zero = k(f, 0)?; - f.select(over, zero, diff) -} - -/// `a / b` rounded up (`b` not 0), without wrapping. -fn div_ceil(f: &mut FunctionBuilder<'_>, a: Value, b: Value) -> BResult { - let q = f.binary(BinOp::UDiv, a, b)?; - let r = f.binary(BinOp::UMod, a, b)?; - let zero = k(f, 0)?; - let one = k(f, 1)?; - let partial = f.binary(BinOp::INotEqual, r, zero)?; - let extra = f.select(partial, one, zero)?; - f.binary(BinOp::IAdd, q, extra) -} - -/// Run `each(f, i)` for `i` from `lo` below `hi`, `step` apart (`step` not 0). -pub(crate) fn for_range<'a>( - f: &mut FunctionBuilder<'_>, - u32_: TypeId, - (lo, hi, step): (Value, Value, Value), - each: impl FnOnce(&mut FunctionBuilder<'_>, Value) -> BResult<()> + 'a, -) -> BResult<()> { - let var = f.local_var(u32_, None)?; - let counter = f.var_ptr(var)?; - f.store(counter, lo, MemAccess::default())?; - let body: LoopFn<'a, ()> = Box::new(move |f, _, lc| { - let i = f.load(counter, MemAccess::default())?; - let done = f.binary(BinOp::UGreaterThanEqual, i, hi)?; - let exit: ArmFn<'_, ()> = Box::new(move |f, _| { - lc.break_(f)?; - Ok(ArmEnd::Exits) - }); - f.if_(&mut (), done, exit, None)?; - // The next `i`, or past `hi` where it would wrap. - let next = saturating_add(f, i, step)?; - f.store(counter, next, MemAccess::default())?; - each(f, i) - }); - f.loop_(&mut (), LoopSpec::default(), body) -} - -/// Run `then(f)` where `c` holds. -pub(crate) fn when<'a>( - f: &mut FunctionBuilder<'_>, - c: Value, - then: impl FnOnce(&mut FunctionBuilder<'_>) -> BResult<()> + 'a, -) -> BResult<()> { - let arm: ArmFn<'a, ()> = Box::new(move |f, _| { - then(f)?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - f.if_(&mut (), c, arm, None)?; - Ok(()) -} - -/// The workgroup barrier over the runs' words. -fn barrier(f: &mut FunctionBuilder<'_>) -> BResult<()> { - let sem = Semantics { - order: MemoryOrder::AcquireRelease, - workgroup_memory: true, - ..Semantics::RELAXED - }; - f.control_barrier(Scope::Workgroup, Scope::Workgroup, sem) -} - -/// The workgroup barrier over the runs' words and the draw's words, between a run's phases. -fn phase_barrier(f: &mut FunctionBuilder<'_>) -> BResult<()> { - let sem = Semantics { - order: MemoryOrder::AcquireRelease, - workgroup_memory: true, - uniform_memory: true, - ..Semantics::RELAXED - }; - f.control_barrier(Scope::Workgroup, Scope::Workgroup, sem) -} - -/// What reads the draw's Metal index at a position. -#[derive(Clone, Copy)] -struct Fetch { - indices: Value, - first_byte: Value, - inside: Value, - start: Value, - wide: Value, - /// A draw without indices: each position is its own index. - sequential: Value, -} - -impl Fetch { - /// The index at the draw's position `q` (Metal position `start + q`): where it lies inside - /// the whole indices (and did not wrap past `start`), its index, else 0; 4 bytes each where - /// `wide`, else 2. A draw without indices reads `q`. - fn at(self, f: &mut FunctionBuilder<'_>, q: Value) -> BResult { - let zero = k(f, 0)?; - let one = k(f, 1)?; - let two = k(f, 2)?; - let three = k(f, 3)?; - let p = f.binary(BinOp::IAdd, self.start, q)?; - let unwrapped = f.binary(BinOp::UGreaterThanEqual, p, self.start)?; - let below = f.binary(BinOp::ULessThan, p, self.inside)?; - let valid = f.binary(BinOp::LogicalAnd, unwrapped, below)?; - let shift = f.select(self.wide, two, one)?; - let offset = f.binary(BinOp::ShiftLeftLogical, p, shift)?; - let byte = f.binary(BinOp::IAdd, self.first_byte, offset)?; - let word = f.binary(BinOp::ShiftRightLogical, byte, two)?; - let indexed = f.unary(UnOp::LogicalNot, self.sequential)?; - let read = f.binary(BinOp::LogicalAnd, valid, indexed)?; - let safe = f.select(read, word, zero)?; - let loaded = contained(f, self.indices, safe)?; - let half = f.binary(BinOp::BitwiseAnd, byte, two)?; - let bits = f.binary(BinOp::ShiftLeftLogical, half, three)?; - let shifted = f.binary(BinOp::ShiftRightLogical, loaded, bits)?; - let mask = k(f, 0xFFFF)?; - let narrow = f.binary(BinOp::BitwiseAnd, shifted, mask)?; - let value = f.select(self.wide, loaded, narrow)?; - let value = f.select(valid, value, zero)?; - f.select(self.sequential, q, value) - } -} - -/// The pass's dispatch of `phase` for `program` as a typed module, before serialization: the -/// module [`index_rewrite_module`] serializes, which the CPU interpreter runs. Its bindings are the -/// symbols [`WORDS`], [`ARGUMENTS`], [`INDICES`], [`OUTPUT`] and [`STATUS`]. -pub fn rewrite_typed_module(program: RewriteProgram, phase: RewritePhase) -> BResult { - typed_module_of(program, Form::Phase(phase)) -} - -/// The dispatch of a run of `program`'s draws ([`IndexRewriteRun`]) as a typed module, before -/// serialization: the module [`index_rewrite_run_module`] serializes. Its bindings are -/// [`index_rewrite_module`]'s, the words those of the run's slots. -pub fn rewrite_run_typed_module(program: RewriteProgram) -> BResult { - typed_module_of(program, Form::Run) -} - -/// What one dispatch of the pass does. -#[derive(Clone, Copy)] -enum Form { - /// One phase of one draw. - Phase(RewritePhase), - /// Every phase of one draw of one group per workgroup, the draw's words its slot's. - Run, -} - -/// The module of `program`'s dispatch of `form`. -fn typed_module_of(program: RewriteProgram, form: Form) -> BResult { - let mut b = ModuleBuilder::new(); - let u32_ = b.ty(Type::Int { - width: 32, - signed: false, - })?; - let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; - let most = b.constant(Constant::Scalar { - ty: u32_, - bits: ConstBits(u64::from(IndexRewritePass::MAX_GROUPS)), - })?; - let list_ty = b.ty(Type::Array { - elem: u32_, - len: most, - stride: None, - })?; - // Per run (count and write) or per group (place): its primitives where its first piece's - // positions before it are even, then those before it; the same where they are odd; the start - // of its last piece, then of the piece it begins in. - let counts = b.plain_global(StorageClass::Workgroup, list_ty, None)?; - let odds = b.plain_global(StorageClass::Workgroup, list_ty, None)?; - let starts = b.plain_global(StorageClass::Workgroup, list_ty, None)?; - let words = words_buffer(&mut b, WORDS, u32_)?; - let arguments = words_buffer(&mut b, ARGUMENTS, u32_)?; - let indices = words_buffer(&mut b, INDICES, u32_)?; - let output = words_buffer(&mut b, OUTPUT, u32_)?; - let status = words_buffer(&mut b, STATUS, u32_)?; - let invocation = b.builtin( - crate::spv::BuiltIn::LocalInvocationIndex, - IoDir::Input, - u32_, - )?; - let workgroup = b.builtin(crate::spv::BuiltIn::WorkgroupId, IoDir::Input, uvec3)?; - let void = b.ty(Type::Void)?; - let mut f = b.function(void)?; - let g = Globals { - words: f.module().global_value(words)?, - arguments: f.module().global_value(arguments)?, - indices: f.module().global_value(indices)?, - output: f.module().global_value(output)?, - status: f.module().global_value(status)?, - counts: f.module().global_value(counts)?, - odds: f.module().global_value(odds)?, - starts: f.module().global_value(starts)?, - slot: None, - u32_, - }; - let invocation = f.module().global_value(invocation)?; - let lin = f.load(invocation, MemAccess::default())?; - let workgroup = f.module().global_value(workgroup)?; - let workgroup = f.load(workgroup, MemAccess::default())?; - let group = f.composite_extract(workgroup, &[0])?; - // A run's workgroup is its draw's slot, and its draw's only group. - let (g, at) = match form { - Form::Phase(_) => (g, Invocation { lin, group }), - Form::Run => { - let per = k(&mut f, IndexRewriteRun::SLOT_WORDS)?; - let first = f.binary(BinOp::IMul, group, per)?; - let group = k(&mut f, 0)?; - let g = Globals { - slot: Some(first), - ..g - }; - (g, Invocation { lin, group }) - } - }; - let d = DrawWalk::read(&mut f, g, program)?; - match form { - Form::Phase(RewritePhase::Count) => count_phase(&mut f, g, d, at)?, - Form::Phase(RewritePhase::Place) => place_phase(&mut f, g, d, lin)?, - Form::Phase(RewritePhase::Write) => write_phase(&mut f, g, d, at)?, - Form::Run => { - count_phase(&mut f, g, d, at)?; - phase_barrier(&mut f)?; - place_phase(&mut f, g, d, lin)?; - phase_barrier(&mut f)?; - write_phase(&mut f, g, d, at)?; - } - } - f.ret(None)?; - let id = f.finish()?; - b.entry( - ExecModel::GLCompute, - id, - vec![ExecMode::LocalSize { - x: IndexRewriteModule::LOCAL_SIZE, - y: 1, - z: 1, - }], - )?; - b.finalize() -} - -/// The module's buffers and workgroup lists, and its `u32` type. -#[derive(Clone, Copy)] -struct Globals { - words: Value, - /// A run's draw: the first of its slot's words ([`IndexRewriteRun::SLOT_WORDS`] per - /// workgroup), from which its words lie as a pass's do; `None` for a pass's dispatch. - slot: Option, - arguments: Value, - indices: Value, - output: Value, - status: Value, - /// Per run or group: its primitives where its first piece's positions before it are even, - /// then those before it. - counts: Value, - /// Per run or group: its primitives where its first piece's positions before it are odd. - odds: Value, - /// Per run or group: the start of its last piece, then of the piece it begins in. - starts: Value, - u32_: TypeId, -} - -/// One entry of the workgroup lists: its primitives where its first piece's positions before it -/// are even and where they are odd, and the start of its last piece (0 for none). -#[derive(Clone, Copy)] -struct Entry { - even: Value, - odd: Value, - start: Value, -} - -impl Globals { - /// The index into the words buffer of the draw's word `index`: past a run's slot's start. - fn word(self, f: &mut FunctionBuilder<'_>, index: Value) -> BResult { - match self.slot { - None => Ok(index), - Some(first) => f.binary(BinOp::IAdd, first, index), - } - } - - /// The draw's word `index`. - fn word_load(self, f: &mut FunctionBuilder<'_>, index: Value) -> BResult { - let i = self.word(f, index)?; - load(f, self.words, i) - } - - /// The draw's word `index`, a constant. - fn word_load_at(self, f: &mut FunctionBuilder<'_>, index: u32) -> BResult { - let i = k(f, index)?; - self.word_load(f, i) - } - - /// Store `v` as the draw's word `index`. - fn word_store(self, f: &mut FunctionBuilder<'_>, index: Value, v: Value) -> BResult<()> { - let i = self.word(f, index)?; - store(f, self.words, i, v) - } - - /// Store `v` as the draw's word `index`, a constant. - fn word_store_at(self, f: &mut FunctionBuilder<'_>, index: u32, v: Value) -> BResult<()> { - let i = k(f, index)?; - self.word_store(f, i, v) - } - - /// A `u32` function variable holding `init`, by its pointer. - fn local(self, f: &mut FunctionBuilder<'_>, init: Value) -> BResult { - let var = f.local_var(self.u32_, None)?; - let ptr = f.var_ptr(var)?; - f.store(ptr, init, MemAccess::default())?; - Ok(ptr) - } - - /// Store `entry` as entry `i` of the workgroup lists. - fn list(self, f: &mut FunctionBuilder<'_>, i: Value, entry: Entry) -> BResult<()> { - for (list, v) in [ - (self.counts, entry.even), - (self.odds, entry.odd), - (self.starts, entry.start), - ] { - let p = f.access_chain(list, &[i])?; - f.store(p, v, MemAccess::default())?; - } - Ok(()) - } - - /// Entry `i` of the workgroup lists. - fn entry(self, f: &mut FunctionBuilder<'_>, i: Value) -> BResult { - let mut read = |list| -> BResult { - let p = f.access_chain(list, &[i])?; - f.load(p, MemAccess::default()) - }; - Ok(Entry { - even: read(self.counts)?, - odd: read(self.odds)?, - start: read(self.starts)?, - }) - } - - /// The first of group `group`'s [`GROUP_WORDS`] words. - fn group_word(self, f: &mut FunctionBuilder<'_>, group: Value) -> BResult { - let per = k(f, GROUP_WORDS)?; - let first = k(f, Output::Groups as u32)?; - let w = f.binary(BinOp::IMul, group, per)?; - f.binary(BinOp::IAdd, first, w) - } -} - -/// An invocation: its index in its workgroup, and its workgroup's along x. -#[derive(Clone, Copy)] -struct Invocation { - lin: Value, - group: Value, -} - -/// An invocation's run of positions, `[lo, hi)`; its place among the runs, and the runs. -#[derive(Clone, Copy)] -struct Run { - lo: Value, - hi: Value, - t: Value, - runs: Value, -} - -/// What every dispatch of a pass reads of its draw: how the walk fetches, `k'`, how far it walks, -/// Metal's other arguments and the output's terms. -#[derive(Clone, Copy)] -struct DrawWalk { - fetch: Fetch, - restart: Value, - /// The draw's positions. - count: Value, - /// The positions the runs walk. - walked: Value, - /// The draw's positions past the walk. - tail: Value, - /// The walk's positions per run. - chunk: Value, - instances: Value, - base: Value, - base_instance: Value, - capacity: Value, - /// The first word of an owned output: a run's draw's region's, else 0. - owned: Value, - /// Whether the output is the index pool. - pooled: Value, - /// The groups, from 1 to `MAX_GROUPS`. - groups: Value, - /// The order's word ([`RewriteOrder::word`]). - order: Value, - /// 1 where the list is drawn in the private list form, else 0. - listed: Value, - program: RewriteProgram, -} - -impl DrawWalk { - fn read(f: &mut FunctionBuilder<'_>, g: Globals, program: RewriteProgram) -> BResult { - let zero = k(f, 0)?; - let one = k(f, 1)?; - let argument_word = g.word_load_at(f, Parameter::ArgumentsWord as u32)?; - let first_byte = g.word_load_at(f, Parameter::IndicesByte as u32)?; - let inside = g.word_load_at(f, Parameter::Inside as u32)?; - let wide = g.word_load_at(f, Parameter::Wide as u32)?; - let restart = g.word_load_at(f, Parameter::Restart as u32)?; - let capacity = g.word_load_at(f, Parameter::Capacity as u32)?; - let pooled = g.word_load_at(f, Parameter::Pooled as u32)?; - let groups = g.word_load_at(f, Parameter::Groups as u32)?; - let sequential = g.word_load_at(f, Parameter::Sequential as u32)?; - let order = g.word_load_at(f, Parameter::Order as u32)?; - let listed = g.word_load_at(f, Parameter::Listed as u32)?; - let owned = match g.slot { - Some(_) => g.word_load_at(f, Parameter::OwnedFirst as u32)?, - None => zero, - }; - let listed = f.glsl(GlslOp::UMin, &[listed, one])?; - // A run's draw is its workgroup's alone. - let groups = match g.slot { - Some(_) => one, - None => { - let most = k(f, IndexRewritePass::MAX_GROUPS)?; - let groups = f.glsl(GlslOp::UMin, &[groups, most])?; - f.glsl(GlslOp::UMax, &[groups, one])? - } - }; - let wide = f.binary(BinOp::INotEqual, wide, zero)?; - let pooled = f.binary(BinOp::INotEqual, pooled, zero)?; - let sequential = f.binary(BinOp::INotEqual, sequential, zero)?; - // Metal's arguments: count, instances, first index, base vertex, base instance; an - // indirect draw's from its buffer, a direct draw's from the words. A draw without indices - // has count, instances, vertex start and base instance: its vertex start is its base - // vertex, and it starts at position 0. - let indirect = f.binary(BinOp::INotEqual, argument_word, zero)?; - let at = f.binary(BinOp::ISub, argument_word, one)?; - let mut argument = Vec::with_capacity(5); - for i in 0..5 { - let i = k(f, i)?; - let w = f.binary(BinOp::IAdd, at, i)?; - let w = f.select(indirect, w, zero)?; - let read = contained(f, g.arguments, w)?; - let given = k(f, Parameter::Arguments as u32)?; - let given = f.binary(BinOp::IAdd, given, i)?; - let given = g.word_load(f, given)?; - argument.push(f.select(indirect, read, given)?); - } - let (count, instances) = (argument[0], argument[1]); - let start = f.select(sequential, zero, argument[2])?; - let base = f.select(sequential, argument[2], argument[3])?; - let base_instance = f.select(sequential, argument[3], argument[4])?; - // A draw without indices holds every position. - let inside = f.select(sequential, count, inside)?; - let fetch = Fetch { - indices: g.indices, - first_byte, - inside, - start, - wide, - sequential, - }; - // The walk: the positions inside the buffer from the first index, and the program's span - // past them (which read 0); past it every position reads 0. - let span = k(f, program.span())?; - let held = saturating_sub(f, inside, start)?; - let reach = saturating_add(f, held, span)?; - let walked = f.glsl(GlslOp::UMin, &[count, reach])?; - let tail = f.binary(BinOp::ISub, count, walked)?; - let lanes = k(f, IndexRewriteModule::LOCAL_SIZE)?; - let runs = f.binary(BinOp::IMul, groups, lanes)?; - let chunk = div_ceil(f, walked, runs)?; - Ok(DrawWalk { - fetch, - restart, - count, - walked, - tail, - chunk, - instances, - base, - base_instance, - capacity, - owned, - pooled, - groups, - order, - listed, - program, - }) - } - - /// A primitive whose vertices are `first` in Metal's order at mode 0 and `last` at mode 1, in - /// the draw's order ([`RewriteOrder::arrange`]). - fn ordered( - self, - f: &mut FunctionBuilder<'_>, - first: &[Value], - last: &[Value], - ) -> BResult> { - let n = last.len(); - let first_word = k(f, RewriteOrder::First.word())?; - let last_word = k(f, RewriteOrder::Last.word())?; - let is_first = f.binary(BinOp::IEqual, self.order, first_word)?; - let is_last = f.binary(BinOp::IEqual, self.order, last_word)?; - let mut out = Vec::with_capacity(n); - for i in 0..n { - let led = f.select(is_last, last[i], last[(i + n - 1) % n])?; - out.push(f.select(is_first, first[i], led)?); - } - Ok(out) - } - - /// Whether a position of index `value` restarts: where the program restarts, the draw has - /// indices, and `value` is `k'`. - fn restarts(self, f: &mut FunctionBuilder<'_>, value: Value) -> BResult { - if !self.program.restarts() { - return boolean(f, false); - } - let at = f.binary(BinOp::IEqual, value, self.restart)?; - let indexed = f.unary(UnOp::LogicalNot, self.fetch.sequential)?; - f.binary(BinOp::LogicalAnd, at, indexed) - } - - /// The first position of run `t` of `groups · LOCAL_SIZE` runs (`t` among them, or the - /// first past them): `t · chunk`, at most the walk. Below 2^32: `t · chunk` is at most the - /// walk where the chunk is at least the runs, and below 2^31 where it is fewer. - fn lo_of(self, f: &mut FunctionBuilder<'_>, t: Value) -> BResult { - let from = f.binary(BinOp::IMul, t, self.chunk)?; - f.glsl(GlslOp::UMin, &[from, self.walked]) - } - - /// `at`'s run: one of `groups · LOCAL_SIZE` runs of the walk's positions, in order, each of - /// as many as the walk over the runs, rounded up; empty where its workgroup is past the - /// groups. - fn run(self, f: &mut FunctionBuilder<'_>, at: Invocation) -> BResult { - let lanes = k(f, IndexRewriteModule::LOCAL_SIZE)?; - let runs = f.binary(BinOp::IMul, self.groups, lanes)?; - let before = f.binary(BinOp::IMul, at.group, lanes)?; - let t = f.binary(BinOp::IAdd, before, at.lin)?; - let among = f.binary(BinOp::ULessThan, at.group, self.groups)?; - let from = self.lo_of(f, t)?; - let lo = f.select(among, from, self.walked)?; - let end = saturating_add(f, lo, self.chunk)?; - let hi = f.glsl(GlslOp::UMin, &[end, self.walked])?; - Ok(Run { lo, hi, t, runs }) - } - - /// Before position `lo`: the positions of its piece there, at most `span - 1` (those of - /// `lo - 1`, `lo - 2`, ... that exist, back to the first that restarts), and the indices at - /// `lo - 1`, `lo - 2` and `lo - 3` (0 where there is none, or the span does not reach). - fn behind(self, f: &mut FunctionBuilder<'_>, lo: Value) -> BResult<(Value, [Value; 3])> { - let zero = k(f, 0)?; - let mut values = [zero; 3]; - let mut streak = zero; - let mut all = boolean(f, true)?; - for n in 1..self.program.span() { - let back = k(f, n)?; - let has = f.binary(BinOp::UGreaterThanEqual, lo, back)?; - let q = f.binary(BinOp::ISub, lo, back)?; - let fetched = self.fetch.at(f, q)?; - let value = f.select(has, fetched, zero)?; - let restarts = self.restarts(f, value)?; - let other = f.unary(UnOp::LogicalNot, restarts)?; - let live = f.binary(BinOp::LogicalAnd, has, other)?; - all = f.binary(BinOp::LogicalAnd, all, live)?; - let n_ = k(f, n)?; - streak = f.select(all, n_, streak)?; - values[n as usize - 1] = value; - } - Ok((streak, values)) - } - - /// Position `q`, of a piece that starts at `piece`, reads `value`: whether it restarts, and - /// whether it completes a step, its piece's positions through it (at most the span) at - /// `streak`. A strip, line loop and fan complete at every position the span reaches back - /// from; quads at every fourth position of the draw; a quad strip at every second position of - /// its piece the span reaches back from. - fn step( - self, - f: &mut FunctionBuilder<'_>, - (streak, q, piece): (Value, Value, Value), - value: Value, - ) -> BResult<(Value, Value)> { - let zero = k(f, 0)?; - let one = k(f, 1)?; - let span = k(f, self.program.span())?; - let restarts = self.restarts(f, value)?; - let s = f.load(streak, MemAccess::default())?; - let grown = f.binary(BinOp::IAdd, s, one)?; - let grown = f.glsl(GlslOp::UMin, &[grown, span])?; - let s = f.select(restarts, zero, grown)?; - f.store(streak, s, MemAccess::default())?; - let spanned = f.binary(BinOp::UGreaterThanEqual, s, span)?; - let completes = match self.program { - RewriteProgram::Quads | RewriteProgram::LineList | RewriteProgram::TriangleList => { - // Every `span`th position of the draw, which never restarts. - let last = k(f, self.program.span() - 1)?; - let phase = f.binary(BinOp::UMod, q, span)?; - f.binary(BinOp::IEqual, phase, last)? - } - RewriteProgram::QuadStrip => { - let into = f.binary(BinOp::ISub, q, piece)?; - let parity = f.binary(BinOp::BitwiseAnd, into, one)?; - let odd = f.binary(BinOp::INotEqual, parity, zero)?; - f.binary(BinOp::LogicalAnd, spanned, odd)? - } - _ => spanned, - }; - Ok((restarts, completes)) - } - - /// `run`'s primitives where the piece it begins in starts at `piece` (only its parity - /// matters, so any position of the same parity stands for it), and the start of its last - /// piece (0 where nothing in it restarts), its piece's positions before it `streak`. - fn count( - self, - f: &mut FunctionBuilder<'_>, - g: Globals, - run: Run, - (streak, piece): (Value, Value), - ) -> BResult<(Value, Value)> { - let zero = k(f, 0)?; - let one = k(f, 1)?; - let streak = g.local(f, streak)?; - let piece = g.local(f, piece)?; - let count = g.local(f, zero)?; - let start = g.local(f, zero)?; - let per_step = self.program.per_step(); - for_range(f, g.u32_, (run.lo, run.hi, one), move |f, q| { - let value = self.fetch.at(f, q)?; - let p = f.load(piece, MemAccess::default())?; - let (restarts, completes) = self.step(f, (streak, q, p), value)?; - let zero = k(f, 0)?; - let one = k(f, 1)?; - let per = k(f, per_step)?; - let add = f.select(completes, per, zero)?; - let c = f.load(count, MemAccess::default())?; - let c = f.binary(BinOp::IAdd, c, add)?; - f.store(count, c, MemAccess::default())?; - let next = f.binary(BinOp::IAdd, q, one)?; - let s = f.load(start, MemAccess::default())?; - let s = f.select(restarts, next, s)?; - f.store(start, s, MemAccess::default())?; - let p = f.select(restarts, next, p)?; - f.store(piece, p, MemAccess::default()) - })?; - let count = f.load(count, MemAccess::default())?; - let start = f.load(start, MemAccess::default())?; - Ok((count, start)) - } - - /// `run`'s entry: its primitives under both parities of its first piece's positions before - /// it (alike but for a quad strip), and the start of its last piece, its piece's positions - /// before it `streak`. - fn entry( - self, - f: &mut FunctionBuilder<'_>, - g: Globals, - run: Run, - streak: Value, - ) -> BResult { - let (even, start) = self.count(f, g, run, (streak, run.lo))?; - let odd = match self.program { - RewriteProgram::QuadStrip => { - let one = k(f, 1)?; - let before = f.binary(BinOp::ISub, run.lo, one)?; - self.count(f, g, run, (streak, before))?.0 - } - _ => even, - }; - Ok(Entry { even, odd, start }) - } - - /// An entry's primitives where the piece it begins in starts at `piece`, its first position - /// `lo`. - fn placed( - self, - f: &mut FunctionBuilder<'_>, - entry: Entry, - (lo, piece): (Value, Value), - ) -> BResult { - if self.program != RewriteProgram::QuadStrip { - return Ok(entry.even); - } - let zero = k(f, 0)?; - let one = k(f, 1)?; - let into = f.binary(BinOp::ISub, lo, piece)?; - let parity = f.binary(BinOp::BitwiseAnd, into, one)?; - let odd = f.binary(BinOp::INotEqual, parity, zero)?; - f.select(odd, entry.odd, entry.even) - } -} - -/// The entries of a scan: `n` of the workgroup lists' first, entry `i` starting at run -/// `first + i · stride` (its first position, which a quad strip's parity reads). -#[derive(Clone, Copy)] -struct Entries { - n: Value, - first: Value, - stride: Value, -} - -/// The first invocation's sums over `entries` from the piece start `carry`, without changing the -/// lists: their primitives, and the start of the last piece among them (0 for none). -fn total( - f: &mut FunctionBuilder<'_>, - g: Globals, - d: DrawWalk, - entries: Entries, - carry: Value, -) -> BResult<(Value, Value)> { - let zero = k(f, 0)?; - let one = k(f, 1)?; - let place = g.local(f, zero)?; - let carry = g.local(f, carry)?; - let last = g.local(f, zero)?; - for_range(f, g.u32_, (zero, entries.n, one), move |f, i| { - let entry = g.entry(f, i)?; - let t = f.binary(BinOp::IMul, i, entries.stride)?; - let t = f.binary(BinOp::IAdd, entries.first, t)?; - let lo = d.lo_of(f, t)?; - let begun = f.load(carry, MemAccess::default())?; - let count = d.placed(f, entry, (lo, begun))?; - let before = f.load(place, MemAccess::default())?; - let next = saturating_add(f, before, count)?; - f.store(place, next, MemAccess::default())?; - let zero = k(f, 0)?; - let restarted = f.binary(BinOp::INotEqual, entry.start, zero)?; - let next = f.select(restarted, entry.start, begun)?; - f.store(carry, next, MemAccess::default())?; - let l = f.load(last, MemAccess::default())?; - let l = f.glsl(GlslOp::UMax, &[l, entry.start])?; - f.store(last, l, MemAccess::default()) - })?; - let place = f.load(place, MemAccess::default())?; - let last = f.load(last, MemAccess::default())?; - Ok((place, last)) -} - -/// The first invocation's scan of `entries`, in order, from `place` and `carry`: each even count -/// becomes the primitives before its entry (`place` and the counts before it, saturated, each -/// taken at its entry's parity), each start the start of the piece its entry begins in (`carry`, -/// or the last start before it). The two totals' pointers. -fn scan( - f: &mut FunctionBuilder<'_>, - g: Globals, - d: DrawWalk, - entries: Entries, - (place, carry): (Value, Value), -) -> BResult<(Value, Value)> { - let zero = k(f, 0)?; - let one = k(f, 1)?; - let place = g.local(f, place)?; - let carry = g.local(f, carry)?; - for_range(f, g.u32_, (zero, entries.n, one), move |f, i| { - let entry = g.entry(f, i)?; - let t = f.binary(BinOp::IMul, i, entries.stride)?; - let t = f.binary(BinOp::IAdd, entries.first, t)?; - let lo = d.lo_of(f, t)?; - let begun = f.load(carry, MemAccess::default())?; - let count = d.placed(f, entry, (lo, begun))?; - let before = f.load(place, MemAccess::default())?; - let p = f.access_chain(g.counts, &[i])?; - f.store(p, before, MemAccess::default())?; - let next = saturating_add(f, before, count)?; - f.store(place, next, MemAccess::default())?; - let p = f.access_chain(g.starts, &[i])?; - f.store(p, begun, MemAccess::default())?; - let zero = k(f, 0)?; - let restarted = f.binary(BinOp::INotEqual, entry.start, zero)?; - let next = f.select(restarted, entry.start, begun)?; - f.store(carry, next, MemAccess::default()) - })?; - Ok((place, carry)) -} - -/// [`RewritePhase::Count`]: each run's primitives and last piece's start, summed over the -/// workgroup into its group's words, under both parities of the group's first piece's positions -/// before it. -fn count_phase( - f: &mut FunctionBuilder<'_>, - g: Globals, - d: DrawWalk, - at: Invocation, -) -> BResult<()> { - let run = d.run(f, at)?; - let (streak, _) = d.behind(f, run.lo)?; - let entry = d.entry(f, g, run, streak)?; - g.list(f, at.lin, entry)?; - barrier(f)?; - let zero = k(f, 0)?; - let first = f.binary(BinOp::IEqual, at.lin, zero)?; - let among = f.binary(BinOp::ULessThan, at.group, d.groups)?; - let first = f.binary(BinOp::LogicalAnd, first, among)?; - when(f, first, move |f| { - let one = k(f, 1)?; - let two = k(f, 2)?; - let lanes = k(f, IndexRewriteModule::LOCAL_SIZE)?; - let first_run = f.binary(BinOp::IMul, at.group, lanes)?; - let entries = Entries { - n: lanes, - first: first_run, - stride: one, - }; - let lo = d.lo_of(f, first_run)?; - let (even, last) = total(f, g, d, entries, lo)?; - let odd = match d.program { - RewriteProgram::QuadStrip => { - let before = f.binary(BinOp::ISub, lo, one)?; - total(f, g, d, entries, before)?.0 - } - _ => even, - }; - let w = g.group_word(f, at.group)?; - g.word_store(f, w, even)?; - let w1 = f.binary(BinOp::IAdd, w, one)?; - g.word_store(f, w1, odd)?; - let w2 = f.binary(BinOp::IAdd, w, two)?; - g.word_store(f, w2, last) - }) -} - -/// The primitives past the walk, every position there reading 0, after the walk's last piece, -/// which starts at `last`: none where `k'` is 0 and the program restarts (each restarts); else a -/// strip's, line loop's and fan's one at each position, quads' two at every fourth position of -/// the draw, a list's one at every second or third, and a quad strip's two at every second -/// position of its piece (the walk ends the span past the buffer, so the span reaches back from -/// each). -fn tail_primitives(f: &mut FunctionBuilder<'_>, d: DrawWalk, last: Value) -> BResult { - let zero = k(f, 0)?; - let two = k(f, 2)?; - let some = f.binary(BinOp::INotEqual, d.restart, zero)?; - match d.program { - RewriteProgram::LineStrip | RewriteProgram::TriangleStrip => f.select(some, d.tail, zero), - RewriteProgram::LineLoop | RewriteProgram::TriangleFan => Ok(d.tail), - RewriteProgram::Quads | RewriteProgram::LineList | RewriteProgram::TriangleList => { - // The positions `q` in `[walked, count)` with `q mod span = span - 1`, each of - // `per_step` primitives. - let span = k(f, d.program.span())?; - let to = f.binary(BinOp::UDiv, d.count, span)?; - let from = f.binary(BinOp::UDiv, d.walked, span)?; - let steps = f.binary(BinOp::ISub, to, from)?; - let per = k(f, d.program.per_step())?; - f.binary(BinOp::IMul, steps, per) - } - RewriteProgram::QuadStrip => { - // The positions `q` in `[walked, count)` with `q - last` odd. - let pairs = |f: &mut FunctionBuilder<'_>, n: Value| -> BResult { - let one = k(f, 1)?; - let into = f.binary(BinOp::ISub, n, last)?; - f.binary(BinOp::ShiftRightLogical, into, one) - }; - let to = pairs(f, d.count)?; - let from = pairs(f, d.walked)?; - let quads = f.binary(BinOp::ISub, to, from)?; - let quads = f.binary(BinOp::IMul, quads, two)?; - f.select(some, quads, zero) - } - } -} - -/// [`RewritePhase::Place`]: each group's words become the primitives before it and the start of -/// the piece it begins in; the output is reserved, the draw written, and what the write -/// dispatch needs stated. -fn place_phase(f: &mut FunctionBuilder<'_>, g: Globals, d: DrawWalk, lin: Value) -> BResult<()> { - let lanes = k(f, IndexRewriteModule::LOCAL_SIZE)?; - // The groups' words into the workgroup lists, the invocations taking turns. - for_range(f, g.u32_, (lin, d.groups, lanes), move |f, i| { - let one = k(f, 1)?; - let two = k(f, 2)?; - let w = g.group_word(f, i)?; - let even = g.word_load(f, w)?; - let w1 = f.binary(BinOp::IAdd, w, one)?; - let odd = g.word_load(f, w1)?; - let w2 = f.binary(BinOp::IAdd, w, two)?; - let start = g.word_load(f, w2)?; - g.list(f, i, Entry { even, odd, start }) - })?; - barrier(f)?; - let zero = k(f, 0)?; - let first = f.binary(BinOp::IEqual, lin, zero)?; - when(f, first, move |f| { - let zero = k(f, 0)?; - let one = k(f, 1)?; - let vk_ = k(f, d.program.vertices())?; - let lanes = k(f, IndexRewriteModule::LOCAL_SIZE)?; - let entries = Entries { - n: d.groups, - first: zero, - stride: lanes, - }; - let (total, last) = scan(f, g, d, entries, (zero, zero))?; - for_range(f, g.u32_, (zero, d.groups, one), move |f, i| { - let one = k(f, 1)?; - let w = g.group_word(f, i)?; - let p = f.access_chain(g.counts, &[i])?; - let before = f.load(p, MemAccess::default())?; - g.word_store(f, w, before)?; - let w = f.binary(BinOp::IAdd, w, one)?; - let p = f.access_chain(g.starts, &[i])?; - let begun = f.load(p, MemAccess::default())?; - g.word_store(f, w, begun) - })?; - let walked_total = f.load(total, MemAccess::default())?; - let last = f.load(last, MemAccess::default())?; - let tail_drawn = tail_primitives(f, d, last)?; - let primitives = saturating_add(f, walked_total, tail_drawn)?; - // A line loop's last segment, from its last position back to its first. - let primitives = match d.program { - RewriteProgram::LineLoop => { - let two = k(f, 2)?; - let closes = f.binary(BinOp::UGreaterThanEqual, d.count, two)?; - let closing = f.select(closes, one, zero)?; - saturating_add(f, primitives, closing)? - } - _ => primitives, - }; - // The output's indices, where they fit a `u32`: where the product's high word is 0 - // (`replay::checked_mul`, whose docs say why). In the private list form Metal's base - // vertex takes a word before them. - let (written, past) = checked_mul(f, primitives, vk_, zero)?; - let words_needed = f.binary(BinOp::IAdd, written, d.listed)?; - let wrapped = f.binary(BinOp::ULessThan, words_needed, written)?; - let past = f.binary(BinOp::LogicalOr, past, wrapped)?; - let countable = f.unary(UnOp::LogicalNot, past)?; - // Placed in the pool's room, or in the draw's own region (a run's draws' always: the run - // reads no counter). - let counter = match g.slot { - Some(_) => None, - None => { - let counter_ptr = word_ptr(f, g.output, zero)?; - let counter = f.load(counter_ptr, MemAccess::default())?; - Some((counter_ptr, counter)) - } - }; - let used = match counter { - Some((_, counter)) => f.glsl(GlslOp::UMin, &[counter, d.capacity])?, - None => zero, - }; - let room = f.binary(BinOp::ISub, d.capacity, used)?; - let four = k(f, 4)?; - let room = f.binary(BinOp::UDiv, room, four)?; - let room = f.select(d.pooled, room, d.capacity)?; - let fits = f.binary(BinOp::ULessThanEqual, words_needed, room)?; - let ok = f.binary(BinOp::LogicalAnd, countable, fits)?; - let reserve = f.binary(BinOp::LogicalAnd, ok, d.pooled)?; - if let Some((counter_ptr, _)) = counter { - when(f, reserve, move |f| { - let four = k(f, 4)?; - let bytes = f.binary(BinOp::IMul, words_needed, four)?; - let next = f.binary(BinOp::IAdd, used, bytes)?; - f.store(counter_ptr, next, MemAccess::default()) - })?; - } - // The list's first index, past the base vertex's word in the private list form. - let first_index = f.binary(BinOp::UDiv, used, four)?; - let first_index = f.select(d.pooled, first_index, d.owned)?; - let first_index = f.binary(BinOp::IAdd, first_index, d.listed)?; - let header = k(f, (IndexRewritePass::POOL_HEADER_BYTES / 4) as u32)?; - let pool_base = f.binary(BinOp::IAdd, header, first_index)?; - let base_word = f.select(d.pooled, pool_base, first_index)?; - let ok_word = f.select(ok, one, zero)?; - for (word, value) in [ - (Output::Base, base_word), - (Output::Written, ok_word), - (Output::TailAt, walked_total), - (Output::Tail, tail_drawn), - ] { - g.word_store_at(f, word as u32, value)?; - } - let drawn = f.select(ok, written, zero)?; - let primitives_drawn = f.select(ok, primitives, zero)?; - // An indexed draw's `VkDrawIndexedIndirectCommand`, or in the private list form a - // `VkDrawIndirectCommand` of the list's positions from its first index as first vertex. - let listed = f.binary(BinOp::INotEqual, d.listed, zero)?; - let fourth = f.select(listed, d.base_instance, d.base)?; - let fifth = f.select(listed, zero, d.base_instance)?; - for (i, value) in [drawn, d.instances, first_index, fourth, fifth] - .into_iter() - .enumerate() - { - g.word_store_at(f, Output::Draw as u32 + i as u32, value)?; - } - g.word_store_at(f, Output::Primitives as u32, primitives_drawn)?; - // A draw whose primitives the output cannot hold draws nothing and says so. - let over = f.unary(UnOp::LogicalNot, ok)?; - when(f, over, move |f| { - let word = k(f, StatusWord::Status.index())?; - let bit = k(f, StatusBits::INDEX_POOL_OVERFLOW.0)?; - let p = word_ptr(f, g.status, word)?; - f.atomic(AtomicOp::Or, p, Scope::Device, Semantics::RELAXED, bit)?; - Ok(()) - }) - }) -} - -/// The list primitives a completing position `q` writes, from the indices at `q - 3` to `q` -/// (`a`, `b`, `c`, `value`), a fan's first index `hub`, and the start of its piece `piece`, each -/// in the draw's order ([`DrawWalk::ordered`]). -fn primitives( - f: &mut FunctionBuilder<'_>, - d: DrawWalk, - (a, b, c, value): (Value, Value, Value, Value), - (hub, q, piece): (Value, Value, Value), -) -> BResult>> { - let same = |f: &mut FunctionBuilder<'_>, p: &[Value]| d.ordered(f, p, p); - Ok(match d.program { - RewriteProgram::LineStrip | RewriteProgram::LineLoop | RewriteProgram::LineList => { - vec![same(f, &[c, value])?] - } - RewriteProgram::TriangleStrip => { - // Vulkan's strip orders: the piece's `i`th triangle (`q - piece - 2`) of positions - // `(i, i + 1, i + 2)` takes them so where `i` is even; where it is odd, `(i, i + 2, - // i + 1)` at mode 0 and `(i + 1, i, i + 2)` at mode 1. - let zero = k(f, 0)?; - let one = k(f, 1)?; - let i = f.binary(BinOp::ISub, q, piece)?; - let parity = f.binary(BinOp::BitwiseAnd, i, one)?; - let odd = f.binary(BinOp::INotEqual, parity, zero)?; - let second = f.select(odd, value, c)?; - let third = f.select(odd, c, value)?; - let led = f.select(odd, c, b)?; - let then = f.select(odd, b, c)?; - vec![d.ordered(f, &[b, second, third], &[led, then, value])?] - } - RewriteProgram::TriangleFan => vec![same(f, &[hub, c, value])?], - RewriteProgram::Quads => vec![same(f, &[a, b, value])?, same(f, &[b, c, value])?], - RewriteProgram::QuadStrip => vec![same(f, &[a, b, value])?, same(f, &[c, a, value])?], - RewriteProgram::TriangleList => vec![same(f, &[b, c, value])?], - }) -} - -/// [`RewritePhase::Write`]: each run, placed after the runs before it from its group's words, -/// writes its primitives where the draw is written; the runs then write the primitives past the -/// walk, and the first invocation a line loop's last segment. -fn write_phase( - f: &mut FunctionBuilder<'_>, - g: Globals, - d: DrawWalk, - at: Invocation, -) -> BResult<()> { - let program = d.program; - let run = d.run(f, at)?; - let (streak, behind) = d.behind(f, run.lo)?; - let entry = d.entry(f, g, run, streak)?; - g.list(f, at.lin, entry)?; - barrier(f)?; - let zero = k(f, 0)?; - let first = f.binary(BinOp::IEqual, at.lin, zero)?; - let among = f.binary(BinOp::ULessThan, at.group, d.groups)?; - let first = f.binary(BinOp::LogicalAnd, first, among)?; - when(f, first, move |f| { - let one = k(f, 1)?; - let lanes = k(f, IndexRewriteModule::LOCAL_SIZE)?; - let w = g.group_word(f, at.group)?; - let place = g.word_load(f, w)?; - let w = f.binary(BinOp::IAdd, w, one)?; - let carry = g.word_load(f, w)?; - let first_run = f.binary(BinOp::IMul, at.group, lanes)?; - let entries = Entries { - n: lanes, - first: first_run, - stride: one, - }; - scan(f, g, d, entries, (place, carry))?; - Ok(()) - })?; - barrier(f)?; - let written = g.word_load_at(f, Output::Written as u32)?; - let ok = f.binary(BinOp::INotEqual, written, zero)?; - let base_word = g.word_load_at(f, Output::Base as u32)?; - // In the private list form, Metal's base vertex in the word before the list, written once. - let listed = f.binary(BinOp::INotEqual, d.listed, zero)?; - let base_too = f.binary(BinOp::LogicalAnd, ok, listed)?; - let group0 = f.binary(BinOp::IEqual, at.group, zero)?; - let base_too = f.binary(BinOp::LogicalAnd, base_too, first)?; - let base_too = f.binary(BinOp::LogicalAnd, base_too, group0)?; - when(f, base_too, move |f| { - let one = k(f, 1)?; - let before = f.binary(BinOp::ISub, base_word, one)?; - contained_store(f, g.output, before, d.base) - })?; - let v = program.vertices(); - // A fan's first index, every triangle's first vertex. - let hub = match program { - RewriteProgram::TriangleFan => d.fetch.at(f, zero)?, - _ => zero, - }; - when(f, ok, move |f| { - let one = k(f, 1)?; - let vk_ = k(f, v)?; - let p = f.access_chain(g.counts, &[at.lin])?; - let place = f.load(p, MemAccess::default())?; - let p = f.access_chain(g.starts, &[at.lin])?; - let begun = f.load(p, MemAccess::default())?; - let into = f.binary(BinOp::IMul, place, vk_)?; - let at0 = f.binary(BinOp::IAdd, base_word, into)?; - let next_word = g.local(f, at0)?; - let streak = g.local(f, streak)?; - let piece = g.local(f, begun)?; - // The indices one, two and three positions back. - let old = g.local(f, behind[0])?; - let older = g.local(f, behind[1])?; - let oldest = g.local(f, behind[2])?; - for_range(f, g.u32_, (run.lo, run.hi, one), move |f, q| { - let value = d.fetch.at(f, q)?; - let p = f.load(piece, MemAccess::default())?; - let (restarts, completes) = d.step(f, (streak, q, p), value)?; - let one = k(f, 1)?; - let next = f.binary(BinOp::IAdd, q, one)?; - let p_next = f.select(restarts, next, p)?; - f.store(piece, p_next, MemAccess::default())?; - let a = f.load(oldest, MemAccess::default())?; - let b = f.load(older, MemAccess::default())?; - let c = f.load(old, MemAccess::default())?; - when(f, completes, move |f| { - let w = f.load(next_word, MemAccess::default())?; - let written = primitives(f, d, (a, b, c, value), (hub, q, p))?; - let mut slot = 0; - for primitive in written { - for index in primitive { - let i = k(f, slot)?; - let at = f.binary(BinOp::IAdd, w, i)?; - contained_store(f, g.output, at, index)?; - slot += 1; - } - } - let n = k(f, slot)?; - let next = f.binary(BinOp::IAdd, w, n)?; - f.store(next_word, next, MemAccess::default()) - })?; - f.store(oldest, b, MemAccess::default())?; - f.store(older, c, MemAccess::default())?; - f.store(old, value, MemAccess::default()) - })?; - // The primitives past the walk, the runs taking turns: every index 0, but a fan's first. - let tail_at = g.word_load_at(f, Output::TailAt as u32)?; - let tail = g.word_load_at(f, Output::Tail as u32)?; - for_range(f, g.u32_, (run.t, tail, run.runs), move |f, j| { - let vk_ = k(f, v)?; - let zero = k(f, 0)?; - let primitive = f.binary(BinOp::IAdd, tail_at, j)?; - let into = f.binary(BinOp::IMul, primitive, vk_)?; - let w = f.binary(BinOp::IAdd, base_word, into)?; - let indices: Vec = (0..v) - .map(|i| match (program, i) { - (RewriteProgram::TriangleFan, 0) => hub, - _ => zero, - }) - .collect(); - let indices = d.ordered(f, &indices, &indices)?; - for (i, index) in indices.into_iter().enumerate() { - let i = k(f, i as u32)?; - let slot = f.binary(BinOp::IAdd, w, i)?; - contained_store(f, g.output, slot, index)?; - } - Ok(()) - })?; - // A line loop's last segment, after every other: from its last position to its first. - if program == RewriteProgram::LineLoop { - let zero = k(f, 0)?; - let two = k(f, 2)?; - let closes = f.binary(BinOp::UGreaterThanEqual, d.count, two)?; - let t0 = f.binary(BinOp::IEqual, run.t, zero)?; - let writes = f.binary(BinOp::LogicalAnd, closes, t0)?; - when(f, writes, move |f| { - let one = k(f, 1)?; - let two = k(f, 2)?; - let zero = k(f, 0)?; - let last = f.binary(BinOp::ISub, d.count, one)?; - let from = d.fetch.at(f, last)?; - let to = d.fetch.at(f, zero)?; - let segment = d.ordered(f, &[from, to], &[from, to])?; - let primitive = f.binary(BinOp::IAdd, tail_at, tail)?; - let into = f.binary(BinOp::IMul, primitive, two)?; - let w = f.binary(BinOp::IAdd, base_word, into)?; - contained_store(f, g.output, w, segment[0])?; - let w = f.binary(BinOp::IAdd, w, one)?; - contained_store(f, g.output, w, segment[1]) - })?; - } - Ok(()) - }) -} - -/// The fixed binding numbers of the module's symbols. -fn binding_of(sym: &Symbol) -> Option { - match sym { - Symbol::DescriptorSet(_) => Some(IndexRewriteModule::SET), - Symbol::Binding(s) if *s == WORDS => Some(IndexRewriteModule::WORDS_BINDING), - Symbol::Binding(s) if *s == ARGUMENTS => Some(IndexRewriteModule::ARGUMENTS_BINDING), - Symbol::Binding(s) if *s == INDICES => Some(IndexRewriteModule::INDICES_BINDING), - Symbol::Binding(s) if *s == OUTPUT => Some(IndexRewriteModule::OUTPUT_BINDING), - Symbol::Binding(s) if *s == STATUS => Some(IndexRewriteModule::STATUS_BINDING), - _ => None, - } -} - -/// The index rewrite module of `program`'s dispatch of `phase` for `device`: built with the typed -/// builder, verified, serialized, and numbered with the fixed bindings of [`IndexRewriteModule`]. -pub fn index_rewrite_module( - device: &Device, - program: RewriteProgram, - phase: RewritePhase, -) -> Result { - let (spirv, requirements) = finished( - device, - rewrite_typed_module(program, phase)?, - binding_of, - "the index rewrite", - )?; - Ok(IndexRewriteModule { - spirv, - requirements, - }) -} - -/// The index rewrite module of a run of `program`'s draws ([`IndexRewriteRun`]) for `device`, -/// as [`index_rewrite_module`]'s phases are made: one workgroup per draw, each draw's three -/// phases in turn. -pub fn index_rewrite_run_module( - device: &Device, - program: RewriteProgram, -) -> Result { - let (spirv, requirements) = finished( - device, - rewrite_run_typed_module(program)?, - binding_of, - "the index rewrite run", - )?; - Ok(IndexRewriteModule { - spirv, - requirements, - }) -} - -mod run; -pub use run::{IndexRewriteRun, RewriteRunDraw}; - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/bind/index_rewrite/run.rs b/crates/metal2vulkan/src/bind/index_rewrite/run.rs deleted file mode 100644 index a9a4ce423..000000000 --- a/crates/metal2vulkan/src/bind/index_rewrite/run.rs +++ /dev/null @@ -1,201 +0,0 @@ -//! A run of the index rewrite pass: the lists of direct indexed draws of one program, order and -//! `k'` over one index buffer, each draw's three phases ([`RewritePhase`](super::RewritePhase)) in one workgroup of one -//! dispatch for the whole run ([`index_rewrite_run_module`](super::index_rewrite_run_module)), -//! where a draw's own pass takes three dispatches between barriers. A draw joins where its walk -//! takes one group ([`IndexRewritePass::groups`]: at most -//! [`IndexRewritePass::GROUP_POSITIONS`] positions), which every strip of a few thousand indices -//! does; its list is the one its own pass writes, index for index. -//! -//! - **The words** ([`IndexRewriteRun::words`], at [`IndexRewriteModule::WORDS_BINDING`](super::IndexRewriteModule::WORDS_BINDING)): one -//! slot of [`IndexRewriteRun::SLOT_WORDS`] words per draw, workgroup `w`'s from word -//! `w · SLOT_WORDS`, each laid out as a pass's rewrite words through its one group's words (the -//! parent module's table), and its word 26 the first word of the draw's region of the output. -//! The draw's `VkDrawIndexedIndirectCommand` lies at [`IndexRewriteRun::draw_offset`]. -//! - **The output** (at [`IndexRewriteModule::OUTPUT_BINDING`](super::IndexRewriteModule::OUTPUT_BINDING)): the run's own, each draw's region -//! of its program's capacity of its count ([`RewriteProgram::capacity`]) after the regions -//! before it; the draw draws it as the run's output's indices from its region's first. -//! - **Bindings**: the arguments as any 4 bytes (every draw is direct), the indices -//! ([`IndexRewriteRun::indices_range`]: the bytes the consumer names, so one binding serves -//! every draw of the run; any 4 bytes where it is `None`), and the status as a pass's. -//! - **Synchronization** (consumer): a pass's, for the one dispatch. - -use super::{ - IndexRewritePass, Parameter, RewriteOrder, RewriteOutput, RewriteProgram, RewriteSource, -}; -use crate::bind::index_bounds::word_range; -use crate::bind::instantiate::BufferRange; - -/// A run of direct indexed draws of the index rewrite pass (the module docs). -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct IndexRewriteRun { - program: RewriteProgram, - order: RewriteOrder, - restart: u32, - /// The bound index bytes, and their end. - indices: Option<(BufferRange, u64)>, - alignment: u64, - max_range: u32, - output_words: u32, - /// The output's words the draws' regions take. - written: u32, - /// Each draw's slot. - slots: Vec<[u32; IndexRewriteRun::SLOT_WORDS as usize]>, -} - -/// One direct indexed draw of a run: Metal's arguments, its index offset and the end of the bytes -/// its fetch reads (in the bound buffer's offsets), and whether its indices are 32-bit. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct RewriteRunDraw { - /// Metal's index count: the draw's positions. - pub count: u32, - /// Metal's instance count. - pub instances: u32, - /// Metal's base vertex. - pub base_vertex: i32, - /// Metal's base instance. - pub base_instance: u32, - /// The draw's index offset: a multiple of its index size. - pub index_offset: u64, - /// Where the draw's fetch stops reading bytes: a position from there on reads index 0. - pub index_end: u64, - /// 4-byte indices, else 2-byte ones. - pub wide: bool, -} - -impl IndexRewriteRun { - /// Words of a draw's slot: a pass's rewrite words through one group's, rounded up to 16 - /// bytes. - pub const SLOT_WORDS: u32 = 36; - /// Bytes of a draw's slot. - pub const SLOT_BYTES: u64 = 4 * Self::SLOT_WORDS as u64; - /// The most draws of a run: Vulkan's least `maxComputeWorkGroupCount[0]`. - pub const MAX_DRAWS: u32 = 65535; - - /// An empty run of draws of `program` in `order` restarting at `restart` (`k'`), whose - /// indices lie in the bytes from `index_start` to `index_end` of a buffer, bound at an offset - /// aligned to `alignment` (`minStorageBufferOffsetAlignment`) over at most `max_range` bytes - /// (`maxStorageBufferRange`), into an output of `output_words` words. `None` where the bytes - /// are past `max_range`. - pub fn new( - (program, order, restart): (RewriteProgram, RewriteOrder, u32), - (index_start, index_end): (u64, u64), - (alignment, max_range): (u64, u32), - output_words: u32, - ) -> Option { - let indices = match index_end > index_start { - true => { - let (range, _) = word_range(index_start, index_end, alignment, max_range)?; - Some((range, range.offset + range.range)) - } - false => None, - }; - Some(IndexRewriteRun { - program, - order, - restart, - indices, - alignment, - max_range, - output_words, - written: 0, - slots: Vec::new(), - }) - } - - /// Add `draw` to the run: its slot. `None` where the run cannot take it, and is as before: a - /// run of [`MAX_DRAWS`](Self::MAX_DRAWS), an index offset not a multiple of the index size, - /// indices read outside the bound bytes, a walk of more than one group, or a list past the - /// output. - pub fn push(&mut self, draw: RewriteRunDraw) -> Option { - let slot = u32::try_from(self.slots.len()).ok()?; - if slot >= Self::MAX_DRAWS { - return None; - } - let capacity = u32::try_from(self.program.capacity(u64::from(draw.count))).ok()?; - let size = if draw.wide { 4 } else { 2 }; - let pass = IndexRewritePass::new( - RewriteSource::Direct { - count: draw.count, - instances: draw.instances, - base_vertex: draw.base_vertex, - base_instance: draw.base_instance, - }, - self.restart, - (size, draw.index_offset, draw.index_end), - RewriteOutput::Owned { capacity }, - self.alignment, - self.max_range, - )? - .with_order(self.order); - if pass.groups != 1 { - return None; - } - // The draw's indices within the run's bound bytes: its byte there. - let mut parameters = pass.parameters; - if pass.indices_range.is_some() { - let inside = u64::from(parameters[Parameter::Inside as usize]); - let end = draw.index_offset.checked_add(inside.checked_mul(size)?)?; - let (range, bound_end) = self.indices?; - if draw.index_offset < range.offset || end > bound_end { - return None; - } - parameters[Parameter::IndicesByte as usize] = - u32::try_from(draw.index_offset - range.offset).ok()?; - } - let first = self.written; - let written = first.checked_add(capacity)?; - if written > self.output_words { - return None; - } - let mut words = [0; Self::SLOT_WORDS as usize]; - words[..IndexRewritePass::PARAMETER_WORDS].copy_from_slice(¶meters); - words[Parameter::OwnedFirst as usize] = first; - self.slots.push(words); - self.written = written; - Some(slot) - } - - /// The run's draws. - pub fn len(&self) -> usize { - self.slots.len() - } - - /// Whether the run has no draw. - pub fn is_empty(&self) -> bool { - self.slots.is_empty() - } - - /// The workgroups of the run's dispatch: one per draw. - pub fn workgroups(&self) -> u32 { - self.slots.len() as u32 - } - - /// The output's words the draws' regions take. - pub fn written(&self) -> u32 { - self.written - } - - /// The range of the index buffer to bind at [`IndexRewriteModule::INDICES_BINDING`](super::IndexRewriteModule::INDICES_BINDING): the - /// bytes [`new`](Self::new) names, aligned down, through a whole word; `None` where they are - /// none. - pub fn indices_range(&self) -> Option { - self.indices.map(|(range, _)| range) - } - - /// The words to upload at [`IndexRewriteModule::WORDS_BINDING`](super::IndexRewriteModule::WORDS_BINDING), each draw's slot in turn. - pub fn words(&self) -> Vec { - self.slots - .iter() - .flatten() - .flat_map(|w| w.to_le_bytes()) - .collect() - } - - /// The byte of the words at which slot `slot`'s draw's `VkDrawIndexedIndirectCommand` lies. - pub fn draw_offset(slot: u32) -> u64 { - u64::from(slot) * Self::SLOT_BYTES + IndexRewritePass::DRAW_OFFSET - } -} - -#[cfg(test)] -mod tests; diff --git a/crates/metal2vulkan/src/bind/index_rewrite/run/tests.rs b/crates/metal2vulkan/src/bind/index_rewrite/run/tests.rs deleted file mode 100644 index efe592dc7..000000000 --- a/crates/metal2vulkan/src/bind/index_rewrite/run/tests.rs +++ /dev/null @@ -1,221 +0,0 @@ -//! A run of the index rewrite pass: its module valid on every committed profile (L3, `G-val`); -//! on the CPU interpreter, one dispatch of a run gives each draw the list Metal draws -//! ([`RewriteProgram::list`] of its fetched positions in the run's order), in its own region of -//! the run's output, and its command Metal's instances and bases, for every program, either -//! index size, restarts, offsets and counts reaching past the buffer's whole indices, in either -//! workgroup order; and a run refuses what it cannot take. - -use super::super::{rewrite_run_typed_module, ARGUMENTS, INDICES, OUTPUT, STATUS, WORDS}; -use super::*; -use crate::bind::status::ExecutionStatus; -use crate::spirv::interp::{run, Buffer, Config, Order, Resources}; -use crate::spirv::testing::{assert_valid, committed_profiles}; - -/// The storage buffer offset alignment of these tests. -const ALIGNMENT: u64 = 16; -/// Bytes of 0xAB before the indices. -const PREFIX: u64 = 4; - -fn words(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|c| u32::from_le_bytes(*c)) - .collect() -} - -/// The index buffer of `indices` after [`PREFIX`] bytes of 0xAB, 4 bytes each where `wide`, -/// else 2, padded to 16 bytes with bytes no position may read. -fn buffer(indices: &[u32], wide: bool) -> (Vec, u64) { - let mut b = vec![0xAB; PREFIX as usize]; - for &i in indices { - match wide { - true => b.extend(i.to_le_bytes()), - false => b.extend((i as u16).to_le_bytes()), - } - } - let end = b.len() as u64; - b.resize(b.len().next_multiple_of(16), 0xCC); - (b, end) -} - -/// The draws of `program` in `order` restarting at `restart` over `indices`, each from its first -/// index for its count, run as one run: each draw's list (its command's indices of the run's -/// output) and command. -fn ran( - (program, order, restart): (RewriteProgram, RewriteOrder, u32), - (indices, wide): (&[u32], bool), - draws: &[(u32, u32)], -) -> Vec<(Vec, [u32; 5])> { - let size = if wide { 4 } else { 2 }; - let (bytes, end) = buffer(indices, wide); - let mut run_ = IndexRewriteRun::new( - (program, order, restart), - (0, end), - (ALIGNMENT, u32::MAX), - 1 << 16, - ) - .expect("run"); - for (i, &(first, count)) in draws.iter().enumerate() { - let i = i as u32; - let slot = run_ - .push(RewriteRunDraw { - count, - instances: 1 + i, - base_vertex: -(i as i32), - base_instance: 7 * i, - index_offset: PREFIX + u64::from(first) * size, - index_end: end, - wide, - }) - .expect("draw"); - assert_eq!(slot, i); - } - let range = run_.indices_range().expect("indices"); - let bound = bytes[range.offset as usize..(range.offset + range.range) as usize].to_vec(); - let module = rewrite_run_typed_module(program).expect("module"); - let mut after = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let buffers = [ - run_.words(), - vec![0xCC; 4], - bound.clone(), - vec![0xDD; run_.written().max(1) as usize * 4], - ExecutionStatus::initial().to_vec(), - ]; - let res = Resources { - buffers: [WORDS, ARGUMENTS, INDICES, OUTPUT, STATUS] - .into_iter() - .zip(buffers) - .map(|(slot, bytes)| Buffer { - slot: Some(slot), - address: None, - bytes, - }) - .collect(), - push: Vec::new(), - spec: Default::default(), - }; - let cfg = Config { - order, - workgroups: [run_.workgroups(), 1, 1], - ..Config::default() - }; - after.push(run(&module, &cfg, res).expect("run").buffers); - } - assert_eq!(after[0], after[1], "order independent"); - let words_after = words(&after[0][0]); - let output = words(&after[0][3]); - (0..draws.len() as u32) - .map(|slot| { - let at = (IndexRewriteRun::draw_offset(slot) / 4) as usize; - let command: [u32; 5] = words_after[at..at + 5].try_into().expect("command"); - let (first, n) = (command[2] as usize, command[0] as usize); - assert!(first + n <= output.len(), "the draw reads past the output"); - (output[first..first + n].to_vec(), command) - }) - .collect() -} - -/// Metal's list of the draw of `program` from `first` for `count` over `indices` (positions past -/// them read 0), restarting at `restart`, in `order`. -fn metal( - (program, order, restart): (RewriteProgram, RewriteOrder, u32), - indices: &[u32], - (first, count): (u32, u32), -) -> Vec { - let values: Vec = (first..first.saturating_add(count)) - .map(|p| indices.get(p as usize).copied().unwrap_or(0)) - .collect(); - program.list(&values, restart, order) -} - -#[test] -fn the_module_is_valid_on_every_committed_profile() { - for (_, p) in committed_profiles().expect("profiles") { - for program in RewriteProgram::ALL { - assert_valid(rewrite_run_typed_module(program).expect("module"), &p); - } - } -} - -/// Each draw of a run gets Metal's list in a region of its own, after the regions before it, and -/// Metal's instances and bases. -#[test] -fn each_draw_of_a_run_gets_metal_s_list() { - let orders = [ - RewriteOrder::First, - RewriteOrder::Last, - RewriteOrder::LastFirst, - ]; - for program in RewriteProgram::ALL { - for wide in [false, true] { - let restart = if wide { 0xFFFF_FFFF } else { 0xFFFF }; - // Pieces between restarts, a repeated index, and an all-ones index of the other size. - let indices: Vec = [ - 0, 1, 2, 3, restart, 4, 5, 6, 7, 8, restart, restart, 9, 10, 0xFFFF, 11, 12, 13, - 14, restart, 15, 16, 17, 18, 19, 20, 21, - ] - .into_iter() - .map(|i| if wide { i } else { i & 0xFFFF }) - .collect(); - let n = indices.len() as u32; - // Every draw from 0, one inside, one past the buffer's whole indices, an empty one, - // and one of several positions per invocation. - let draws = [(0, n), (3, 9), (1, 2), (20, 12), (5, 0), (n, 3), (2, 700)]; - for order in orders { - let terms = (program, order, restart); - let lists = ran(terms, (&indices, wide), &draws); - let mut next = 0; - for (i, (&draw, (list, command))) in draws.iter().zip(&lists).enumerate() { - let what = format!("{program:?} wide {wide} {order:?} draw {draw:?}"); - assert_eq!(*list, metal(terms, &indices, draw), "{what}"); - let i = i as u32; - assert_eq!( - command[1..], - [1 + i, next, (-(i as i32)) as u32, 7 * i], - "{what}" - ); - next += program.capacity(u64::from(draw.1)) as u32; - } - } - } - } -} - -/// A run takes no draw whose walk takes more than one group, whose indices lie outside its bound -/// bytes or at an offset not a multiple of their size, or whose list is past its output. -#[test] -fn a_run_refuses_what_it_cannot_take() { - let terms = ( - RewriteProgram::TriangleStrip, - RewriteOrder::LastFirst, - 0xFFFF, - ); - let draw = |count: u32, index_offset: u64| RewriteRunDraw { - count, - instances: 1, - base_vertex: 0, - base_instance: 0, - index_offset, - index_end: 1 << 20, - wide: false, - }; - let mut run_ = - IndexRewriteRun::new(terms, (0, 1 << 20), (ALIGNMENT, u32::MAX), 1 << 16).expect("run"); - let one_group = IndexRewritePass::GROUP_POSITIONS as u32 - 4; - assert_eq!(run_.push(draw(one_group, 0)), Some(0)); - assert_eq!(run_.push(draw(one_group + 5, 0)), None, "two groups"); - assert_eq!(run_.push(draw(3, 1)), None, "an odd offset"); - let mut small = IndexRewriteRun::new(terms, (64, 128), (ALIGNMENT, u32::MAX), 6).expect("run"); - let inside = |count, index_offset| RewriteRunDraw { - index_end: 128, - ..draw(count, index_offset) - }; - assert_eq!(small.push(inside(3, 32)), None, "before the bound bytes"); - assert_eq!(small.push(draw(64, 64)), None, "past the bound bytes"); - assert_eq!(small.push(inside(4, 64)), Some(0)); - assert_eq!(small.push(inside(3, 64)), None, "past the output"); - assert_eq!(small.written(), 6); -} diff --git a/crates/metal2vulkan/src/bind/index_rewrite/tests.rs b/crates/metal2vulkan/src/bind/index_rewrite/tests.rs deleted file mode 100644 index 045727ab7..000000000 --- a/crates/metal2vulkan/src/bind/index_rewrite/tests.rs +++ /dev/null @@ -1,1012 +0,0 @@ -//! The index rewrite pass: its modules valid on every committed profile (L3, `G-val`), and, on -//! the CPU interpreter, the list it writes is the one Metal draws: a strip's pieces between the -//! restart index, each piece's triangles in Vulkan's strip order with the parity counted from the -//! piece's start, or its segments, in order; Apple's line loop, fan, quads and quad strip as the -//! Metal probes on the M3 Max drew them ([`RewriteProgram::list`], checked against the probes' -//! lists); positions past the buffer's whole indices read 0, restart included; the draw's -//! arguments carry Metal's instances and bases; a draw without indices reads its positions as -//! its indices; a pooled draw reserves whole words from the pool's counter, and a draw its output -//! cannot hold draws nothing and sets `INDEX_POOL_OVERFLOW`; each primitive is written in the -//! pass's order, Metal's at either provoking vertex mode, or with Metal's last vertex first. - -use super::*; -use crate::bind::status::{ExecutionStatus, StatusReport}; -use crate::spirv::interp::{run, Buffer, Config, Order, Resources}; -use crate::spirv::testing::{assert_valid, committed_profiles}; - -/// The pool's index bytes in these tests. -const POOL_BYTES: u32 = 4096; -/// The storage buffer offset alignment of these tests. -const ALIGNMENT: u64 = 16; - -fn words(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|c| u32::from_le_bytes(*c)) - .collect() -} - -fn bytes(words: &[u32]) -> Vec { - words.iter().flat_map(|w| w.to_le_bytes()).collect() -} - -/// Index buffer bytes of `indices`, 4 bytes each where `wide`, else 2. -fn index_bytes(indices: &[u32], wide: bool) -> Vec { - indices - .iter() - .flat_map(|&i| { - if wide { - i.to_le_bytes().to_vec() - } else { - (i as u16).to_le_bytes().to_vec() - } - }) - .collect() -} - -/// Metal's primitives of `program` over `values` (each position's index, as the fetch reads it) -/// restarting at `restart` where the program restarts, in Metal's order at provoking vertex mode -/// 0: [`RewriteProgram::list`], which the probes' lists check below. -fn metal(program: RewriteProgram, values: &[u32], restart: u32) -> Vec { - program.list(values, restart, RewriteOrder::First) -} - -/// Each position's index: position `start + q` at its index where it lies among the buffer's -/// `indices`, else 0. -fn fetched(indices: &[u32], start: u32, count: u32) -> Vec { - (0..u64::from(count)) - .map(|q| { - let p = u64::from(start) + q; - indices.get(p as usize).copied().unwrap_or(0) - }) - .collect() -} - -/// One draw. -#[derive(Clone)] -struct Draw { - program: RewriteProgram, - wide: bool, - /// The index buffer's indices from its byte `offset`, after `offset` bytes of 0xAB. - indices: Vec, - offset: u64, - restart: u32, - /// Metal's count, instances, first index, base vertex and base instance. - arguments: [u32; 5], - /// Indirect: the arguments' offset in the indirect buffer; direct: `None`. - indirect: Option, - /// Pooled: the pool's counter before the pass; owned: `None`. - counter: Option, - /// The workgroups of the count and write dispatches, where not the pass's own. - groups: Option, - /// An indirect draw without indices, its arguments the first four (count, instances, vertex - /// start, base instance). - vertices: bool, - /// The order each primitive is written in. - order: RewriteOrder, - /// The list in the private list form (`IndexRewritePass::listed`). - listed: bool, -} - -/// What a pass left: the words, the output's indices (from the pool's index region where -/// pooled), the pool's counter, and the status report. -struct Ran { - words: Vec, - output: Vec, - counter: Option, - report: StatusReport, -} - -impl Draw { - fn strip(program: RewriteProgram, wide: bool, indices: &[u32], restart: u32) -> Draw { - Draw { - program, - wide, - indices: indices.to_vec(), - offset: 0, - restart, - arguments: [indices.len() as u32, 1, 0, 0, 0], - indirect: None, - counter: None, - groups: None, - vertices: false, - order: RewriteOrder::First, - listed: false, - } - } - - /// An indirect draw without indices of `program`: `count` vertices from `start`. - fn vertices( - program: RewriteProgram, - [count, instances, start, base_instance]: [u32; 4], - ) -> Draw { - Draw { - arguments: [count, instances, start, base_instance, 0xEEEE], - indirect: Some(8), - counter: Some(12), - vertices: true, - ..Draw::strip(program, true, &[], 0xABCD) - } - } - - fn size(&self) -> u64 { - if self.wide { - 4 - } else { - 2 - } - } - - /// The pass's run: the indices bound as its range names, the arguments, and the output. - fn run(&self) -> Ran { - let size = self.size(); - let mut buffer = vec![0xAB; self.offset as usize]; - buffer.extend(index_bytes(&self.indices, self.wide)); - let end = buffer.len() as u64; - // The `VkBuffer` runs on to a multiple of 16 bytes (the padding), of bytes no position may - // read as an index. - buffer.resize(buffer.len().next_multiple_of(16).max(16), 0xCC); - let [count, instances, _, base, base_instance] = self.arguments; - let source = match self.indirect { - None => RewriteSource::Direct { - count, - instances, - base_vertex: base as i32, - base_instance, - }, - Some(at) if self.vertices => RewriteSource::IndirectVertices { - arguments: IndirectRef::new(0, at), - }, - Some(at) => RewriteSource::Indirect { - arguments: IndirectRef::new(0, at), - }, - }; - let capacity = self.program.capacity(u64::from(count)) as u32 + u32::from(self.listed); - let output = match self.counter { - None => RewriteOutput::Owned { capacity }, - Some(_) => RewriteOutput::Pooled { - pool_bytes: POOL_BYTES, - }, - }; - let terms = match self.vertices { - true => (4, 0, 0), - false => (size, self.offset, end), - }; - let pass = IndexRewritePass::new(source, self.restart, terms, output, ALIGNMENT, u32::MAX) - .expect("pass") - .with_order(self.order); - let mut pass = match self.listed { - true => pass.listed(), - false => pass, - }; - if let Some(groups) = self.groups { - pass.groups = groups; - pass.parameters[Parameter::Groups as usize] = groups; - } - let mut rewrite = pass.parameters.to_vec(); - rewrite.resize((IndexRewritePass::BYTES / 4) as usize, 0xEEEE_EEEE); - // The indirect buffer: the arguments at their offset, bound as the pass names. - let arguments = match (self.indirect, pass.arguments_range) { - (Some(at), Some(range)) => { - let mut b = vec![0xCDu8; (at + 20) as usize]; - b[at as usize..at as usize + 20].copy_from_slice(&bytes(&self.arguments)); - b[range.offset as usize..(range.offset + range.range) as usize].to_vec() - } - (None, None) => vec![0xCC; 4], - _ => panic!("an indirect draw's range"), - }; - // Exactly the range the pass names, as Vulkan binds it: a shader reads the words that lie - // wholly inside it. - let indices = match pass.indices_range { - Some(range) => { - buffer[range.offset as usize..(range.offset + range.range) as usize].to_vec() - } - None => vec![0xCC; 4], - }; - let header = (IndexRewritePass::POOL_HEADER_BYTES / 4) as usize; - let out = match self.counter { - None => vec![0xDDDD_DDDD; capacity.max(1) as usize], - Some(counter) => { - let mut pool = vec![0xDDDD_DDDD; header + (POOL_BYTES / 4) as usize]; - pool[0] = counter; - pool - } - }; - let modules = RewritePhase::ALL.map(|phase| { - ( - phase, - rewrite_typed_module(self.program, phase).expect("module"), - ) - }); - let mut ran = Vec::new(); - for order in [Order::Forward, Order::Reverse] { - let mut buffers = vec![ - bytes(&rewrite), - arguments.clone(), - indices.clone(), - bytes(&out), - ExecutionStatus::initial().to_vec(), - ]; - // The three dispatches in order, each over the buffers the one before left. - for (phase, module) in &modules { - let slots = [WORDS, ARGUMENTS, INDICES, OUTPUT, STATUS]; - let res = Resources { - buffers: slots - .into_iter() - .zip(buffers) - .map(|(slot, bytes)| Buffer { - slot: Some(slot), - address: None, - bytes, - }) - .collect(), - push: Vec::new(), - spec: Default::default(), - }; - let cfg = Config { - order, - workgroups: [phase.workgroups(&pass), 1, 1], - ..Config::default() - }; - buffers = run(module, &cfg, res).expect("rewrite run").buffers; - } - ran.push(buffers); - } - assert_eq!(ran[0], ran[1], "order independent"); - let after = &ran[0]; - let status: [u8; ExecutionStatus::BYTES] = after[4].as_slice().try_into().expect("status"); - let out = words(&after[3]); - let (output, counter) = match self.counter { - None => (out, None), - Some(_) => (out[header..].to_vec(), Some(out[0])), - }; - Ran { - words: words(&after[0]), - output, - counter, - report: ExecutionStatus::decode(&status), - } - } - - /// The indices the draw draws: its command's from the output, every one inside it. - fn drawn(&self) -> (Vec, [u32; 5], Ran) { - let r = self.run(); - let at = (IndexRewritePass::DRAW_OFFSET / 4) as usize; - let command: [u32; 5] = r.words[at..at + 5].try_into().expect("command"); - let first = command[2] as usize; - let n = command[0] as usize; - assert!( - first + n <= r.output.len(), - "the draw reads past its output" - ); - let list = r.output[first..first + n].to_vec(); - (list, command, r) - } -} - -#[test] -fn every_program_is_valid_on_every_committed_profile() { - for (_, p) in committed_profiles().expect("profiles") { - for program in RewriteProgram::ALL { - for phase in RewritePhase::ALL { - assert_valid(rewrite_typed_module(program, phase).expect("module"), &p); - } - } - } -} - -/// The pass binds the arguments and the whole indices from aligned offsets, and states the -/// residuals, the whole indices, the index size, `k'` and the output. -#[test] -fn the_pass_binds_aligned_ranges_and_states_its_parameters() { - let pass = IndexRewritePass::new( - RewriteSource::Indirect { - arguments: IndirectRef::new(0, 68), - }, - 3, - (4, 8, 30), - RewriteOutput::Pooled { pool_bytes: 64 }, - 64, - 1 << 27, - ) - .expect("pass"); - assert_eq!( - pass.arguments_range, - Some(BufferRange { - offset: 64, - range: 24 - }) - ); - assert_eq!( - pass.indices_range, - Some(BufferRange { - offset: 0, - range: 28 - }) - ); - assert_eq!(pass.parameters[..8], [2, 8, 5, 1, 3, 64, 1, 1]); - // The indices' range ends at a whole word: nine 16-bit indices end at byte 18, and ten from - // byte 2 at byte 22. - let indices_range = |offset, end| { - IndexRewritePass::new( - RewriteSource::Indirect { - arguments: IndirectRef::new(0, 0), - }, - 3, - (2, offset, end), - RewriteOutput::Pooled { pool_bytes: 64 }, - 64, - 1 << 27, - ) - .expect("pass") - .indices_range - }; - for (offset, end, range) in [(0, 18, 20), (2, 22, 24), (2, 20, 20), (66, 82, 20)] { - assert_eq!( - indices_range(offset, end), - Some(BufferRange { - offset: offset - offset % 64, - range - }), - "from {offset} to {end}" - ); - } - assert_eq!(pass.groups, 1); - assert_eq!(pass.parameters[8..], [0; 8]); - let direct = IndexRewritePass::new( - RewriteSource::Direct { - count: 7, - instances: 2, - base_vertex: -1, - base_instance: 5, - }, - 0xFFFF, - (2, 30, 30), - RewriteOutput::Owned { capacity: 15 }, - 64, - 1 << 27, - ) - .expect("direct"); - assert_eq!(direct.arguments_range, None); - assert_eq!(direct.indices_range, None); - assert_eq!(direct.parameters[..8], [0, 0, 0, 0, 0xFFFF, 15, 0, 1]); - assert_eq!(direct.parameters[8..13], [7, 2, 0, u32::MAX, 5]); - let refused = |source, size, offset, output| { - IndexRewritePass::new(source, 0, (size, offset, 64), output, 64, 1 << 27).is_none() - }; - let owned = RewriteOutput::Owned { capacity: 1 }; - let at = |offset| RewriteSource::Indirect { - arguments: IndirectRef::new(0, offset), - }; - assert!(refused(at(2), 4, 0, owned), "arguments' offset"); - assert!(refused(at(0), 3, 0, owned), "index size"); - assert!(refused(at(0), 4, 2, owned), "index offset"); - assert!(refused( - at(0), - 4, - 0, - RewriteOutput::Pooled { pool_bytes: 6 } - )); -} - -/// Probe 5's strips, drawn directly: each restarts at `k'` alone, the all-ones index drawn as a -/// vertex where it is not `k'`; 16- and 32-bit alike. -#[test] -fn a_strip_restarts_at_its_index_alone() { - for program in RewriteProgram::ALL { - for (wide, indices, restart) in [ - (false, vec![1, 2, 3, 0, 4, 5, 6, 0xFFFF, 7, 8, 9], 0), - (false, vec![0, 1, 2, 3, 4, 5, 6, 0xFFFF, 7, 8, 9], 3), - (false, vec![1, 2, 3, 0, 4, 5, 6, 0xFFFF, 7, 8, 9], 0xFFFF), - ( - true, - vec![1, 2, 3, 0, 4, 5, 6, u32::MAX, 7, 8, 0xFFFF, 9, 10], - 0, - ), - ( - true, - vec![0, 1, 2, 3, 4, 5, 6, u32::MAX, 7, 8, 0xFFFF, 9, 10], - 0xFFFF, - ), - (true, vec![3, 3, 0, 1, 3, 2, 4, 5, 3], 3), - (true, vec![3, 3, 3], 3), - (true, vec![1, 2], 3), - (true, vec![], 3), - ] { - let draw = Draw::strip(program, wide, &indices, restart); - let (list, command, r) = draw.drawn(); - let expected = metal(program, &indices, restart); - assert_eq!( - list, expected, - "{program:?} {wide} {indices:?} k' {restart}" - ); - assert_eq!(command[1..], [1, 0, 0, 0], "{indices:?}"); - assert_eq!( - r.words[Output::Primitives as usize] as usize, - expected.len() / program.vertices() as usize - ); - assert!(!r.report.index_pool_overflow); - } - } -} - -/// A strip longer than a workgroup's invocations, over one workgroup and over several: its runs' -/// pieces cross between runs and between groups, and each run's first triangles take their -/// piece's parity from the runs before, its group's and the groups' before it. The other programs -/// draw the same indices over three groups: the fan's first index, and the loop's closing -/// segment, reach across them. -#[test] -fn a_strip_of_many_runs_keeps_each_piece_s_parity() { - // A deterministic mix: restarts at 0 here and there, long pieces and short ones. - let mut state = 0x1234_5678u32; - let mut next = || { - state ^= state << 13; - state ^= state >> 17; - state ^= state << 5; - state - }; - for (len, rate) in [(600, 7), (1000, 97), (777, 3), (1300, 1000)] { - let indices: Vec = (0..len) - .map(|_| { - let r = next(); - if r % rate == 0 { - 0 - } else { - 1 + r % 50 - } - }) - .collect(); - for program in RewriteProgram::ALL { - // The strips each way; the other programs (the quad strip has a test of its own) - // over three groups. - let strip = matches!( - program, - RewriteProgram::LineStrip | RewriteProgram::TriangleStrip - ); - let ways: &[(bool, Option)] = match strip { - true => &[ - (false, None), - (true, None), - (false, Some(3)), - (true, Some(2)), - ], - false => &[(false, Some(3))], - }; - for &(wide, groups) in ways { - let draw = Draw { - groups, - ..Draw::strip(program, wide, &indices, 0) - }; - let (list, _, _) = draw.drawn(); - assert_eq!( - list, - metal(program, &indices, 0), - "{program:?} {wide} {len} {rate} {groups:?}" - ); - } - } - } -} - -/// The count and write dispatches take a workgroup per 4096 positions the walk may take, from 1 -/// to 256: a direct draw's count bounds the walk, an indirect draw's by the buffer's whole -/// indices and the most positions a step spans past them, and an indirect draw without indices -/// takes all 256. -#[test] -fn the_groups_follow_the_walk() { - let groups = |source, inside: u64| { - let output = RewriteOutput::Pooled { pool_bytes: 64 }; - IndexRewritePass::new(source, 0, (4, 0, inside * 4), output, 64, u32::MAX) - .expect("pass") - .groups - }; - let direct = |count| RewriteSource::Direct { - count, - instances: 1, - base_vertex: 0, - base_instance: 0, - }; - let indirect = RewriteSource::Indirect { - arguments: IndirectRef::new(0, 0), - }; - assert_eq!(groups(direct(10), 10), 1); - assert_eq!(groups(direct(4096), 1 << 20), 1); - assert_eq!(groups(direct(4097), 1 << 20), 2); - assert_eq!(groups(direct(1_000_000), 1_000_000), 245); - assert_eq!(groups(direct(1_000_000), 0), 1); - assert_eq!(groups(direct(u32::MAX), 1 << 29), 256); - assert_eq!(groups(indirect, 4092), 1); - assert_eq!(groups(indirect, 4093), 2); - assert_eq!(groups(indirect, 2_000_000), 256); - let vertices = RewriteSource::IndirectVertices { - arguments: IndirectRef::new(0, 0), - }; - assert_eq!(groups(vertices, 0), 256); -} - -/// An indirect draw reads Metal's arguments (its first index, instances and bases), reserves -/// whole words from the pool's counter, and draws from there; a draw the pool cannot hold draws -/// nothing and sets the overflow bit. -#[test] -fn an_indirect_draw_reserves_its_list_in_the_pool() { - let indices: Vec = vec![9, 9, 1, 2, 3, 0, 4, 5, 6, 7, 0, 8]; - for program in RewriteProgram::ALL { - let draw = Draw { - arguments: [8, 3, 2, 0xFFFF_FFFE, 4], - indirect: Some(36), - counter: Some(40), - ..Draw::strip(program, false, &indices, 0) - }; - let (list, command, r) = draw.drawn(); - let expected = metal(program, &fetched(&indices, 2, 8), 0); - assert_eq!(list, expected, "{program:?}"); - assert_eq!(command[1..], [3, 10, 0xFFFF_FFFE, 4], "{program:?}"); - assert_eq!(r.counter, Some(40 + 4 * expected.len() as u32)); - assert!(!r.report.index_pool_overflow); - // No room: nothing drawn, the counter kept, the bit set. - let full = Draw { - counter: Some(POOL_BYTES - 4), - ..draw.clone() - }; - let (list, command, r) = full.drawn(); - assert!(list.is_empty()); - assert_eq!(command[0], 0); - assert_eq!(r.counter, Some(POOL_BYTES - 4)); - assert!(r.report.index_pool_overflow); - } -} - -/// Positions past the buffer's whole indices read 0: they restart where `k'` is 0, and are -/// vertex 0 otherwise, the primitives past the walk written without one; an index offset inside -/// a word, and a partial last index, read as Metal's fetch does. -#[test] -fn positions_past_the_buffer_read_index_0() { - let indices = vec![5, 6, 7, 8, 9]; - for program in RewriteProgram::ALL { - for (restart, count) in [(0, 9), (3, 9), (3, 40), (0, 40), (3, 2)] { - for wide in [false, true] { - let draw = Draw { - arguments: [count, 1, 0, 0, 0], - offset: if wide { 4 } else { 6 }, - ..Draw::strip(program, wide, &indices, restart) - }; - let (list, _, _) = draw.drawn(); - let expected = metal(program, &fetched(&indices, 0, count), restart); - assert_eq!(list, expected, "{program:?} {wide} k' {restart} {count}"); - } - } - // An indirect draw from past the buffer reads 0 throughout. - let draw = Draw { - arguments: [6, 1, 9, 0, 0], - indirect: Some(0), - counter: Some(0), - ..Draw::strip(program, true, &indices, 4) - }; - let (list, _, _) = draw.drawn(); - assert_eq!( - list, - metal(program, &[0; 6], 4), - "{program:?} from past the buffer" - ); - } -} - -/// The last whole index of a word the buffer's indices end inside is read, not 0: an odd count -/// of 16-bit indices from a multiple of 4 bytes, or an even count from 2 past one, direct and -/// indirect (the consumer's nine 16-bit indices restarting at 3, from an 18- or a 20-byte buffer, -/// drew their last triangle to vertex 0 on an M3 Max where ten were exact). -#[test] -fn the_last_index_of_a_partial_word_is_read() { - let nine: Vec = vec![0, 1, 2, 3, 4, 5, 6, 7, 8]; - let ten: Vec = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - let seven: Vec = vec![1, 2, 3, 4, 5, 6, 7]; - for program in RewriteProgram::ALL { - for (indices, offset) in [ - (&nine, 0), - (&nine, 2), - (&ten, 2), - (&ten, 0), - (&seven, 4), - (&seven, 6), - ] { - let count = indices.len() as u32; - let direct = Draw { - offset, - ..Draw::strip(program, false, indices, 3) - }; - let indirect = Draw { - arguments: [count, 1, 0, 0, 0], - indirect: Some(4), - counter: Some(0), - ..direct.clone() - }; - for (draw, how) in [(direct, "direct"), (indirect, "indirect")] { - let (list, _, _) = draw.drawn(); - assert_eq!( - list, - metal(program, indices, 3), - "{program:?} {how}: {count} from byte {offset}" - ); - } - } - } -} - -/// The lists of Apple's private types are those the Metal probes drew on the M3 Max (macOS -/// 27.0.1, `primtypes` probe: each primitive's vertices in barycentric order, its flat vertex the -/// first at provoking vertex mode 0 and the last at mode 1), and a draw without indices draws the -/// list of its positions. -#[test] -fn the_private_lists_are_the_probes() { - use RewriteProgram::{LineLoop, QuadStrip, Quads, TriangleFan}; - let drawn: &[(RewriteProgram, u32, &[u32])] = &[ - (LineLoop, 0, &[]), - (LineLoop, 1, &[]), - (LineLoop, 2, &[0, 1, 1, 0]), - (LineLoop, 5, &[0, 1, 1, 2, 2, 3, 3, 4, 4, 0]), - (TriangleFan, 2, &[]), - (TriangleFan, 3, &[0, 1, 2]), - (TriangleFan, 6, &[0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5]), - (Quads, 3, &[]), - (Quads, 4, &[0, 1, 3, 1, 2, 3]), - (Quads, 7, &[0, 1, 3, 1, 2, 3]), - (Quads, 9, &[0, 1, 3, 1, 2, 3, 4, 5, 7, 5, 6, 7]), - (QuadStrip, 3, &[]), - (QuadStrip, 4, &[0, 1, 3, 2, 0, 3]), - (QuadStrip, 5, &[0, 1, 3, 2, 0, 3]), - ( - QuadStrip, - 8, - &[0, 1, 3, 2, 0, 3, 2, 3, 5, 4, 2, 5, 4, 5, 7, 6, 4, 7], - ), - ]; - for &(program, count, list) in drawn { - let positions: Vec = (0..count).collect(); - assert_eq!( - program.list(&positions, u32::MAX, RewriteOrder::First), - list, - "{program:?} {count}" - ); - assert_eq!( - program.sequential_list(count, RewriteOrder::First), - list, - "{program:?} {count}" - ); - assert!(list.len() as u64 <= program.capacity(u64::from(count))); - } - // Every count from 0 to 40: the CPU's list of positions is the general one's. - for program in RewriteProgram::ALL { - for count in 0..40 { - let positions: Vec = (0..count).collect(); - let list = program.sequential_list(count, RewriteOrder::First); - assert_eq!( - list, - program.list(&positions, u32::MAX, RewriteOrder::First), - "{program:?} {count}" - ); - assert_eq!(list.len() as u64, program.capacity(u64::from(count))); - } - } - // The probes' 16-bit draws of `40 + 2i` with the all-ones index at position 5: the line - // loop, fan and quads draw it as a vertex; the quad strip restarts there, its second piece - // pairing from its own start. - let mut values: Vec = (0..12).map(|i| 40 + 2 * i).collect(); - values[5] = 0xFFFF; - assert_eq!( - Quads.list(&values, 0xFFFF, RewriteOrder::First), - [40, 42, 46, 42, 44, 46, 48, 0xFFFF, 54, 0xFFFF, 52, 54, 56, 58, 62, 58, 60, 62] - ); - assert_eq!( - QuadStrip.list(&values, 0xFFFF, RewriteOrder::First), - [40, 42, 46, 44, 40, 46, 52, 54, 58, 56, 52, 58, 56, 58, 62, 60, 56, 62] - ); - assert_eq!( - TriangleFan.list(&values, 0xFFFF, RewriteOrder::First)[9..12], - [40, 48, 0xFFFF] - ); - assert_eq!( - LineLoop.list(&values, 0xFFFF, RewriteOrder::First).len(), - 24 - ); -} - -/// An indirect draw without indices writes the list of its positions from 0, whatever its count, -/// into the pool, and draws it from its vertex start as base vertex with Metal's instances and -/// base instance; none of its positions restarts. Its pass takes every group, as the GPU alone -/// knows its count (`IndexRewritePass::groups`, which the groups test checks); here one group or -/// three, the interpreter being slow. -#[test] -fn a_draw_without_indices_lists_its_positions() { - let mut draws = Vec::new(); - for program in RewriteProgram::ALL { - for (count, groups) in [ - (0, 1), - (1, 1), - (2, 3), - (3, 1), - (4, 3), - (5, 1), - (9, 3), - (130, 3), - ] { - draws.push((program, count, Some(groups))); - } - } - for (program, count, groups) in draws { - let draw = Draw { - groups, - ..Draw::vertices(program, [count, 2, 0xFFFF, 7]) - }; - let (list, command, r) = draw.drawn(); - let expected = program.sequential_list(count, RewriteOrder::First); - assert_eq!(list, expected, "{program:?} {count}"); - assert_eq!(command[1..], [2, 3, 0xFFFF, 7], "{program:?} {count}"); - assert_eq!(r.counter, Some(12 + 4 * expected.len() as u32)); - assert!(!r.report.index_pool_overflow); - } -} - -/// A quad strip of many runs over several groups, restarting here and there: each piece pairs -/// from its own start, whichever run or group it began in, so a run's first quads take the -/// parity of its piece's positions before it. -#[test] -fn a_quad_strip_pairs_from_each_piece_s_start() { - let mut state = 0x9E37_79B9u32; - let mut next = || { - state ^= state << 13; - state ^= state >> 17; - state ^= state << 5; - state - }; - for (len, rate) in [(700, 5), (1500, 61), (999, 2), (2048, 333)] { - let indices: Vec = (0..len) - .map(|_| { - let r = next(); - if r % rate == 0 { - 7 - } else { - 8 + r % 40 - } - }) - .collect(); - for (groups, wide) in [ - (None, false), - (Some(1), true), - (Some(3), false), - (Some(5), true), - ] { - let draw = Draw { - groups, - ..Draw::strip(RewriteProgram::QuadStrip, wide, &indices, 7) - }; - let (list, _, _) = draw.drawn(); - assert_eq!( - list, - metal(RewriteProgram::QuadStrip, &indices, 7), - "{len} {rate} {groups:?} {wide}" - ); - } - } -} - -/// The orders of a primitive: Metal's at mode 0, at mode 1 (a triangle strip's odd triangle -/// `(i + 1, i, i + 2)`, its even one and every other primitive as at mode 0), and Metal's at mode -/// 1 with the last vertex first, so a first-vertex pipeline reads each primitive's flat inputs -/// from the vertex Metal's mode 1 reads them from (Metal probes on the M3 Max, macOS 27.0.1: line -/// list `2j + 1`, line strip `j + 1`, triangle list `3j + 2`, strip `j + 2`, line loop the -/// segment's second, fan `j + 2`, quads and quad strip `d`), each triangle keeping its winding. -#[test] -fn the_orders_are_metal_s_at_either_mode() { - use RewriteOrder::{First, Last, LastFirst}; - use RewriteProgram::{LineList, LineStrip, TriangleList, TriangleStrip}; - assert_eq!( - TriangleStrip.sequential_list(5, First), - [0, 1, 2, 1, 3, 2, 2, 3, 4] - ); - assert_eq!( - TriangleStrip.sequential_list(5, Last), - [0, 1, 2, 2, 1, 3, 2, 3, 4] - ); - assert_eq!( - TriangleStrip.sequential_list(5, LastFirst), - [2, 0, 1, 3, 2, 1, 4, 2, 3] - ); - assert_eq!(LineStrip.sequential_list(3, LastFirst), [1, 0, 2, 1]); - assert_eq!(LineList.sequential_list(5, First), [0, 1, 2, 3]); - assert_eq!(LineList.sequential_list(5, LastFirst), [1, 0, 3, 2]); - assert_eq!(TriangleList.sequential_list(7, First), [0, 1, 2, 3, 4, 5]); - assert_eq!( - TriangleList.sequential_list(7, LastFirst), - [2, 0, 1, 5, 3, 4] - ); - // Metal's mode-1 flat vertex of each list primitive, by program, of the positions `0..n`. - let flat = |program: RewriteProgram, n: u32| -> Vec { - let list = program.sequential_list(n, Last); - let v = program.vertices() as usize; - list.chunks(v).map(|p| p[v - 1]).collect() - }; - assert_eq!(flat(LineList, 6), [1, 3, 5]); - assert_eq!(flat(LineStrip, 4), [1, 2, 3]); - assert_eq!(flat(TriangleList, 6), [2, 5]); - assert_eq!(flat(TriangleStrip, 6), [2, 3, 4, 5]); - assert_eq!(flat(RewriteProgram::LineLoop, 4), [1, 2, 3, 0]); - assert_eq!(flat(RewriteProgram::TriangleFan, 5), [2, 3, 4]); - assert_eq!(flat(RewriteProgram::Quads, 4), [3, 3]); - assert_eq!(flat(RewriteProgram::QuadStrip, 6), [3, 3, 5, 5]); - // The winding: a signed area of positions on a convex curve, so each position's point is - // distinct and no three are collinear. - let point = |i: u32| { - let t = f64::from(i) * 0.37; - (t.cos() * (1.0 + 0.1 * t), t.sin() * (1.0 + 0.1 * t)) - }; - let area = |t: &[u32]| { - let (a, b, c) = (point(t[0]), point(t[1]), point(t[2])); - (b.0 - a.0) * (c.1 - a.1) - (c.0 - a.0) * (b.1 - a.1) - }; - for program in RewriteProgram::ALL { - for n in 0..24 { - let first = program.sequential_list(n, First); - let last = program.sequential_list(n, Last); - let led = program.sequential_list(n, LastFirst); - let v = program.vertices() as usize; - assert_eq!(first.len(), last.len(), "{program:?} {n}"); - assert_eq!(first.len(), led.len(), "{program:?} {n}"); - for ((f, l), r) in first.chunks(v).zip(last.chunks(v)).zip(led.chunks(v)) { - // The last-first order leads with Metal's mode-1 flat vertex, then the rest in - // their order. - assert_eq!(r[0], l[v - 1], "{program:?} {n}"); - assert_eq!(r[1..], l[..v - 1], "{program:?} {n}"); - if v == 3 { - assert!(area(f) * area(l) > 0.0, "{program:?} {n} {f:?} {l:?}"); - assert!(area(f) * area(r) > 0.0, "{program:?} {n} {f:?} {r:?}"); - } else if program != TriangleStrip { - assert_eq!(f, l, "{program:?} {n}"); - } - } - if program != TriangleStrip { - assert_eq!(first, last, "{program:?} {n}"); - } - } - } -} - -/// The pass writes each order as the CPU's list does, for every program: restarting draws, -/// a fan's first index and a loop's closing segment over groups, the primitives past the walk, -/// and an indirect draw without indices. -#[test] -fn the_pass_writes_each_order() { - let mut state = 0x0BAD_5EEDu32; - let mut next = || { - state ^= state << 13; - state ^= state >> 17; - state ^= state << 5; - state - }; - let long: Vec = (0..700) - .map(|_| { - let r = next(); - if r % 9 == 0 { - 0 - } else { - 1 + r % 50 - } - }) - .collect(); - let short = vec![1, 2, 3, 0, 4, 5, 6, 0xFFFF, 7, 8, 9]; - for order in [RewriteOrder::Last, RewriteOrder::LastFirst] { - for program in RewriteProgram::ALL { - let draws = [ - Draw::strip(program, false, &short, 0), - Draw { - groups: Some(3), - ..Draw::strip(program, true, &long, 0) - }, - // Nine positions past five indices: the primitives past the walk. - Draw { - arguments: [40, 1, 0, 0, 0], - ..Draw::strip(program, true, &[5, 6, 7, 8, 9], 3) - }, - ]; - for draw in draws { - let draw = Draw { order, ..draw }; - let (list, _, _) = draw.drawn(); - let count = draw.arguments[0]; - let values = fetched(&draw.indices, 0, count); - assert_eq!( - list, - program.list(&values, draw.restart, order), - "{program:?} {order:?} {count}" - ); - } - let draw = Draw { - groups: Some(3), - order, - ..Draw::vertices(program, [130, 1, 4, 0]) - }; - let (list, _, _) = draw.drawn(); - assert_eq!( - list, - program.sequential_list(130, order), - "{program:?} {order:?} without indices" - ); - } - } -} - -/// In the private list form the pass writes the same list one word on, Metal's base vertex (a -/// direct or indexed indirect draw's base vertex, an indirect draw's vertex start) in the word -/// before it, and the draw as a `VkDrawIndirectCommand` of the list from its first index as -/// first vertex, with Metal's instances and base instance; the reservation takes the word too, -/// and a list the room holds but for the word draws nothing and says so. -#[test] -fn the_private_list_form_writes_the_base_vertex_before_its_list() { - let indices: Vec = vec![9, 9, 1, 2, 3, 0, 4, 5, 6, 7, 0, 8]; - for program in RewriteProgram::ALL { - let direct = Draw { - arguments: [9, 2, 0, 0x8000_0005, 3], - ..Draw::strip(program, true, &indices, 0) - }; - let indirect = Draw { - arguments: [8, 3, 2, 0xFFFF_FFFE, 4], - indirect: Some(36), - counter: Some(40), - ..Draw::strip(program, false, &indices, 0) - }; - let vertices = Draw { - groups: Some(1), - ..Draw::vertices(program, [7, 2, 0x8000_0010, 5]) - }; - for (draw, base, instances, base_instance) in [ - (direct, 0x8000_0005, 2, 3), - (indirect, 0xFFFF_FFFE, 3, 4), - (vertices, 0x8000_0010, 2, 5), - ] { - let (plain, _, _) = draw.drawn(); - let listed = Draw { - listed: true, - ..draw.clone() - }; - let (list, command, r) = listed.drawn(); - assert_eq!(list, plain, "{program:?}"); - let first = command[2] as usize; - let start = match draw.counter { - Some(counter) => (counter / 4) as usize + 1, - None => 1, - }; - assert_eq!(first, start, "{program:?}: the list's first index"); - assert_eq!(r.output[first - 1], base, "{program:?}: the base vertex"); - assert_eq!( - command, - [ - plain.len() as u32, - instances, - first as u32, - base_instance, - 0 - ], - "{program:?}" - ); - if let (Some(before), Some(after)) = (draw.counter, r.counter) { - assert_eq!(after, before + 4 * (plain.len() as u32 + 1), "{program:?}"); - } - assert!(!r.report.index_pool_overflow); - } - // Room for the list but not its base vertex's word: nothing drawn, the bit set. - let needed = metal(program, &fetched(&indices, 2, 8), 0).len() as u32; - let tight = Draw { - arguments: [8, 3, 2, 7, 4], - indirect: Some(36), - counter: Some(POOL_BYTES - 4 * needed), - listed: true, - ..Draw::strip(program, false, &indices, 0) - }; - let (list, command, r) = tight.drawn(); - if needed > 0 { - assert!(list.is_empty(), "{program:?}"); - assert_eq!(command[0], 0, "{program:?}"); - assert!(r.report.index_pool_overflow, "{program:?}"); - } - } -} diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index 3849c5fce..28c26d6c1 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -35,19 +35,7 @@ //! [`StatusReport`] names. A command reaches it by its device address where the device addresses buffers, and //! through the binding [`WriteSource::ExecutionStatus`] names where it does not. An indirect //! dispatch reads its group counts from Metal's buffer itself ([`IndirectArgs::Buffer`]). -//! An indexed indirect draw whose index fetch -//! nothing bounds (`DrawCommands::index_bounds_pass`) can bound it on the GPU instead of reading -//! its arguments: an [`IndexBoundsPass`] of [`index_bounds_plan_module`] and -//! [`index_bounds_fill_module`] before the render pass instance, and two indirect draws (a run of -//! such draws over one arguments buffer and one index buffer, one [`IndexBoundsRun`] plan of -//! [`index_bounds_plan_run_module`] and one fill of [`index_bounds_fill_run_module`] for all of -//! them instead). An -//! indexed draw whose primitives Vulkan's input assembly does not form as Metal does (a strip -//! restarting at another index than all-ones) can draw them as a list instead: an -//! [`IndexRewritePass`] of three [`index_rewrite_module`] dispatches ([`RewritePhase`]) before the -//! render pass instance, and one indirect draw (a run of direct draws of one walk group each, -//! over one index buffer, one [`IndexRewriteRun`] dispatch of [`index_rewrite_run_module`] for -//! all of them instead). A pass's visibility results are its queries' results copied to their +//! A pass's visibility results are its queries' results copied to their //! offsets, a `Boolean` one the device's own nonzero value where a sample passed. A pass whose //! fetching draws //! read a multisampled attachment's sample planes (`StorageAttachmentView::SamplePlanes`) splits @@ -100,8 +88,6 @@ pub(crate) mod etc_decode; pub mod fan_out; pub(crate) mod graphics; pub(crate) mod heap; -pub(crate) mod index_bounds; -pub(crate) mod index_rewrite; pub mod indirect_commands; pub(crate) mod instantiate; pub(crate) mod mesh_arguments; @@ -145,16 +131,6 @@ pub use heap::{ handle_entry, handle_entry_flags, heap_classes, heap_element, heap_raw_form, HeapElement, HeapElements, HeapSource, HANDLE_ENTRY_BYTES, HANDLE_TABLE_CAPACITY, NEUTRAL_HEAP_ELEMENT, }; -pub use index_bounds::{ - index_bounds_fill_module, index_bounds_fill_run_module, index_bounds_plan_module, - index_bounds_plan_run_module, BoundsRunDraw, IndexBoundsFillModule, IndexBoundsPass, - IndexBoundsPlanModule, IndexBoundsRun, -}; -pub use index_rewrite::{ - index_rewrite_module, index_rewrite_run_module, IndexRewriteModule, IndexRewritePass, - IndexRewriteRun, RewriteOrder, RewriteOutput, RewritePhase, RewriteProgram, RewriteRunDraw, - RewriteSource, -}; pub use instantiate::{ BufferExtent, BufferRange, DescriptorBytes, DescriptorRange, IndexBufferRef, IndirectRef, PushConstantWrite, PushHole, ResidentRange, ResidentSet, RootTable, diff --git a/crates/metal2vulkan/src/bind/replay/rules.rs b/crates/metal2vulkan/src/bind/replay/rules.rs index d22f357f8..cc1876e34 100644 --- a/crates/metal2vulkan/src/bind/replay/rules.rs +++ b/crates/metal2vulkan/src/bind/replay/rules.rs @@ -54,8 +54,6 @@ pub enum DrawReplayRule { InputAttachments, /// The state's indirect draw needs its arguments on the CPU. ArgumentsOnCpu, - /// The state's draw bounds its indices. - IndexBounds, /// The state's draw is amplified or draws views. Amplified, /// The state's vertex function fetches attributes of a layout whose stride is set per bind @@ -115,7 +113,6 @@ impl fmt::Display for DrawReplayRule { DrawReplayRule::ArgumentsOnCpu => { "the inherited state's indirect draw needs its arguments on the CPU" } - DrawReplayRule::IndexBounds => "the inherited state's draw bounds its indices", DrawReplayRule::Amplified => "the inherited state's draw is amplified or draws views", DrawReplayRule::VertexAttributes => { "the inherited state's vertex function fetches attributes at a stride set per bind" @@ -280,7 +277,6 @@ pub fn draw_replay_draw( commands.indirect_needs_arguments, DrawReplayRule::ArgumentsOnCpu, ), - (commands.index_bounds_pass, DrawReplayRule::IndexBounds), ( !commands.amplifications.is_empty() || plan.views != ViewSetup::default(), DrawReplayRule::Amplified, diff --git a/crates/metal2vulkan/src/bind/state.rs b/crates/metal2vulkan/src/bind/state.rs index 34c446dee..50c6d61a3 100644 --- a/crates/metal2vulkan/src/bind/state.rs +++ b/crates/metal2vulkan/src/bind/state.rs @@ -113,9 +113,9 @@ pub struct BindState { #[cfg_attr(feature = "serde", serde(default))] pub primitive_id_indices: Option, /// The draw is of Metal's private quads or quad strip, which the consumer lists as two - /// triangles a quad, each quad's adjacent (`bind::RewriteProgram::Quads`, `QuadStrip`): a - /// pipeline whose fragment function reads Vulkan's `PrimitiveId` runs the variant that reads - /// the quad's, that value shifted right by one, as Metal counts one primitive a quad + /// triangles a quad, each quad's adjacent: a pipeline whose fragment function reads Vulkan's + /// `PrimitiveId` runs the variant that reads the quad's, that value shifted right by one, as + /// Metal counts one primitive a quad /// (`VariantKey::quad_primitive_ids`). Part of the shape (`BindShape::quad_primitive_ids`); /// `false` for every other draw. #[cfg_attr(feature = "serde", serde(default))] diff --git a/crates/metal2vulkan/src/bind/status.rs b/crates/metal2vulkan/src/bind/status.rs index 02b8038a9..328510b95 100644 --- a/crates/metal2vulkan/src/bind/status.rs +++ b/crates/metal2vulkan/src/bind/status.rs @@ -24,7 +24,7 @@ impl ExecutionStatus { } /// What the buffer's bytes report after the command buffer ran. The consumer maps a replay - /// fault, an index pool overflow, an absent argument read, a mesh grid Metal's GPU + /// fault, an absent argument read, a mesh grid Metal's GPU /// discards or the device cannot launch, and a cubic argument sampler's sample /// to a command-buffer execution error, and treats resident-set misses by its own policy. pub fn decode(bytes: &[u8; ExecutionStatus::BYTES]) -> StatusReport { @@ -38,7 +38,6 @@ impl ExecutionStatus { resident_misses: word(StatusWord::ResidentMisses), replay_fault: bits.contains(StatusBits::REPLAY_FAULT), replay_faults: ReplayFaults(word(StatusWord::ReplayFaults)), - index_pool_overflow: bits.contains(StatusBits::INDEX_POOL_OVERFLOW), absent_argument_read: bits.contains(StatusBits::ABSENT_ARGUMENT_READ), cubic_argument_sampler: bits.contains(StatusBits::CUBIC_ARGUMENT_SAMPLER), mesh_grid_discarded: bits.contains(StatusBits::MESH_GRID_DISCARDED), @@ -61,9 +60,6 @@ pub struct StatusReport { pub replay_fault: bool, /// Why the device replay's preprocess refused commands: the union of their reasons. pub replay_faults: ReplayFaults, - /// An index bounds pass found no room in its command buffer's index pool for a draw's - /// indices: that draw drew nothing. - pub index_pool_overflow: bool, /// A function read an argument its pipeline's function constants removed, which Metal gives /// no value (`RuntimeFact::AbsentArgumentRead`): the read yielded zero, so no result of the /// command buffer is Metal's. @@ -131,26 +127,23 @@ impl StatusBits { pub const RESIDENT_MISS: StatusBits = StatusBits(1 << 0); /// The device replay's preprocess refused a command; [`StatusWord::ReplayFaults`] holds why. pub const REPLAY_FAULT: StatusBits = StatusBits(1 << 1); - /// An index bounds pass found no room in the command buffer's index pool for a draw's - /// indices, and the draw drew nothing (`bind::IndexBoundsPass`). - pub const INDEX_POOL_OVERFLOW: StatusBits = StatusBits(1 << 2); /// A function read an argument its pipeline's function constants removed, a read Metal /// gives no value, and took zero for it (`RuntimeFact::AbsentArgumentRead`). - pub const ABSENT_ARGUMENT_READ: StatusBits = StatusBits(1 << 3); + pub const ABSENT_ARGUMENT_READ: StatusBits = StatusBits(1 << 2); /// A function sampled, gathered, or queried through a sampler an argument buffer holds whose /// min or mag filter is `Cubic`, whose bicubic filter it does not emulate there /// (`RuntimeFact::CubicArgumentSampler`): its result is the device's through a nearest /// placeholder, not Metal's. - pub const CUBIC_ARGUMENT_SAMPLER: StatusBits = StatusBits(1 << 4); + pub const CUBIC_ARGUMENT_SAMPLER: StatusBits = StatusBits(1 << 3); /// An indirect mesh draw's arguments pass met a grid that Metal draws and the device cannot /// launch: a mesh grid past the mesh stage's limits, an unfolded object grid past the task /// stage's, or a folded one of more pieces than `MeshArguments::OBJECT_PIECES` (only under task /// limits below Vulkan's required least); the draw drew nothing (`bind::MeshArguments`). - pub const MESH_GRID_PAST_LIMITS: StatusBits = StatusBits(1 << 5); + pub const MESH_GRID_PAST_LIMITS: StatusBits = StatusBits(1 << 4); /// An indirect mesh draw's arguments pass met an object grid of more threadgroups than /// `bind::METAL_OBJECT_GRID_TOTAL`, which Metal's GPU discards; the draw drew nothing /// (`bind::MeshArguments`). - pub const MESH_GRID_DISCARDED: StatusBits = StatusBits(1 << 6); + pub const MESH_GRID_DISCARDED: StatusBits = StatusBits(1 << 5); /// Every bit in `other` is set in `self`. pub const fn contains(self, other: StatusBits) -> bool { self.0 & other.0 == other.0 @@ -242,7 +235,6 @@ mod tests { let bits = [ StatusBits::RESIDENT_MISS, StatusBits::REPLAY_FAULT, - StatusBits::INDEX_POOL_OVERFLOW, StatusBits::ABSENT_ARGUMENT_READ, StatusBits::CUBIC_ARGUMENT_SAMPLER, StatusBits::MESH_GRID_PAST_LIMITS, @@ -271,32 +263,26 @@ mod tests { #[test] fn decode_reports_every_bit_and_counter() { let mut bytes = [0u8; ExecutionStatus::BYTES]; - let bits = StatusBits::INDEX_POOL_OVERFLOW.0 | StatusBits::RESIDENT_MISS.0; + let bits = StatusBits::ABSENT_ARGUMENT_READ.0 | StatusBits::RESIDENT_MISS.0; bytes[0..4].copy_from_slice(&bits.to_le_bytes()); bytes[4..8].copy_from_slice(&7u32.to_le_bytes()); let r = ExecutionStatus::decode(&bytes); - assert!(r.index_pool_overflow && r.resident_miss); + assert!(r.absent_argument_read && r.resident_miss); assert_eq!(r.resident_misses, 7); bytes = [0u8; ExecutionStatus::BYTES]; - bytes[0..4].copy_from_slice(&StatusBits::INDEX_POOL_OVERFLOW.0.to_le_bytes()); + bytes[0..4].copy_from_slice(&StatusBits::ABSENT_ARGUMENT_READ.0.to_le_bytes()); let r = ExecutionStatus::decode(&bytes); - assert!(r.index_pool_overflow && !r.resident_miss); + assert!(r.absent_argument_read && !r.resident_miss); assert_eq!(r.resident_misses, 0); bytes = [0u8; ExecutionStatus::BYTES]; bytes[0..4].copy_from_slice(&StatusBits::REPLAY_FAULT.0.to_le_bytes()); let faults = ReplayFaults::VARIANT.0 | ReplayFaults::RECORD.0; bytes[8..12].copy_from_slice(&faults.to_le_bytes()); let r = ExecutionStatus::decode(&bytes); - assert!(r.replay_fault && !r.index_pool_overflow); + assert!(r.replay_fault && !r.absent_argument_read); assert!(r.replay_faults.contains(ReplayFaults::VARIANT)); assert!(r.replay_faults.contains(ReplayFaults::RECORD)); assert!(!r.replay_faults.contains(ReplayFaults::ENCODING)); - assert!(!r.index_pool_overflow); - bytes = [0u8; ExecutionStatus::BYTES]; - bytes[0..4].copy_from_slice(&StatusBits::INDEX_POOL_OVERFLOW.0.to_le_bytes()); - let r = ExecutionStatus::decode(&bytes); - assert!(r.index_pool_overflow && !r.replay_fault); - assert!(!r.absent_argument_read); bytes = [0u8; ExecutionStatus::BYTES]; bytes[0..4].copy_from_slice(&StatusBits::ABSENT_ARGUMENT_READ.0.to_le_bytes()); let r = ExecutionStatus::decode(&bytes); @@ -305,7 +291,7 @@ mod tests { cubic[0..4].copy_from_slice(&StatusBits::CUBIC_ARGUMENT_SAMPLER.0.to_le_bytes()); let c = ExecutionStatus::decode(&cubic); assert!(c.cubic_argument_sampler && !c.absent_argument_read); - assert!(r.absent_argument_read && !r.index_pool_overflow); + assert!(r.absent_argument_read && !r.replay_fault); } #[test] diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 81c9a8378..80ac01d79 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2225; +pub const SEMANTICS_VERSION: u32 = 2226; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 571; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2545; +pub const RUNTIME_VERSION: u32 = 2546; /// Writes a digest as lowercase hex. pub(crate) fn write_hex(f: &mut fmt::Formatter<'_>, name: &str, hash: &Hash256) -> fmt::Result { diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index 76a296601..afc0ff9dc 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -1275,7 +1275,6 @@ mod bind_serde_round_trips { mesh_arguments: None, object_fold: None, discards_command_buffer: false, - index_bounds_pass: false, extents: Vec::new(), push_holes: Vec::new(), descriptor_ranges: Vec::new(), diff --git a/crates/metal2vulkan/src/tests/owned_divisions.rs b/crates/metal2vulkan/src/tests/owned_divisions.rs index 8ec4c90fc..38fed34a7 100644 --- a/crates/metal2vulkan/src/tests/owned_divisions.rs +++ b/crates/metal2vulkan/src/tests/owned_divisions.rs @@ -8,7 +8,7 @@ use std::collections::BTreeSet; use std::sync::Arc; -use crate::bind::{self, DepthStandInForm, PlanesCopy, RewritePhase, RewriteProgram}; +use crate::bind::{self, DepthStandInForm, PlanesCopy}; use crate::device::{Device, DevicePolicy}; use crate::error::{Error, Feature}; use crate::spirv::testing::{all_ones_divisions, committed_descriptions}; @@ -26,23 +26,11 @@ fn modules() -> Vec { $(out.push((stringify!($f).into(), Box::new(|d| Ok(bind::$f(d)?.spirv))));)* }; } - plain!( - index_bounds_fill_module, - index_bounds_plan_module, - replay_preprocess_module, - ); + plain!(replay_preprocess_module); let mut push = |name: String, build: Box Result, Error> + Sync>| { out.push((name, build)); }; - for program in RewriteProgram::ALL { - for phase in RewritePhase::ALL { - push( - format!("index_rewrite_module({program:?}, {phase:?})"), - Box::new(move |d| Ok(bind::index_rewrite_module(d, program, phase)?.spirv)), - ); - } - } for copy in PlanesCopy::ALL { push( format!("planes_split_module({copy:?})"), diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 941a1de30..2f7fc056c 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -74,39 +74,6 @@ assoc-const metal2vulkan::bind::ExecutionStatus::BYTES pub const BYTES: usize assoc-const metal2vulkan::bind::ExecutionStatus::WORDS pub const WORDS: usize assoc-const metal2vulkan::bind::GeneratedLayout::INDEX_OFFSET pub const INDEX_OFFSET: u32 assoc-const metal2vulkan::bind::GeneratedLayout::PUSH_OFFSET pub const PUSH_OFFSET: u32 -assoc-const metal2vulkan::bind::IndexBoundsFillModule::INDICES_BINDING pub const INDICES_BINDING: u32 -assoc-const metal2vulkan::bind::IndexBoundsFillModule::LOCAL_SIZE pub const LOCAL_SIZE: u32 -assoc-const metal2vulkan::bind::IndexBoundsFillModule::POOL_BINDING pub const POOL_BINDING: u32 -assoc-const metal2vulkan::bind::IndexBoundsFillModule::SET pub const SET: u32 -assoc-const metal2vulkan::bind::IndexBoundsFillModule::WORDS_BINDING pub const WORDS_BINDING: u32 -assoc-const metal2vulkan::bind::IndexBoundsPass::BYTES pub const BYTES: u64 -assoc-const metal2vulkan::bind::IndexBoundsPass::PARAMETER_WORDS pub const PARAMETER_WORDS: usize -assoc-const metal2vulkan::bind::IndexBoundsPass::POOL_HEADER_BYTES pub const POOL_HEADER_BYTES: u64 -assoc-const metal2vulkan::bind::IndexBoundsPlanModule::ARGUMENTS_BINDING pub const ARGUMENTS_BINDING: u32 -assoc-const metal2vulkan::bind::IndexBoundsPlanModule::POOL_BINDING pub const POOL_BINDING: u32 -assoc-const metal2vulkan::bind::IndexBoundsPlanModule::SET pub const SET: u32 -assoc-const metal2vulkan::bind::IndexBoundsPlanModule::STATUS_BINDING pub const STATUS_BINDING: u32 -assoc-const metal2vulkan::bind::IndexBoundsPlanModule::WORDS_BINDING pub const WORDS_BINDING: u32 -assoc-const metal2vulkan::bind::IndexBoundsRun::DISPATCH_OFFSET pub const DISPATCH_OFFSET: u64 -assoc-const metal2vulkan::bind::IndexBoundsRun::HEADER_WORDS pub const HEADER_WORDS: u32 -assoc-const metal2vulkan::bind::IndexBoundsRun::SLOT_BYTES pub const SLOT_BYTES: u64 -assoc-const metal2vulkan::bind::IndexBoundsRun::SLOT_WORDS pub const SLOT_WORDS: u32 -assoc-const metal2vulkan::bind::IndexRewriteModule::ARGUMENTS_BINDING pub const ARGUMENTS_BINDING: u32 -assoc-const metal2vulkan::bind::IndexRewriteModule::INDICES_BINDING pub const INDICES_BINDING: u32 -assoc-const metal2vulkan::bind::IndexRewriteModule::LOCAL_SIZE pub const LOCAL_SIZE: u32 -assoc-const metal2vulkan::bind::IndexRewriteModule::OUTPUT_BINDING pub const OUTPUT_BINDING: u32 -assoc-const metal2vulkan::bind::IndexRewriteModule::SET pub const SET: u32 -assoc-const metal2vulkan::bind::IndexRewriteModule::STATUS_BINDING pub const STATUS_BINDING: u32 -assoc-const metal2vulkan::bind::IndexRewriteModule::WORDS_BINDING pub const WORDS_BINDING: u32 -assoc-const metal2vulkan::bind::IndexRewritePass::BYTES pub const BYTES: u64 -assoc-const metal2vulkan::bind::IndexRewritePass::DRAW_OFFSET pub const DRAW_OFFSET: u64 -assoc-const metal2vulkan::bind::IndexRewritePass::GROUP_POSITIONS pub const GROUP_POSITIONS: u64 -assoc-const metal2vulkan::bind::IndexRewritePass::MAX_GROUPS pub const MAX_GROUPS: u32 -assoc-const metal2vulkan::bind::IndexRewritePass::PARAMETER_WORDS pub const PARAMETER_WORDS: usize -assoc-const metal2vulkan::bind::IndexRewritePass::POOL_HEADER_BYTES pub const POOL_HEADER_BYTES: u64 -assoc-const metal2vulkan::bind::IndexRewriteRun::MAX_DRAWS pub const MAX_DRAWS: u32 -assoc-const metal2vulkan::bind::IndexRewriteRun::SLOT_BYTES pub const SLOT_BYTES: u64 -assoc-const metal2vulkan::bind::IndexRewriteRun::SLOT_WORDS pub const SLOT_WORDS: u32 assoc-const metal2vulkan::bind::InstanceRecord::BYTES pub const BYTES: usize assoc-const metal2vulkan::bind::InterleaveMergeModules::SET pub const SET: u32 assoc-const metal2vulkan::bind::InterleaveMergeModules::WIDE_BINDING pub const WIDE_BINDING: u32 @@ -150,12 +117,9 @@ assoc-const metal2vulkan::bind::ReplayPreprocessModule::PUSH_BYTES pub const PUS assoc-const metal2vulkan::bind::ReplayPreprocessModule::RECORDS_PUSH pub const RECORDS_PUSH: u32 assoc-const metal2vulkan::bind::ReplayPreprocessModule::RESIDENT_PUSH pub const RESIDENT_PUSH: u32 assoc-const metal2vulkan::bind::ReplayPreprocessModule::STATUS_PUSH pub const STATUS_PUSH: u32 -assoc-const metal2vulkan::bind::RewritePhase::ALL pub const ALL: [RewritePhase; 3] -assoc-const metal2vulkan::bind::RewriteProgram::ALL pub const ALL: [RewriteProgram; 8] assoc-const metal2vulkan::bind::RootTable::SINK_HOST_OFFSET pub const SINK_HOST_OFFSET: u32 assoc-const metal2vulkan::bind::StatusBits::ABSENT_ARGUMENT_READ pub const ABSENT_ARGUMENT_READ: StatusBits assoc-const metal2vulkan::bind::StatusBits::CUBIC_ARGUMENT_SAMPLER pub const CUBIC_ARGUMENT_SAMPLER: StatusBits -assoc-const metal2vulkan::bind::StatusBits::INDEX_POOL_OVERFLOW pub const INDEX_POOL_OVERFLOW: StatusBits assoc-const metal2vulkan::bind::StatusBits::MESH_GRID_DISCARDED pub const MESH_GRID_DISCARDED: StatusBits assoc-const metal2vulkan::bind::StatusBits::MESH_GRID_PAST_LIMITS pub const MESH_GRID_PAST_LIMITS: StatusBits assoc-const metal2vulkan::bind::StatusBits::REPLAY_FAULT pub const REPLAY_FAULT: StatusBits @@ -328,39 +292,6 @@ assoc-const-value metal2vulkan::bind::ExecutionStatus::BYTES 16 assoc-const-value metal2vulkan::bind::ExecutionStatus::WORDS 4 assoc-const-value metal2vulkan::bind::GeneratedLayout::INDEX_OFFSET 0 assoc-const-value metal2vulkan::bind::GeneratedLayout::PUSH_OFFSET 4 -assoc-const-value metal2vulkan::bind::IndexBoundsFillModule::INDICES_BINDING 1 -assoc-const-value metal2vulkan::bind::IndexBoundsFillModule::LOCAL_SIZE 64 -assoc-const-value metal2vulkan::bind::IndexBoundsFillModule::POOL_BINDING 2 -assoc-const-value metal2vulkan::bind::IndexBoundsFillModule::SET 0 -assoc-const-value metal2vulkan::bind::IndexBoundsFillModule::WORDS_BINDING 0 -assoc-const-value metal2vulkan::bind::IndexBoundsPass::BYTES 96 -assoc-const-value metal2vulkan::bind::IndexBoundsPass::PARAMETER_WORDS 8 -assoc-const-value metal2vulkan::bind::IndexBoundsPass::POOL_HEADER_BYTES 16 -assoc-const-value metal2vulkan::bind::IndexBoundsPlanModule::ARGUMENTS_BINDING 1 -assoc-const-value metal2vulkan::bind::IndexBoundsPlanModule::POOL_BINDING 2 -assoc-const-value metal2vulkan::bind::IndexBoundsPlanModule::SET 0 -assoc-const-value metal2vulkan::bind::IndexBoundsPlanModule::STATUS_BINDING 3 -assoc-const-value metal2vulkan::bind::IndexBoundsPlanModule::WORDS_BINDING 0 -assoc-const-value metal2vulkan::bind::IndexBoundsRun::DISPATCH_OFFSET 4 -assoc-const-value metal2vulkan::bind::IndexBoundsRun::HEADER_WORDS 8 -assoc-const-value metal2vulkan::bind::IndexBoundsRun::SLOT_BYTES 4 * Self::SLOT_WORDS as u64 -assoc-const-value metal2vulkan::bind::IndexBoundsRun::SLOT_WORDS 28 -assoc-const-value metal2vulkan::bind::IndexRewriteModule::ARGUMENTS_BINDING 1 -assoc-const-value metal2vulkan::bind::IndexRewriteModule::INDICES_BINDING 2 -assoc-const-value metal2vulkan::bind::IndexRewriteModule::LOCAL_SIZE 128 -assoc-const-value metal2vulkan::bind::IndexRewriteModule::OUTPUT_BINDING 3 -assoc-const-value metal2vulkan::bind::IndexRewriteModule::SET 0 -assoc-const-value metal2vulkan::bind::IndexRewriteModule::STATUS_BINDING 4 -assoc-const-value metal2vulkan::bind::IndexRewriteModule::WORDS_BINDING 0 -assoc-const-value metal2vulkan::bind::IndexRewritePass::BYTES 4 * (Output::Groups as u64 + GROUP_WORDS as u64 * Self::MAX_GROUPS as u64) -assoc-const-value metal2vulkan::bind::IndexRewritePass::DRAW_OFFSET 64 -assoc-const-value metal2vulkan::bind::IndexRewritePass::GROUP_POSITIONS 32 * IndexRewriteModule::LOCAL_SIZE as u64 -assoc-const-value metal2vulkan::bind::IndexRewritePass::MAX_GROUPS 256 -assoc-const-value metal2vulkan::bind::IndexRewritePass::PARAMETER_WORDS 16 -assoc-const-value metal2vulkan::bind::IndexRewritePass::POOL_HEADER_BYTES IndexBoundsPass::POOL_HEADER_BYTES -assoc-const-value metal2vulkan::bind::IndexRewriteRun::MAX_DRAWS 65535 -assoc-const-value metal2vulkan::bind::IndexRewriteRun::SLOT_BYTES 4 * Self::SLOT_WORDS as u64 -assoc-const-value metal2vulkan::bind::IndexRewriteRun::SLOT_WORDS 36 assoc-const-value metal2vulkan::bind::InstanceRecord::BYTES 64 assoc-const-value metal2vulkan::bind::InterleaveMergeModules::SET 0 assoc-const-value metal2vulkan::bind::InterleaveMergeModules::WIDE_BINDING 0 @@ -404,14 +335,11 @@ assoc-const-value metal2vulkan::bind::ReplayPreprocessModule::PUSH_BYTES 24 assoc-const-value metal2vulkan::bind::ReplayPreprocessModule::RECORDS_PUSH 16 assoc-const-value metal2vulkan::bind::ReplayPreprocessModule::RESIDENT_PUSH 0 assoc-const-value metal2vulkan::bind::ReplayPreprocessModule::STATUS_PUSH 8 -assoc-const-value metal2vulkan::bind::RewritePhase::ALL [RewritePhase::Count, RewritePhase::Place, RewritePhase::Write] -assoc-const-value metal2vulkan::bind::RewriteProgram::ALL [RewriteProgram::LineStrip, RewriteProgram::TriangleStrip, RewriteProgram::LineLoop, RewriteProgram::TriangleFan, RewriteProgram::Quads, RewriteProgram::QuadStrip, RewriteProgram::LineList, RewriteProgram::TriangleList] assoc-const-value metal2vulkan::bind::RootTable::SINK_HOST_OFFSET (SINK_ROOT * ENTRY_BYTES + HOST) as u32 -assoc-const-value metal2vulkan::bind::StatusBits::ABSENT_ARGUMENT_READ StatusBits(1 <<3) -assoc-const-value metal2vulkan::bind::StatusBits::CUBIC_ARGUMENT_SAMPLER StatusBits(1 <<4) -assoc-const-value metal2vulkan::bind::StatusBits::INDEX_POOL_OVERFLOW StatusBits(1 <<2) -assoc-const-value metal2vulkan::bind::StatusBits::MESH_GRID_DISCARDED StatusBits(1 <<6) -assoc-const-value metal2vulkan::bind::StatusBits::MESH_GRID_PAST_LIMITS StatusBits(1 <<5) +assoc-const-value metal2vulkan::bind::StatusBits::ABSENT_ARGUMENT_READ StatusBits(1 <<2) +assoc-const-value metal2vulkan::bind::StatusBits::CUBIC_ARGUMENT_SAMPLER StatusBits(1 <<3) +assoc-const-value metal2vulkan::bind::StatusBits::MESH_GRID_DISCARDED StatusBits(1 <<5) +assoc-const-value metal2vulkan::bind::StatusBits::MESH_GRID_PAST_LIMITS StatusBits(1 <<4) assoc-const-value metal2vulkan::bind::StatusBits::REPLAY_FAULT StatusBits(1 <<1) assoc-const-value metal2vulkan::bind::StatusBits::RESIDENT_MISS StatusBits(1 <<0) assoc-const-value metal2vulkan::bind::StatusWord::ALL [StatusWord::Status, StatusWord::ResidentMisses, StatusWord::ReplayFaults, StatusWord::SeqCstFences] @@ -908,11 +836,6 @@ enum metal2vulkan::bind::RateMapError #[derive(Clone, Debug, PartialEq, Eq)] #[n enum metal2vulkan::bind::RegionError #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub enum RegionError enum metal2vulkan::bind::ReplayRefusal #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum ReplayRefusal enum metal2vulkan::bind::ResourceClass #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ResourceClass -enum metal2vulkan::bind::RewriteOrder #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum RewriteOrder -enum metal2vulkan::bind::RewriteOutput #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum RewriteOutput -enum metal2vulkan::bind::RewritePhase #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum RewritePhase -enum metal2vulkan::bind::RewriteProgram #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum RewriteProgram -enum metal2vulkan::bind::RewriteSource #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum RewriteSource enum metal2vulkan::bind::SamplerSource #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum SamplerSource enum metal2vulkan::bind::StatusWord #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum StatusWord enum metal2vulkan::bind::TextureShape #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum TextureShape @@ -2125,10 +2048,6 @@ field metal2vulkan::bind::BoundSamplerShape.degree pub degree: u32 field metal2vulkan::bind::BoundSamplerShape.min_level pub min_level: u32 field metal2vulkan::bind::BoundSamplerShape.shape pub shape: SamplerShape field metal2vulkan::bind::BoundSamplerShape.word pub word: metal::sampler::SamplerWord -field metal2vulkan::bind::BoundsRunDraw.arguments_offset pub arguments_offset: u64 -field metal2vulkan::bind::BoundsRunDraw.index_end pub index_end: u64 -field metal2vulkan::bind::BoundsRunDraw.index_offset pub index_offset: u64 -field metal2vulkan::bind::BoundsRunDraw.index_size pub index_size: u64 field metal2vulkan::bind::BufferExtent.slot pub slot: SlotRef field metal2vulkan::bind::BufferExtent.window pub window: Window field metal2vulkan::bind::BufferRange.offset pub offset: u64 @@ -2175,7 +2094,6 @@ field metal2vulkan::bind::DrawCommands.descriptor_ranges pub descriptor_ranges: field metal2vulkan::bind::DrawCommands.discards_command_buffer pub discards_command_buffer: bool field metal2vulkan::bind::DrawCommands.draw pub draw: vk::DrawCommand field metal2vulkan::bind::DrawCommands.extents pub extents: Vec -field metal2vulkan::bind::DrawCommands.index_bounds_pass pub index_bounds_pass: bool field metal2vulkan::bind::DrawCommands.index_overrun pub index_overrun: Option field metal2vulkan::bind::DrawCommands.indirect_needs_arguments pub indirect_needs_arguments: bool field metal2vulkan::bind::DrawCommands.mesh_arguments pub mesh_arguments: Option @@ -2248,21 +2166,8 @@ field metal2vulkan::bind::ImageViewDesc.shader_swizzle pub shader_swizzle: bool field metal2vulkan::bind::ImageViewDesc.view_type pub view_type: vk::ImageViewType field metal2vulkan::bind::ImageblockSize.height pub height: u32 field metal2vulkan::bind::ImageblockSize.width pub width: u32 -field metal2vulkan::bind::IndexBoundsFillModule.requirements pub requirements: Requirements -field metal2vulkan::bind::IndexBoundsFillModule.spirv pub spirv: Arc<[u32]> -field metal2vulkan::bind::IndexBoundsPass.arguments_range pub arguments_range: BufferRange -field metal2vulkan::bind::IndexBoundsPass.indices_range pub indices_range: Option -field metal2vulkan::bind::IndexBoundsPass.parameters pub parameters: [u32; IndexBoundsPass::PARAMETER_WORDS] -field metal2vulkan::bind::IndexBoundsPlanModule.requirements pub requirements: Requirements -field metal2vulkan::bind::IndexBoundsPlanModule.spirv pub spirv: Arc<[u32]> field metal2vulkan::bind::IndexBufferRef.length pub length: u64 field metal2vulkan::bind::IndexBufferRef.token pub token: u32 -field metal2vulkan::bind::IndexRewriteModule.requirements pub requirements: Requirements -field metal2vulkan::bind::IndexRewriteModule.spirv pub spirv: Arc<[u32]> -field metal2vulkan::bind::IndexRewritePass.arguments_range pub arguments_range: Option -field metal2vulkan::bind::IndexRewritePass.groups pub groups: u32 -field metal2vulkan::bind::IndexRewritePass.indices_range pub indices_range: Option -field metal2vulkan::bind::IndexRewritePass.parameters pub parameters: [u32; IndexRewritePass::PARAMETER_WORDS] field metal2vulkan::bind::IndirectRef.offset pub offset: u64 field metal2vulkan::bind::IndirectRef.token pub token: u32 field metal2vulkan::bind::InheritedBytes.index pub index: u32 @@ -2372,13 +2277,6 @@ field metal2vulkan::bind::ResourceUse.class pub class: AccessClass field metal2vulkan::bind::ResourceUse.range pub range: Option field metal2vulkan::bind::ResourceUse.resource pub resource: UseTarget field metal2vulkan::bind::ResourceUse.stages pub stages: vk::PipelineStageFlags2 -field metal2vulkan::bind::RewriteRunDraw.base_instance pub base_instance: u32 -field metal2vulkan::bind::RewriteRunDraw.base_vertex pub base_vertex: i32 -field metal2vulkan::bind::RewriteRunDraw.count pub count: u32 -field metal2vulkan::bind::RewriteRunDraw.index_end pub index_end: u64 -field metal2vulkan::bind::RewriteRunDraw.index_offset pub index_offset: u64 -field metal2vulkan::bind::RewriteRunDraw.instances pub instances: u32 -field metal2vulkan::bind::RewriteRunDraw.wide pub wide: bool field metal2vulkan::bind::RootTable.bytes pub bytes: Vec field metal2vulkan::bind::SamplerDescriptor.border_color pub border_color: metal::SamplerBorderColor field metal2vulkan::bind::SamplerDescriptor.compare_function pub compare_function: metal::CompareFunction @@ -2418,7 +2316,6 @@ field metal2vulkan::bind::StageTable.textures pub textures: BTreeMap field metal2vulkan::bind::StatusReport.absent_argument_read pub absent_argument_read: bool field metal2vulkan::bind::StatusReport.cubic_argument_sampler pub cubic_argument_sampler: bool -field metal2vulkan::bind::StatusReport.index_pool_overflow pub index_pool_overflow: bool field metal2vulkan::bind::StatusReport.mesh_grid_discarded pub mesh_grid_discarded: bool field metal2vulkan::bind::StatusReport.mesh_grid_past_limits pub mesh_grid_past_limits: bool field metal2vulkan::bind::StatusReport.replay_fault pub replay_fault: bool @@ -3510,12 +3407,6 @@ fn metal2vulkan::bind::handle_entry_flags pub fn handle_entry_flags(profile: &De fn metal2vulkan::bind::heap_classes pub fn heap_classes(profile: &DeviceProfile) -> Vec fn metal2vulkan::bind::heap_element pub fn heap_element(profile: &DeviceProfile, class: &HandleClass, facts: &TextureFacts, layout: vk::ImageLayout) -> Result fn metal2vulkan::bind::heap_raw_form pub fn heap_raw_form(facts: &TextureFacts) -> Option -fn metal2vulkan::bind::index_bounds_fill_module pub fn index_bounds_fill_module(device: &Device) -> Result -fn metal2vulkan::bind::index_bounds_fill_run_module pub fn index_bounds_fill_run_module(device: &Device) -> Result -fn metal2vulkan::bind::index_bounds_plan_module pub fn index_bounds_plan_module(device: &Device) -> Result -fn metal2vulkan::bind::index_bounds_plan_run_module pub fn index_bounds_plan_run_module(device: &Device) -> Result -fn metal2vulkan::bind::index_rewrite_module pub fn index_rewrite_module(device: &Device, program: RewriteProgram, phase: RewritePhase) -> Result -fn metal2vulkan::bind::index_rewrite_run_module pub fn index_rewrite_run_module(device: &Device, program: RewriteProgram) -> Result fn metal2vulkan::bind::indirect_commands::records_address pub const fn records_address(id: u64) -> u64 fn metal2vulkan::bind::indirect_commands::written_flag_offset pub const fn written_flag_offset(capacity: u32, index: u32) -> u64 fn metal2vulkan::bind::instance_record pub fn instance_record(instance: &MetalInstance, reference: u64, geometry_table_offset: u32) -> Result @@ -6953,28 +6844,8 @@ method metal2vulkan::bind::GeneratedVariant::new pub fn new(pipeline: &'a Comput method metal2vulkan::bind::HeapElements::element pub fn element(&self, write: &DescriptorWrite) -> Option method metal2vulkan::bind::ImageViewDesc::new pub fn new(view_type: vk::ImageViewType, format: vk::Format, aspect: vk::ImageAspectFlags, layout: vk::ImageLayout, components: vk::ComponentMapping) -> ImageViewDesc method metal2vulkan::bind::ImageblockSize::new pub fn new(width: u32, height: u32) -> ImageblockSize -method metal2vulkan::bind::IndexBoundsPass::new pub fn new(arguments: IndirectRef, index_size: u64, index_offset: u64, index_end: u64, alignment: u64, max_range: u32, pool_bytes: u32) -> Option -method metal2vulkan::bind::IndexBoundsRun::arguments_range pub fn arguments_range(&self) -> BufferRange -method metal2vulkan::bind::IndexBoundsRun::indices_range pub fn indices_range(&self) -> Option -method metal2vulkan::bind::IndexBoundsRun::is_empty pub fn is_empty(&self) -> bool -method metal2vulkan::bind::IndexBoundsRun::len pub fn len(&self) -> usize -method metal2vulkan::bind::IndexBoundsRun::new pub fn new((arguments_start, arguments_end): (u64, u64), indices: Option<(u64, u64)>, (alignment, max_range, max_groups): (u64, u32, u32), pool_bytes: u32) -> Option -method metal2vulkan::bind::IndexBoundsRun::push pub fn push(&mut self, draw: BoundsRunDraw) -> Option -method metal2vulkan::bind::IndexBoundsRun::words pub fn words(&self) -> Vec method metal2vulkan::bind::IndexBufferRef::fetch_end pub fn fetch_end(&self, index_offset: u64) -> u64 method metal2vulkan::bind::IndexBufferRef::new pub fn new(token: u32, length: u64) -> IndexBufferRef -method metal2vulkan::bind::IndexRewritePass::listed pub fn listed(mut self) -> IndexRewritePass -method metal2vulkan::bind::IndexRewritePass::new pub fn new(source: RewriteSource, restart: u32, (index_size, index_offset, index_end): (u64, u64, u64), output: RewriteOutput, alignment: u64, max_range: u32) -> Option -method metal2vulkan::bind::IndexRewritePass::with_order pub fn with_order(mut self, order: RewriteOrder) -> IndexRewritePass -method metal2vulkan::bind::IndexRewriteRun::draw_offset pub fn draw_offset(slot: u32) -> u64 -method metal2vulkan::bind::IndexRewriteRun::indices_range pub fn indices_range(&self) -> Option -method metal2vulkan::bind::IndexRewriteRun::is_empty pub fn is_empty(&self) -> bool -method metal2vulkan::bind::IndexRewriteRun::len pub fn len(&self) -> usize -method metal2vulkan::bind::IndexRewriteRun::new pub fn new((program, order, restart): (RewriteProgram, RewriteOrder, u32), (index_start, index_end): (u64, u64), (alignment, max_range): (u64, u32), output_words: u32) -> Option -method metal2vulkan::bind::IndexRewriteRun::push pub fn push(&mut self, draw: RewriteRunDraw) -> Option -method metal2vulkan::bind::IndexRewriteRun::words pub fn words(&self) -> Vec -method metal2vulkan::bind::IndexRewriteRun::workgroups pub fn workgroups(&self) -> u32 -method metal2vulkan::bind::IndexRewriteRun::written pub fn written(&self) -> u32 method metal2vulkan::bind::IndirectRef::new pub fn new(token: u32, offset: u64) -> IndirectRef method metal2vulkan::bind::InstanceRecord::bytes pub fn bytes(&self) -> &[u8; InstanceRecord::BYTES] method metal2vulkan::bind::MergedLayout::draw_offset pub fn draw_offset(&self, index: u32) -> u64 @@ -7045,16 +6916,6 @@ method metal2vulkan::bind::ResidentSet::is_empty pub fn is_empty(&self) -> bool method metal2vulkan::bind::ResidentSet::len pub fn len(&self) -> u64 method metal2vulkan::bind::ResidentSet::new pub fn new(ranges: impl IntoIterator) -> ResidentSet method metal2vulkan::bind::ResidentSet::with pub fn with(&self, ranges: impl IntoIterator) -> ResidentSet -method metal2vulkan::bind::RewriteOrder::arrange pub fn arrange(self, first: &[T], last: &[T]) -> Vec -method metal2vulkan::bind::RewriteOrder::word pub const fn word(self) -> u32 -method metal2vulkan::bind::RewritePhase::workgroups pub fn workgroups(self, pass: &IndexRewritePass) -> u32 -method metal2vulkan::bind::RewriteProgram::capacity pub fn capacity(self, count: u64) -> u64 -method metal2vulkan::bind::RewriteProgram::list pub fn list(self, values: &[u32], restart: u32, order: RewriteOrder) -> Vec -method metal2vulkan::bind::RewriteProgram::per_step pub fn per_step(self) -> u32 -method metal2vulkan::bind::RewriteProgram::restarts pub fn restarts(self) -> bool -method metal2vulkan::bind::RewriteProgram::sequential_list pub fn sequential_list(self, count: u32, order: RewriteOrder) -> Vec -method metal2vulkan::bind::RewriteProgram::span pub fn span(self) -> u32 -method metal2vulkan::bind::RewriteProgram::vertices pub fn vertices(self) -> u32 method metal2vulkan::bind::RootTable::resident_ranges pub fn resident_ranges(&self) -> Vec method metal2vulkan::bind::SamplerDescriptor::new pub fn new() -> SamplerDescriptor method metal2vulkan::bind::SamplerDescriptor::shape pub fn shape(&self) -> SamplerShape @@ -7817,7 +7678,6 @@ struct metal2vulkan::bind::BindingPlan #[cfg_attr(feature = "serde", derive(serd struct metal2vulkan::bind::BoundAccelerationStructure #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BoundAccelerationStructure struct metal2vulkan::bind::BoundSampler #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct BoundSampler struct metal2vulkan::bind::BoundSamplerShape #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct BoundSamplerShape -struct metal2vulkan::bind::BoundsRunDraw #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct BoundsRunDraw struct metal2vulkan::bind::BufferExtent #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BufferExtent struct metal2vulkan::bind::BufferRange #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BufferRange struct metal2vulkan::bind::BufferRanges #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct BufferRanges @@ -7847,14 +7707,7 @@ struct metal2vulkan::bind::GraphicsTemplate #[cfg_attr(feature = "serde", derive struct metal2vulkan::bind::HeapElements #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct HeapElements struct metal2vulkan::bind::ImageViewDesc #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ImageViewDesc struct metal2vulkan::bind::ImageblockSize #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct ImageblockSize -struct metal2vulkan::bind::IndexBoundsFillModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct IndexBoundsFillModule -struct metal2vulkan::bind::IndexBoundsPass #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct IndexBoundsPass -struct metal2vulkan::bind::IndexBoundsPlanModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct IndexBoundsPlanModule -struct metal2vulkan::bind::IndexBoundsRun #[derive(Clone, Debug, PartialEq, Eq)] pub struct IndexBoundsRun struct metal2vulkan::bind::IndexBufferRef #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct IndexBufferRef -struct metal2vulkan::bind::IndexRewriteModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct IndexRewriteModule -struct metal2vulkan::bind::IndexRewritePass #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct IndexRewritePass -struct metal2vulkan::bind::IndexRewriteRun #[derive(Clone, Debug, PartialEq, Eq)] pub struct IndexRewriteRun struct metal2vulkan::bind::IndirectRef #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct IndirectRef struct metal2vulkan::bind::InheritedBytes #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct InheritedBytes struct metal2vulkan::bind::InstanceRecord #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct InstanceRecord([u8; InstanceRecord::BYTES]) @@ -7889,7 +7742,6 @@ struct metal2vulkan::bind::ReplayVariant #[derive(Clone, Copy, Debug, PartialEq, struct metal2vulkan::bind::ResidentRange #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ResidentRange struct metal2vulkan::bind::ResidentSet #[derive(Clone, Debug, PartialEq, Eq)] pub struct ResidentSet struct metal2vulkan::bind::ResourceUse #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ResourceUse -struct metal2vulkan::bind::RewriteRunDraw #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct RewriteRunDraw struct metal2vulkan::bind::RootTable #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct RootTable struct metal2vulkan::bind::SamplerDescriptor #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct SamplerDescriptor struct metal2vulkan::bind::SamplerShape #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct SamplerShape @@ -9756,7 +9608,6 @@ variant metal2vulkan::bind::DrawReplayRule::ArgumentsOnCpu ArgumentsOnCpu variant metal2vulkan::bind::DrawReplayRule::CommandTypes CommandTypes variant metal2vulkan::bind::DrawReplayRule::FragmentImageblock FragmentImageblock variant metal2vulkan::bind::DrawReplayRule::FragmentWritesMemory FragmentWritesMemory -variant metal2vulkan::bind::DrawReplayRule::IndexBounds IndexBounds variant metal2vulkan::bind::DrawReplayRule::IndexedPrimitiveIds IndexedPrimitiveIds variant metal2vulkan::bind::DrawReplayRule::InputAttachments InputAttachments variant metal2vulkan::bind::DrawReplayRule::MergedHeader MergedHeader @@ -9874,25 +9725,6 @@ variant metal2vulkan::bind::ReplayRefusal::VariantCount VariantCount { count: us variant metal2vulkan::bind::ResourceClass::Buffer Buffer variant metal2vulkan::bind::ResourceClass::Heap Heap variant metal2vulkan::bind::ResourceClass::Texture Texture(TextureFacts) -variant metal2vulkan::bind::RewriteOrder::First First -variant metal2vulkan::bind::RewriteOrder::Last Last -variant metal2vulkan::bind::RewriteOrder::LastFirst LastFirst -variant metal2vulkan::bind::RewriteOutput::Owned Owned { capacity: u32 } -variant metal2vulkan::bind::RewriteOutput::Pooled Pooled { pool_bytes: u32 } -variant metal2vulkan::bind::RewritePhase::Count Count -variant metal2vulkan::bind::RewritePhase::Place Place -variant metal2vulkan::bind::RewritePhase::Write Write -variant metal2vulkan::bind::RewriteProgram::LineList LineList -variant metal2vulkan::bind::RewriteProgram::LineLoop LineLoop -variant metal2vulkan::bind::RewriteProgram::LineStrip LineStrip -variant metal2vulkan::bind::RewriteProgram::QuadStrip QuadStrip -variant metal2vulkan::bind::RewriteProgram::Quads Quads -variant metal2vulkan::bind::RewriteProgram::TriangleFan TriangleFan -variant metal2vulkan::bind::RewriteProgram::TriangleList TriangleList -variant metal2vulkan::bind::RewriteProgram::TriangleStrip TriangleStrip -variant metal2vulkan::bind::RewriteSource::Direct Direct { count: u32, instances: u32, base_vertex: i32, base_instance: u32 } -variant metal2vulkan::bind::RewriteSource::Indirect Indirect { arguments: IndirectRef } -variant metal2vulkan::bind::RewriteSource::IndirectVertices IndirectVertices { arguments: IndirectRef } variant metal2vulkan::bind::SamplerSource::Immutable Immutable variant metal2vulkan::bind::SamplerSource::Neutral Neutral(NeutralResource) variant metal2vulkan::bind::SamplerSource::Slot Slot { slot: SlotRef, compare: bool, integer: bool, opaque_black: OpaqueBlackBorder } diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 2c380b61b..121d5ddc7 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -661,26 +661,6 @@ surface! { struct DepthStencilCopyModules N; struct StencilBit O; struct StencilSplitModule N; - fn index_bounds_fill_module; - fn index_bounds_fill_run_module; - fn index_bounds_plan_module; - fn index_bounds_plan_run_module; - struct BoundsRunDraw E; - struct IndexBoundsFillModule N; - struct IndexBoundsPass N; - struct IndexBoundsPlanModule N; - struct IndexBoundsRun O; - fn index_rewrite_module; - fn index_rewrite_run_module; - struct IndexRewriteModule N; - struct IndexRewritePass N; - struct IndexRewriteRun O; - enum RewriteOrder N; - enum RewriteOutput N; - enum RewritePhase N; - enum RewriteProgram N; - struct RewriteRunDraw E; - enum RewriteSource N; mod fan_out; mod indirect_commands; }