diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs index 7fc0849f0..63c3ef245 100644 --- a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs @@ -110,6 +110,9 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock, Weak}; pub(crate) mod carry; +mod set_states; + +use set_states::{Keyed, SetStates, StateKey}; /// The threadgroup lengths a fresh descriptor binds, as Metal's answers. const DEFAULT_THREADGROUP_LENGTHS: u32 = 31; @@ -652,7 +655,7 @@ impl Device { inheritance, size, options, - pipelines: Mutex::default(), + pipelines: Mutex::new(CommandStates::new(size)), unlocked: UnlockedWrites::new(size), gpu_written: AtomicBool::new(false), gpu_writer: OnceLock::new(), @@ -694,14 +697,13 @@ enum CommandState { /// What the CPU left beside a buffer's records: the pipeline state it set on each command it /// set one on (`CommandState`), by index, none for the rest, so a buffer of commands never -/// encoded holds nothing for them; the kept recordings of its chunks (`kept_commands.rs`), -/// which each write of a command forgets, and those host steps kept; and what the CPU's edits added to what the records may -/// hold (`added`). -#[derive(Default)] +/// encoded holds nothing for them ([`SetStates`]); the kept recordings of its chunks +/// (`kept_commands.rs`), which each write of a command forgets, and those host steps kept; and +/// what the CPU's edits added to what the records may hold (`added`). struct CommandStates { /// Only an edit sets a state here, adding it to `added` (`IndirectCommandBuffer::edit`); a /// reset keeps or drops the one it finds. - states: BTreeMap, + states: SetStates, kept: KeptChunks, /// The kept recordings of its chunks a host step made from the records as the GPU and the CPU /// left them (`render/executions/kept.rs`), each with the bytes it was recorded from: no write @@ -714,26 +716,34 @@ struct CommandStates { } impl CommandStates { + /// What the CPU left beside the records of a buffer of `size` commands as made: nothing. + fn new(size: u32) -> CommandStates { + CommandStates { + states: SetStates::new(size), + kept: KeptChunks::default(), + step_kept: KeptChunks::default(), + added: Default::default(), + } + } + /// The state the CPU set on command `index`. fn state(&self, index: u32) -> Option { - self.states.get(&index).cloned() + self.states.get(index).cloned() } /// The states the CPU set on commands `range`, in order. fn states_in(&self, range: Range) -> Vec { - self.states - .range(range) - .map(|(_, set)| set.clone()) - .collect() + self.states.in_range(range).cloned().collect() } +} - /// Set `set` as the state the CPU set on command `index` (none: none). - fn set(&mut self, index: u32, set: Option) { - match set { - Some(set) => self.states.insert(index, set), - None => self.states.remove(&index), - }; - } +/// A pipeline state a setter sets on a command ([`IndirectCommandBuffer::edit`]): its key, what +/// it may do to indirect command buffers, and the command's state made of it, which only a set +/// where no command names the state yet makes ([`SetStates::set`]). +struct StateSet<'s> { + key: StateKey, + named: Named, + make: &'s dyn Fn() -> CommandState, } /// The ID a state had when the CPU set it on a command, and the serial of its hold of the ID, @@ -746,6 +756,17 @@ struct IdStamp { identifier: u64, } +impl Keyed for CommandState { + fn key(&self) -> StateKey { + let (id, serial) = self.stamp(); + StateKey { + compute: matches!(self, CommandState::Compute(..)), + id, + serial, + } + } +} + impl CommandState { /// A compute command's state: the state while it lives, and its stamp. fn compute(&self) -> Option<(Option, IdStamp)> { @@ -1687,7 +1708,7 @@ impl IndirectCommandBuffer { let mut commands = lock(&self.0.pipelines); for index in range.clone() { self.write(&mut commands, index, &CommandRecord::default())?; - commands.set(index, None); + commands.states.clear(index); } self.clear_overflow(&mut commands, range) } @@ -1882,12 +1903,12 @@ impl IndirectCommandBuffer { } /// Write `field` into command `index`'s record (below the size), and where the field names a - /// pipeline state, `set` as the state the CPU set on it: the field's words alone, in place, as + /// pipeline state, `set`'s as the state the CPU set on it: the field's words alone, in place, as /// Metal's setter writes its field, the rest of the record as the GPU and the CPU left it /// (`CommandRecord::write_field`); then what the record holds joins what its records may /// (`grown_writes`, `add_written`). All of it under one hold of `pipelines`; a buffer slot's /// takes [`edit_slot`](Self::edit_slot). - fn edit(&self, index: u32, field: RecordField, set: Option) -> Result<(), Error> { + fn edit(&self, index: u32, field: RecordField, set: Option>) -> Result<(), Error> { let mut commands = lock(&self.0.pipelines); // SAFETY: the record of a command below the size lies inside the mapped storage, and the // CPU's writes of the records are one at a time (`pipelines`, held while the slice lives), @@ -1904,12 +1925,12 @@ impl IndirectCommandBuffer { _ => internal("an indirect command's record does not take a setter's field"), })?; self.wrote(&mut commands, index..index + 1); - let named = set.as_ref().map(CommandState::named); + let named = set.as_ref().map(|set| set.named); // Read before the state is set, so a state set is always added: only a GPU write since // the field's, the program's race, leaves a record that does not decode here. let grown = self.grown_writes(&commands, bytes, field, named)?; if let Some(set) = set { - commands.set(index, Some(set)); + commands.states.set(index, set.key, set.make); } let followed = match grown { Some(writes) => self.add_written(&mut commands, index, writes, named), @@ -2010,7 +2031,7 @@ impl IndirectCommandBuffer { writes: CommandWrites, set: Option, ) -> Followed { - let named = set.or_else(|| commands.states.get(&index).map(CommandState::named)); + let named = set.or_else(|| commands.states.get(index).map(CommandState::named)); let followed = self.0.written.add_record(writes, named); let pipeline = CommandWrites { operations: named.map_or(0, |_| CommandWrites::PIPELINE), @@ -2024,19 +2045,19 @@ impl IndirectCommandBuffer { followed } - /// Reset command `index` (below the size) by `reset`, which changes its whole record and the - /// pipeline state the CPU set on it, and clear its slots past the record's, as Metal's reset - /// clears every slot. + /// Reset command `index` (below the size) by `reset`, which changes its whole record and + /// answers whether the pipeline state the CPU set on it stays, and clear its slots past the + /// record's, as Metal's reset clears every slot. fn reset_command( &self, index: u32, - reset: impl FnOnce(&mut CommandRecord, &mut Option), + reset: impl FnOnce(&mut CommandRecord) -> bool, ) -> Result<(), Error> { let mut commands = lock(&self.0.pipelines); let mut record = self.record(index)?; - let mut set = commands.states.remove(&index); - reset(&mut record, &mut set); - commands.set(index, set); + if !reset(&mut record) { + commands.states.clear(index); + } self.write(&mut commands, index, &record)?; self.clear_overflow(&mut commands, index..index + 1) } @@ -3464,8 +3485,7 @@ impl IndirectCommandBuffer { let mut stamps = BTreeSet::new(); let sets: Vec = lock(&self.0.pipelines) .states - .range(range) - .map(|(_, set)| set) + .in_range(range) .filter(|set| stamps.insert(set.stamp())) .cloned() .collect(); @@ -4080,7 +4100,7 @@ pub struct IndirectComputeCommand { impl IndirectComputeCommand { /// Write `field` into the record, with `set` as the state the CPU set where it names one /// (`IndirectCommandBuffer::edit`). - fn edit(&self, field: RecordField, set: Option) -> Result<(), Error> { + fn edit(&self, field: RecordField, set: Option>) -> Result<(), Error> { self.icb.edit(self.index, field, set) } @@ -4094,8 +4114,9 @@ impl IndirectComputeCommand { pub fn set_compute_pipeline_state(&self, state: &ComputePipelineState) -> Result<(), Error> { const CALL: &str = "set_compute_pipeline_state"; self.icb.check_command_types(CALL)?; - // The state's program, held while the command takes it (`pipeline/carry.rs`). - let _held = state.hold(); + // The state's program, held while the command takes it (`pipeline/carry.rs`): one hold + // for every read of the state below. + let held = state.hold(); let device = state.bound_device()?; if !device.same(self.icb.generation()) { return Err(device.foreign(CALL, self.icb.generation())); @@ -4120,11 +4141,23 @@ impl IndirectComputeCommand { serial, identifier: state.identifier_value(), }; + // `can_encode_indirect_commands` and `indirect_command_writes`, under the hold. + let interface = state.interface(); let named = Named { - encodes: state.can_encode_indirect_commands(), - writes: state.indirect_command_writes(), + encodes: interface.reaches_command_buffers, + writes: interface.command_writes, + }; + let set = StateSet { + key: StateKey { + compute: true, + id: id.get(), + serial, + }, + named, + make: &|| { + CommandState::Compute(state.downgrade(), state.program_held(&held), stamp, named) + }, }; - let set = CommandState::Compute(state.downgrade(), state.program(), stamp, named); self.edit(RecordField::Pipeline(id), Some(set)) } @@ -4300,13 +4333,14 @@ impl IndirectComputeCommand { /// integration consumer on an M3 without API validation). pub fn reset(&self) -> Result<(), Error> { self.icb.check_command_types("reset")?; - self.icb.reset_command(self.index, |record, _| { + self.icb.reset_command(self.index, |record| { let retained = record.bindings.pipeline.or(record.retained_pipeline); *record = CommandRecord { retained_pipeline: retained, imageblock_size: record.imageblock_size, ..CommandRecord::default() }; + true }) } /// `getCommandType`, Apple's private getter: the command's @@ -4700,7 +4734,7 @@ impl IndirectRenderCommand { &self, call: &'static str, field: RecordField, - set: Option, + set: Option>, ) -> Result<(), Error> { if self.of_compute() { return Err(problem(call, IndirectCommandBufferProblem::CommandKind)); @@ -4716,8 +4750,9 @@ impl IndirectRenderCommand { pub fn set_render_pipeline_state(&self, state: &RenderPipelineState) -> Result<(), Error> { const CALL: &str = "set_render_pipeline_state"; self.icb.check_command_types(CALL)?; - // The state's program, held while the command takes it (`pipeline/carry.rs`). - let _held = state.hold(); + // The state's program, held while the command takes it (`pipeline/carry.rs`): one hold + // for every read of the state below. + let held = state.hold(); let device = state.bound_device()?; if !device.same(self.icb.generation()) { return Err(device.foreign(CALL, self.icb.generation())); @@ -4747,8 +4782,7 @@ impl IndirectRenderCommand { return Err(problem(CALL, IndirectCommandBufferProblem::PipelineKind)); } // A tile pipeline's state has no ID, refused above. - let (Some(named), Some(program), Some(serial)) = - (state.downgrade(), state.program(), state.id_serial()) + let (RenderStateKind::Graphics(graphics), Some(serial)) = (state.kind(), state.id_serial()) else { return Err(problem( CALL, @@ -4760,11 +4794,28 @@ impl IndirectRenderCommand { serial, identifier: state.identifier_value(), }; - let can = Named { - encodes: state.can_encode_indirect_commands(), - writes: state.indirect_command_writes(), + // `can_encode_indirect_commands` and `indirect_command_writes`, under the hold. + let interface = &graphics.base().interface; + let named = Named { + encodes: interface.reaches_command_buffers, + writes: interface.command_writes, + }; + let set = StateSet { + key: StateKey { + compute: false, + id: id.get(), + serial, + }, + named, + make: &|| { + CommandState::Render( + graphics.downgrade(), + graphics.program_held(&held), + stamp, + named, + ) + }, }; - let set = CommandState::Render(named, program, stamp, can); self.edit(CALL, RecordField::Pipeline(id), Some(set)) } @@ -5346,9 +5397,9 @@ impl IndirectRenderCommand { if self.of_compute() && !self.icb.has_no_command_types() { return Err(problem("reset", IndirectCommandBufferProblem::CommandKind)); } - self.icb.reset_command(self.index, |record, pipeline| { + self.icb.reset_command(self.index, |record| { *record = CommandRecord::default(); - *pipeline = None; + false }) } diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs index 1b343f983..2fa06b382 100644 --- a/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs @@ -73,9 +73,9 @@ impl IndirectCommandBuffer { if let Contents::Lost(_) = contents { // Every command reset, as a new buffer's: the states the CPU set on them go. self.write_header().map_err(|_| Left::Failed)?; - commands.states.clear(); + commands.states.clear_all(); } - for state in commands.states.values_mut() { + for state in commands.states.entries_mut() { *state = state.carried(to); } commands.kept.clear(); diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer/set_states.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer/set_states.rs new file mode 100644 index 000000000..8f71911e6 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer/set_states.rs @@ -0,0 +1,241 @@ +//! The pipeline state the CPU set on each command of an indirect command buffer +//! ([`SetStates`]), under the buffer's `pipelines` lock. +//! +//! A command names one of the distinct states set on the buffer's commands, by a slot of its own: +//! a set of a state another command names already stores the slot and counts the command, so a +//! set costs a store whatever the buffer's size, and the table keeps one entry a state, however +//! many commands name it. An entry goes with the last command that names it, so the table holds +//! no state none of the commands names. A recovery's carry carries each entry once +//! ([`entries_mut`](SetStates::entries_mut)). + +use std::collections::HashMap; +use std::ops::Range; + +/// What tells two states the CPU set apart: the kind, the ID and the serial of the state's hold +/// of it (`IdStamp`), which no other state's hold of any ID shares. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) struct StateKey { + pub(super) compute: bool, + pub(super) id: u64, + pub(super) serial: u64, +} + +/// A state a command names, by the key that tells it apart (`CommandState`'s). +pub(super) trait Keyed { + fn key(&self) -> StateKey; +} + +/// A distinct state, and how many commands name it. +struct Entry { + state: S, + commands: u32, +} + +/// The pipeline state the CPU set on each command, by index (the module docs): `S` a +/// `CommandState`. +pub(super) struct SetStates { + /// The buffer's commands. + size: u32, + /// A command's slot: 0 for none, else 1 plus its entry's place in `entries`. Empty until a + /// state is set, so a buffer whose commands never name one holds nothing for them. + slots: Vec, + /// The distinct states, by place; `None` at a place no state holds, which `free` lists. + entries: Vec>>, + free: Vec, + /// Each entry's place, by its state's key. + places: HashMap, + /// The place of the entry set last, looked at first: a buffer's commands mostly name one + /// state in turn. + last: Option<(StateKey, u32)>, +} + +impl SetStates { + /// The table of a buffer of `size` commands: none set. + pub(super) fn new(size: u32) -> SetStates { + SetStates { + size, + slots: Vec::new(), + entries: Vec::new(), + free: Vec::new(), + places: HashMap::new(), + last: None, + } + } + + /// The state the CPU set on command `index`. + pub(super) fn get(&self, index: u32) -> Option<&S> { + let slot = *self.slots.get(index as usize)?; + self.entry(slot).map(|entry| &entry.state) + } + + /// The states the CPU set on commands `range`, in order, skipping those it set none on. + pub(super) fn in_range(&self, range: Range) -> impl Iterator { + let slots = match self.slots.is_empty() { + true => &[][..], + false => &self.slots[range.start as usize..range.end as usize], + }; + slots + .iter() + .filter_map(|&slot| self.entry(slot).map(|entry| &entry.state)) + } + + /// Set the state of key `key` on command `index` (below the size): the entry of that key + /// where a command names one, else `make`'s state, a new entry. + pub(super) fn set(&mut self, index: u32, key: StateKey, make: impl FnOnce() -> S) { + let place = match self.last { + Some((last, place)) if last == key => place, + _ => match self.places.get(&key) { + Some(&place) => place, + None => self.add(key, make()), + }, + }; + self.last = Some((key, place)); + if self.slots.is_empty() { + self.slots = vec![0; self.size as usize]; + } + let slot = place + 1; + let before = std::mem::replace(&mut self.slots[index as usize], slot); + if before == slot { + return; + } + if let Some(entry) = self.entries[place as usize].as_mut() { + entry.commands += 1; + } + self.release(before); + } + + /// Command `index` (below the size) names no state from now on. + pub(super) fn clear(&mut self, index: u32) { + if let Some(slot) = self.slots.get_mut(index as usize) { + let before = std::mem::replace(slot, 0); + self.release(before); + } + } + + /// No command names a state from now on. + pub(super) fn clear_all(&mut self) { + *self = SetStates::new(self.size); + } + + /// Each distinct state a command names, once. + pub(super) fn entries_mut(&mut self) -> impl Iterator { + self.entries + .iter_mut() + .flatten() + .map(|entry| &mut entry.state) + } + + /// The entry of slot `slot`: none for 0. + fn entry(&self, slot: u32) -> Option<&Entry> { + let place = slot.checked_sub(1)?; + self.entries[place as usize].as_ref() + } + + /// `state`, of key `key`, as a new entry no command names yet: its place. + fn add(&mut self, key: StateKey, state: S) -> u32 { + let entry = Some(Entry { state, commands: 0 }); + let place = match self.free.pop() { + Some(place) => { + self.entries[place as usize] = entry; + place + } + None => { + self.entries.push(entry); + (self.entries.len() - 1) as u32 + } + }; + self.places.insert(key, place); + place + } + + /// A command no longer names slot `slot`'s entry (none for 0): the entry goes with the last. + fn release(&mut self, slot: u32) { + let Some(place) = slot.checked_sub(1) else { + return; + }; + let entry = self.entries[place as usize] + .as_mut() + .expect("a command's slot names an entry"); + entry.commands -= 1; + if entry.commands > 0 { + return; + } + let gone = self.entries[place as usize] + .take() + .expect("a command's slot names an entry"); + self.places.remove(&gone.state.key()); + self.free.push(place); + if self.last.is_some_and(|(_, last)| last == place) { + self.last = None; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A state of key `.0`, made `.1`th. + #[derive(Debug, PartialEq)] + struct Made(StateKey, u32); + + impl Keyed for Made { + fn key(&self) -> StateKey { + self.0 + } + } + + fn key(id: u64) -> StateKey { + StateKey { + compute: false, + id, + serial: 1, + } + } + + /// One entry a distinct state, made once while a command names it, shared by the commands + /// that name it, gone with the last of them and made again after; a reset command names + /// none; the range skips commands that name none. + #[test] + fn a_state_is_kept_once_while_a_command_names_it() { + let mut table = SetStates::new(6); + assert!(table.get(0).is_none()); + assert_eq!(table.in_range(0..6).count(), 0); + let mut made = 0; + let mut set = |table: &mut SetStates, index, id| { + table.set(index, key(id), || { + made += 1; + Made(key(id), made) + }) + }; + for index in 0..4 { + set(&mut table, index, 7); + } + set(&mut table, 4, 9); + set(&mut table, 1, 9); + assert_eq!(table.get(0), Some(&Made(key(7), 1))); + assert_eq!(table.get(1), Some(&Made(key(9), 2))); + assert_eq!(table.get(5), None); + let ids: Vec = table.in_range(0..6).map(|state| state.0.id).collect(); + assert_eq!(ids, [7, 9, 7, 7, 9]); + assert_eq!(table.entries_mut().count(), 2); + // The commands that name 7 go: its entry with the last. + for index in [0, 2] { + table.clear(index); + } + assert_eq!(table.entries_mut().count(), 2); + set(&mut table, 3, 9); + assert_eq!(table.entries_mut().count(), 1); + assert_eq!(table.in_range(0..6).count(), 3); + // Set again, it is made again, at the free place. + set(&mut table, 0, 7); + assert_eq!(table.get(0), Some(&Made(key(7), 3))); + assert_eq!(table.entries_mut().count(), 2); + // A command set its own state again changes nothing. + set(&mut table, 0, 7); + assert_eq!(table.get(0), Some(&Made(key(7), 3))); + table.clear_all(); + assert_eq!(table.in_range(0..6).count(), 0); + assert_eq!(table.entries_mut().count(), 0); + } +} diff --git a/crates/metal2vulkan-runtime/src/pipeline/mod.rs b/crates/metal2vulkan-runtime/src/pipeline/mod.rs index 734b48dcc..03e88957d 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/mod.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/mod.rs @@ -1579,7 +1579,13 @@ impl ComputePipelineState { /// What the state runs, held without its ID (`ComputeProgram`). pub(crate) fn program(&self) -> ComputeProgram { - let _held = self.hold(); + let held = self.hold(); + self.program_held(&held) + } + + /// [`program`](Self::program), under `_held`, the caller's hold of the state + /// ([`hold`](Self::hold)): a call that reads more of the state under one hold. + pub(crate) fn program_held(&self, _held: &CallHold<'_>) -> ComputeProgram { ComputeProgram(Arc::clone(self.0.program())) } diff --git a/crates/metal2vulkan-runtime/src/pipeline/render.rs b/crates/metal2vulkan-runtime/src/pipeline/render.rs index 13450b66a..b8072f061 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render.rs @@ -1374,8 +1374,8 @@ impl RenderPipelineState { pub(crate) fn program(&self) -> Option { match &self.0 { Kind::Graphics(state) => { - let _held = state.hold(); - Some(RenderProgram(Arc::clone(state.0.program()))) + let held = state.hold(); + Some(state.program_held(&held)) } Kind::Tile(_) => None, } @@ -2385,6 +2385,13 @@ impl GraphicsState { WeakRenderPipelineState(Arc::downgrade(&self.0)) } + /// What it runs, held without its ID ([`RenderPipelineState::program`]), under `_held`, the + /// caller's hold of it ([`hold`](Self::hold)): a call that reads more of the state under one + /// hold. + pub(crate) fn program_held(&self, _held: &CallHold<'_>) -> RenderProgram { + RenderProgram(Arc::clone(self.0.program())) + } + /// Its program, named without holding it: what a draw's encoder keeps the state's last /// settle under (`live_bind.rs`), which [`runs`](Self::runs) tells apart. pub(crate) fn program_name(&self) -> ProgramName { diff --git a/crates/metal2vulkan-runtime/src/tests/icb_encode_bench.rs b/crates/metal2vulkan-runtime/src/tests/icb_encode_bench.rs index 638807cec..f71cefa01 100644 --- a/crates/metal2vulkan-runtime/src/tests/icb_encode_bench.rs +++ b/crates/metal2vulkan-runtime/src/tests/icb_encode_bench.rs @@ -4,6 +4,11 @@ //! outgrow a CPU's last-level cache) and on one of [`CACHED`] (whose records fit in its L2), its //! commands encoded in turn over and over: //! +//! - **full slot**: `indirect_render_command_at(i)`, a render pipeline state, two vertex buffers +//! (one at `(i % 16) * 16`), a fragment buffer and a draw of primitives, the consumer's +//! `icb_slots_cost` loop through the runtime alone; +//! - **compute slot**: `indirect_compute_command_at(i)` of a buffer of dispatches, a compute +//! pipeline state, two kernel buffers (one at `(i % 16) * 16`) and a dispatch of threadgroups; //! - **three fields**: `indirect_render_command_at(i)`, a vertex buffer at `(i % 8) * 256`, a //! fragment buffer at `(i % 4) * 64` and a draw of primitives, a consumer's loop; //! - **draw only**: the command and its draw; @@ -16,9 +21,10 @@ //! `m2v_cpu_icd`), on the kind of device the cfg selects. use super::blit_holds::{device, Scratch}; +use super::indirect_command_buffer_device::{compute_state, render_state, EXAMPLES}; use crate::{ DrawPrimitiveType, Error, IndirectCommandBuffer, IndirectCommandBufferDescriptor, - ResourceOptions, + ResourceOptions, Size, }; use metal2vulkan::bind::indirect_commands::COMMAND_BYTES; use metal2vulkan::metal::IndirectCommandType; @@ -73,6 +79,13 @@ fn icb_encode_costs() { device.new_buffer(65536, shared).unwrap(), ); let strip = DrawPrimitiveType::from_raw(4).unwrap(); + let triangle = DrawPrimitiveType::from_raw(3).unwrap(); + let render = render_state(&device, true); + let compute = compute_state(&device, EXAMPLES, "scale_and_offset", true); + let mut compute_descriptor = IndirectCommandBufferDescriptor::new(); + compute_descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH; + compute_descriptor.max_kernel_buffer_bind_count = 2; + let group = Size::new(1, 1, 1); eprintln!( "ICB-ENCODE {}: Result<(), Error> {} bytes, Error {} bytes, a record {COMMAND_BYTES} \ bytes, {COMMANDS} commands a loop", @@ -86,7 +99,37 @@ fn icb_encode_costs() { .unwrap(); let records = size * COMMAND_BYTES as u64 / 1024; print( - &format!("{size} commands ({records} KiB of records), three fields"), + &format!("{size} commands ({records} KiB of records), full slot"), + per_command(size, |i| { + let command = icb.indirect_render_command_at(i).unwrap(); + command.set_render_pipeline_state(&render).unwrap(); + command + .set_vertex_buffer(Some(&vertex), (i % 16) * 16, 0) + .unwrap(); + command.set_vertex_buffer(Some(&fragment), 0, 1).unwrap(); + command.set_fragment_buffer(Some(&vertex), 256, 0).unwrap(); + command.draw_primitives(triangle, 0, 3, 1, 0).unwrap(); + }), + ); + let dispatches: IndirectCommandBuffer = device + .new_indirect_command_buffer(&compute_descriptor, size, shared) + .unwrap(); + print( + &format!("{size} commands, compute slot"), + per_command(size, |i| { + let command = dispatches.indirect_compute_command_at(i).unwrap(); + command.set_compute_pipeline_state(&compute).unwrap(); + command + .set_kernel_buffer(Some(&vertex), (i % 16) * 16, 0) + .unwrap(); + command.set_kernel_buffer(Some(&fragment), 0, 1).unwrap(); + command + .concurrent_dispatch_threadgroups(group, group) + .unwrap(); + }), + ); + print( + &format!("{size} commands, three fields"), per_command(size, |i| { let command = icb.indirect_render_command_at(i).unwrap(); command diff --git a/crates/metal2vulkan-runtime/src/tests/indirect_command_buffer_device.rs b/crates/metal2vulkan-runtime/src/tests/indirect_command_buffer_device.rs index a140f78ea..ea7fe4ce3 100644 --- a/crates/metal2vulkan-runtime/src/tests/indirect_command_buffer_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/indirect_command_buffer_device.rs @@ -37,7 +37,7 @@ use std::num::NonZeroU64; const COMMANDS: u32 = 6; /// The owned fixtures' paths under `validation/fixtures/public/`. -const EXAMPLES: &str = "examples/runtime_examples.ll"; +pub(super) const EXAMPLES: &str = "examples/runtime_examples.ll"; const ENCODES: &str = "engine/icb_replay_encode_dispatch.ll"; /// What a setter's call leaves, as the model has it. @@ -231,7 +231,7 @@ fn bound(stage: BufferStage, slot: usize, buffer: Option<&Buffer>, offset: u64) /// A state drawing into `RGBA8Unorm` with the examples' `colored_vertex` and `colored_fragment`, /// made for indirect command buffers where `icb`. -fn render_state(device: &Device, icb: bool) -> RenderPipelineState { +pub(super) fn render_state(device: &Device, icb: bool) -> RenderPipelineState { let library = library(device, EXAMPLES); let vertex = library.new_function_with_name("colored_vertex").unwrap(); let fragment = library.new_function_with_name("colored_fragment").unwrap(); @@ -246,7 +246,12 @@ fn render_state(device: &Device, icb: bool) -> RenderPipelineState { } /// A state of `kernel` of the fixture at `path`, made for indirect command buffers where `icb`. -fn compute_state(device: &Device, path: &str, kernel: &str, icb: bool) -> ComputePipelineState { +pub(super) fn compute_state( + device: &Device, + path: &str, + kernel: &str, + icb: bool, +) -> ComputePipelineState { let function = library(device, path) .new_function_with_name(kernel) .unwrap(); diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 219478517..76ae22869 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 518; /// 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 = 2237; +pub const RUNTIME_VERSION: u32 = 2238; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles