diff --git a/crates/metal2vulkan-runtime/src/argument_table.rs b/crates/metal2vulkan-runtime/src/argument_table.rs index 1a4fd7242..9ff1c5535 100644 --- a/crates/metal2vulkan-runtime/src/argument_table.rs +++ b/crates/metal2vulkan-runtime/src/argument_table.rs @@ -35,8 +35,9 @@ use metal2vulkan::bind::{BoundBuffer, BoundSampler, BoundTexture, StageTable}; use metal2vulkan::pipeline::{ BufferKind, PipelineInterface, SlotClass, SlotInterface, SlotRef, Stage, }; +use std::any::Any; use std::collections::{BTreeMap, BTreeSet}; -use std::sync::{Arc, Mutex, Weak}; +use std::sync::{Arc, Mutex}; /// Entries of a buffer table (`setBuffer:offset:atIndex:` and its stage forms). pub(super) const BUFFER_SLOTS: u32 = 31; @@ -83,11 +84,13 @@ pub(super) struct ArgumentTable { retained: Retained, } -/// The core an argument table was last retained into ([`EncoderCore::id`]), and the objects it -/// bound then, which that core holds ([`ArgumentTable::retain`]): held weakly, so the table never -/// holds an object longer than the core does. +/// The core an argument table was last retained into ([`EncoderCore::id`]) and the objects it +/// bound then, by slot and address in its order ([`ArgumentTable::retain`]). The table holds none +/// of them, so it never holds an object longer than the core does: the core holds each from that +/// retain or an earlier one until its command buffer completes, and nothing is retained into it +/// once it ends, so while it is the core named here no other object has one of the addresses. #[derive(Default)] -struct Retained(Mutex)>>); +struct Retained(Mutex); impl Clone for Retained { fn clone(&self) -> Retained { @@ -95,25 +98,37 @@ impl Clone for Retained { } } -/// The objects an argument table bound, which an encoder's core holds until its command buffer -/// completes ([`ArgumentTable::retain`]), each in the table's order. -struct RetainedObjects { - buffers: Vec, - textures: Vec, - samplers: Vec, +#[derive(Clone, Default)] +struct RetainedBy { + core: Option, + /// Each object's slot (its table, then its index) and address; its storage is kept from + /// one retain to the next. + bound: Vec<((SlotClass, u32), usize)>, } -impl RetainedObjects { - /// Whether `table` binds exactly these objects (by identity), in its order. - fn bound_by(&self, table: &ArgumentTable) -> bool { - self.buffers - .iter() - .eq(table.buffers.values().map(|(b, _)| b)) - && self.textures.iter().eq(table.textures.values()) - && self - .samplers - .iter() - .eq(table.samplers.values().map(|(s, _)| s)) +/// An object an argument table binds, which a command that uses the table holds. +#[derive(Clone, Copy)] +enum Bound<'a> { + Buffer(&'a Buffer), + Texture(&'a Texture), + Sampler(&'a SamplerState), +} + +impl Bound<'_> { + fn address(self) -> usize { + match self { + Bound::Buffer(buffer) => buffer.address(), + Bound::Texture(texture) => texture.address(), + Bound::Sampler(sampler) => sampler.address(), + } + } + + fn held(self) -> Arc { + match self { + Bound::Buffer(buffer) => buffer.held(), + Bound::Texture(texture) => texture.held(), + Bound::Sampler(sampler) => sampler.held(), + } } } @@ -789,30 +804,55 @@ impl ArgumentTable { } } + /// Each object bound, by slot, in the table's order: its buffers, then its textures, then + /// its sampler states, each by index. + fn bound(&self) -> impl DoubleEndedIterator)> { + let buffers = self + .buffers + .iter() + .map(|(&index, (buffer, _))| ((SlotClass::Buffer, index), Bound::Buffer(buffer))); + let textures = self + .textures + .iter() + .map(|(&index, texture)| ((SlotClass::Texture, index), Bound::Texture(texture))); + let samplers = self + .samplers + .iter() + .map(|(&index, (sampler, _))| ((SlotClass::Sampler, index), Bound::Sampler(sampler))); + buffers.chain(textures).chain(samplers) + } + /// Hold everything bound until `core`'s command buffer completes: a command uses it, and /// the command buffer lists it among its used resources (`used_resources.rs`). Once while it /// binds the same objects: where `core` retained the table before and it binds exactly the /// objects it bound then (by identity), `core` holds them and keeps their keys, each a function - /// of its object, until the command buffer completes, so nothing is retained again. + /// of its object, until the command buffer completes, so nothing is retained again. Where it + /// binds others, `core` holds each object the table bound at its slot then already, and takes + /// the rest, each by another reference to it (`retained.rs`): its last first, so they go in + /// the table's order, as one hold of them all went. pub(super) fn retain(&self, core: &mut EncoderCore) { let mut retained = lock(&self.retained.0); - let held = retained - .as_ref() - .filter(|(id, _)| *id == core.id()) - .and_then(|(_, objects)| objects.upgrade()); - if held.is_some_and(|objects| objects.bound_by(self)) { + let RetainedBy { core: by, bound } = &mut *retained; + let same_core = *by == Some(core.id()); + let now = self.bound().map(|(slot, object)| (slot, object.address())); + if same_core && bound.iter().copied().eq(now) { return; } let keys = self.buffers.values().map(|(b, _)| b.identity().key); let texture_keys = self.textures.values().map(Texture::use_key); core.touch_keys(keys.chain(texture_keys)); - let objects = Arc::new(RetainedObjects { - buffers: self.buffers.values().map(|(b, _)| b.clone()).collect(), - textures: self.textures.values().cloned().collect(), - samplers: self.samplers.values().map(|(s, _)| s.clone()).collect(), - }); - *retained = Some((core.id(), Arc::downgrade(&objects))); - core.retain(objects); + for (slot, object) in self.bound().rev() { + let held = same_core + && bound + .binary_search_by_key(&slot, |&(slot, _)| slot) + .is_ok_and(|at| bound[at].1 == object.address()); + if !held { + core.retain_shared(object.held()); + } + } + bound.clear(); + bound.extend(self.bound().map(|(slot, object)| (slot, object.address()))); + *by = Some(core.id()); core.device().shared().counts.argument_table_retained(); } } diff --git a/crates/metal2vulkan-runtime/src/binding.rs b/crates/metal2vulkan-runtime/src/binding.rs index bf0196f65..33cec989f 100644 --- a/crates/metal2vulkan-runtime/src/binding.rs +++ b/crates/metal2vulkan-runtime/src/binding.rs @@ -76,7 +76,7 @@ use std::sync::Arc; /// What an encoder binds: each stage's argument table. pub(super) struct Tables<'a> { - stages: Vec<(Stage, &'a ArgumentTable)>, + stages: &'a [(Stage, &'a ArgumentTable)], /// The resources the encoder made resident, which the bind state lists as used. residency: Option<&'a Residency>, /// A render encoder's pass, whose attachments a draw's input and storage attachments read, @@ -132,7 +132,7 @@ pub(super) struct Tables<'a> { impl<'a> Tables<'a> { /// The tables of `stages`. - pub(super) fn new(stages: Vec<(Stage, &'a ArgumentTable)>) -> Tables<'a> { + pub(super) fn new(stages: &'a [(Stage, &'a ArgumentTable)]) -> Tables<'a> { Tables { stages, residency: None, @@ -732,14 +732,15 @@ fn heap_texture<'a>(tables: &Tables<'a>, source: HeapSource) -> Result<&'a Textu } /// The push writes of `writes` (one region's, or one draw's) with `holes` filled: each hole in -/// the write of its own stages that covers its eight bytes. +/// the write of its own stages that covers its eight bytes. Its writes' bytes become theirs, in +/// their storage. pub(super) fn push_writes( - writes: &[PushConstantWrite], + writes: Vec, holes: &[Hole], ) -> Result, Error> { let mut filled: Vec = writes - .iter() - .map(|write| (write.stages.into(), write.offset, write.bytes.clone())) + .into_iter() + .map(|write| (write.stages.into(), write.offset, write.bytes)) .collect(); for hole in holes { let write = filled @@ -756,7 +757,11 @@ pub(super) fn push_writes( Ok(filled) } -/// Write `writes` into `sets`, the descriptor sets of their layout by set number. +/// The descriptor writes [`write_sets`] hands the driver in one call: their infos sit on the stack. +const WRITES_AT_ONCE: usize = 16; + +/// Write `writes` into `sets`, the descriptor sets of their layout by set number: in order, +/// [`WRITES_AT_ONCE`] at a time. /// /// # Safety /// @@ -770,45 +775,38 @@ pub(super) unsafe fn write_sets( if writes.iter().any(|write| write.set as usize >= sets.len()) { return Err(internal("a descriptor write to a set the layout lacks")); } - let buffer_infos: Vec<[vk::DescriptorBufferInfo; 1]> = writes - .iter() - .map(|write| match write.info { - Info::Buffer(info) => [info], - _ => [vk::DescriptorBufferInfo::default()], - }) - .collect(); - let image_infos: Vec<[vk::DescriptorImageInfo; 1]> = writes - .iter() - .map(|write| match write.info { - Info::Image(info) => [info], - _ => [vk::DescriptorImageInfo::default()], - }) - .collect(); - let texel_views: Vec<[vk::BufferView; 1]> = writes - .iter() - .map(|write| match write.info { - Info::Texel(view) => [view], - _ => [vk::BufferView::null()], - }) - .collect(); - let raw: Vec> = writes - .iter() - .enumerate() - .map(|(i, write)| { + for writes in writes.chunks(WRITES_AT_ONCE) { + let mut buffer_infos = [[vk::DescriptorBufferInfo::default()]; WRITES_AT_ONCE]; + let mut image_infos = [[vk::DescriptorImageInfo::default()]; WRITES_AT_ONCE]; + let mut texel_views = [[vk::BufferView::null()]; WRITES_AT_ONCE]; + for (i, write) in writes.iter().enumerate() { + match write.info { + Info::Buffer(info) => buffer_infos[i] = [info], + Info::Image(info) => image_infos[i] = [info], + Info::Texel(view) => texel_views[i] = [view], + } + } + let mut raw = [vk::WriteDescriptorSet::default(); WRITES_AT_ONCE]; + for (i, write) in writes.iter().enumerate() { let set = vk::WriteDescriptorSet::default() .dst_set(sets[write.set as usize]) .dst_binding(write.binding) .dst_array_element(write.element) .descriptor_type(write.ty); - match write.info { + raw[i] = match write.info { Info::Buffer(_) => set.buffer_info(&buffer_infos[i]), Info::Image(_) => set.image_info(&image_infos[i]), Info::Texel(_) => set.texel_buffer_view(&texel_views[i]), - } - }) - .collect(); - // SAFETY: the caller's contract; every array `raw` points at is live for the call. - unsafe { device.shared().vk().update_descriptor_sets(&raw, &[]) }; + }; + } + // SAFETY: the caller's contract; every array `raw` points at is live for the call. + unsafe { + device + .shared() + .vk() + .update_descriptor_sets(&raw[..writes.len()], &[]) + }; + } Ok(()) } @@ -1459,8 +1457,14 @@ pub(super) fn command_uses( let mut uses = Vec::new(); // The keys of the buffers made resident the command reaches through the resident set, by // address; every other use names its resource (a descriptor, a root table's static, a view). + // Those it names are gathered once it reaches one so: until then each use names its key. let mut reached = BTreeSet::new(); let mut named = BTreeSet::new(); + let name = |named: &mut BTreeSet, reached: &BTreeSet, key| { + if !reached.is_empty() { + named.insert(key); + } + }; for resource in plan.uses.iter().chain(command.uses) { if !resource.access.read && !resource.access.write { continue; @@ -1495,7 +1499,7 @@ pub(super) fn command_uses( access(read, resource.access.read), access(write, resource.access.write), )?; - named.insert(used.key); + name(&mut named, &reached, used.key); uses.push(used); } continue; @@ -1518,7 +1522,7 @@ pub(super) fn command_uses( access(read, resource.access.read), access(write, resource.access.write), ); - named.insert(used.key); + name(&mut named, &reached, used.key); uses.push(used); continue; } @@ -1551,9 +1555,15 @@ pub(super) fn command_uses( let (read, write) = buffer_access(resource.class)?; let (identity, range) = buffer.tracked(range); match resource.resource { - UseTarget::Used(_) => reached.insert(identity.key), - _ => named.insert(identity.key), - }; + UseTarget::Used(_) => { + // The first reached: every use before it named its key. + if reached.is_empty() { + named.extend(uses.iter().map(|used: &Use| used.key)); + } + reached.insert(identity.key); + } + _ => name(&mut named, &reached, identity.key), + } uses.push(Use { key: identity.key, tracked: identity.tracked, diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 44ae3b4ab..1dec6a049 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -1825,6 +1825,17 @@ impl Buffer { } } + /// Another reference to the buffer, which a command buffer holds it by + /// (`EncoderCore::retain_shared`). + pub(super) fn held(&self) -> Arc { + self.0.clone() + } + + /// The buffer's address: no other object's while it lives. + pub(super) fn address(&self) -> usize { + Arc::as_ptr(&self.0) as usize + } + /// The buffer's identity for hazard tracking: a heap buffer's is its heap's, as Metal tracks /// a heap's resources as one ([`Buffer::tracked`]). pub(super) fn identity(&self) -> Identity { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 0107b7600..80c7ebf6b 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -924,7 +924,7 @@ impl State { for segment in part.segments.drain(..) { retained.push(Box::new((segment.work, segment.inputs))); if let Some(mut done) = segment.recorded { - retained.extend(done.retained); + retained.extend(done.retained.into_entry()); done.taken.retain_into(retained); } } @@ -1015,7 +1015,7 @@ impl State { let at = executions_at + *placed; *placed += done.executions.len(); executions.splice(at..at, done.executions); - retained.extend(done.retained); + retained.extend(done.retained.into_entry()); // The segment's keys are its encoder's. if let Some(record) = ended.get_mut(encoder.encoder) { record.keys.extend(done.keys); @@ -1043,7 +1043,7 @@ impl State { } = segment; self.retained.push(Box::new((work, inputs))); if let Some(mut done) = recorded { - self.retained.extend(done.retained); + self.retained.extend(done.retained.into_entry()); done.taken.retain_into(&mut self.retained); } } @@ -2201,7 +2201,7 @@ impl CommandBufferShared { segment.stepped = true; let before = segment.recorded.replace(done); if let Some(mut before) = before { - state.retained.extend(before.retained); + state.retained.extend(before.retained.into_entry()); before.taken.retain_into(&mut state.retained); } } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index d17f15d27..22fc788c0 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -182,7 +182,7 @@ impl State { // recording does. for segment in recorded.segments.drain(..) { if let Some(mut before) = segment.recorded { - self.retained.extend(before.retained); + self.retained.extend(before.retained.into_entry()); before.taken.retain_into(&mut self.retained); } self.retained.push(Box::new(segment.work)); @@ -215,7 +215,7 @@ impl State { self.retained.push(Box::new(first)); } } - self.retained.extend(retained); + self.retained.extend(retained.into_entry()); self.retained.push(Box::new(heaps)); Ok(()) } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs b/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs index daa012213..6f2e05a33 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs @@ -86,7 +86,7 @@ impl CommandBuffer { summary: recorded.summary, sparse: Vec::new(), }); - state.retained.extend(recorded.retained); + state.retained.extend(recorded.retained.into_entry()); // What its commands took is the encoder's, as the switch's commands are. if let Some(record) = state.ended.get_mut(encoder) { record.taken.join(recorded.taken); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index 713205a1d..d90691f00 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -87,6 +87,7 @@ use crate::exit_guard::{self, Call}; use crate::gpu_time; use crate::release; use crate::replay::Replay; +use crate::retained::Retained; use crate::scheduler; use crate::sparse::bind::{bind_batch, BindFailure, Bound}; use crate::sparse::encoder::SparseUpdate; @@ -702,7 +703,7 @@ impl CommandBufferShared { state.recorded[encoder].segments[at].recorded = Some(RecordedSegment { raw, summary: EncoderUses::new(true).finish(), - retained: Vec::new(), + retained: Retained::default(), executions: Vec::new(), keys: Default::default(), taken: Default::default(), diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index c656c0cd6..0863fd54d 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -1514,7 +1514,8 @@ fn record( // table at the texture handle tables. let heap = heap_sets::heap_elements(&variant.pipeline().layout, &plan, &state)?; let texture_table = heap_sets::texture_table(core.device(), &variant.pipeline().layout)?; - let mut bound_tables = binding::Tables::new(vec![(Stage::Kernel, tables.table)]) + let stages = [(Stage::Kernel, tables.table)]; + let mut bound_tables = binding::Tables::new(&stages) .with_residency(tables.residency) .with_texture_table(texture_table.as_ref()) .with_sampler_maps(sampler_maps); @@ -1608,7 +1609,7 @@ fn record( }; let mut push = Vec::with_capacity(commands.regions.len()); for region in &commands.regions { - let writes = binding::push_writes(®ion.push_constants, &bound.holes)?; + let writes = binding::push_writes(region.push_constants.clone(), &bound.holes)?; push.push((region.group_count, writes)); } let objects = std::sync::Arc::clone(variant.objects()); diff --git a/crates/metal2vulkan-runtime/src/descriptor_arena.rs b/crates/metal2vulkan-runtime/src/descriptor_arena.rs index 31b9b5ae4..f54f31d88 100644 --- a/crates/metal2vulkan-runtime/src/descriptor_arena.rs +++ b/crates/metal2vulkan-runtime/src/descriptor_arena.rs @@ -22,7 +22,7 @@ //! pools back to the device's spares, and one that failed or was dropped unsubmitted releases //! them. -use super::error::{internal, vulkan, Error}; +use super::error::{vulkan, Error}; use super::spares::{release_in_section, DescriptorPool}; use super::Device; use ash::vk; @@ -205,12 +205,15 @@ impl DescriptorArena { let info = vk::DescriptorSetAllocateInfo::default() .descriptor_pool(self.pools[at].raw) .set_layouts(&layouts); - // SAFETY: the pool has room for the set (counted); its sets go with it. - let sets = unsafe { raw.allocate_descriptor_sets(&info) }.map_err(vulkan)?; + // The set straight into a local: `ash`'s wrapper collects it into a `Vec`. + let mut set = vk::DescriptorSet::null(); + // SAFETY: the pool has room for the set (counted); its sets go with it. `info` names one + // layout, so the driver writes one set. + unsafe { (raw.fp_v1_0().allocate_descriptor_sets)(raw.handle(), &info, &mut set) } + .result() + .map_err(vulkan)?; self.book.take(at, needs); - sets.first() - .copied() - .ok_or_else(|| internal("the driver allocated no descriptor set")) + Ok(set) } /// Give every pool to the device's spares: the command buffer completed, so no command uses diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 2cc9745eb..990c892fe 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -63,6 +63,7 @@ use super::memory::Memory; use super::mipmap_scratch::MipmapScratch; use super::owned_kernel::OwnedKernels; use super::render_state::{depth_bias_command, DepthBiasCommand}; +use super::render_target::KeptCompatible; use super::resource_ids::{ResourceIds, SamplerIdReads}; use super::sample_planes::PlanesObjects; use super::sampler::{SamplerCount, SamplerKey, SamplerShared}; @@ -302,6 +303,8 @@ pub(super) struct DeviceShared { /// The render passes of its passes without attachments, one per sample count, made on first /// use (`attachmentless.rs`). pub(super) attachmentless: Mutex, + /// The compatible passes it keeps, by shape (`render_target::shared_compatible_pass`). + pub(super) compatible_passes: Mutex, /// The caller's images that move between layouts, and the events' timeline semaphores /// (`interop.rs`). pub(super) interop: Interop, @@ -494,6 +497,7 @@ impl Drop for DeviceShared { lock(&self.depth_copies).destroy(self.vk()); lock(&self.depth_stencil_resolves).destroy(self.vk()); lock(&self.attachmentless).destroy(self.vk()); + lock(&self.compatible_passes).destroy(self.vk()); // What released variants left (`pipeline/kept.rs`). lock(&self.kept).destroy(self); // The graphics pipeline libraries, after every pipeline they linked: each linked @@ -1256,6 +1260,7 @@ impl Device { depth_copies: Mutex::new(DepthCopyObjects::default()), depth_stencil_resolves: Mutex::new(DepthStencilResolveObjects::default()), attachmentless: Mutex::default(), + compatible_passes: Mutex::default(), interop: Interop::default(), heap_keys: Default::default(), rebinds: Default::default(), diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index e168a71b1..480925224 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -38,6 +38,7 @@ use super::rebind::{Holds, Taken}; use super::replay::Replay; use super::residency::Residency; use super::resource::ResourceKey; +use super::retained::Retained; use super::shadow::{ShadowCopy, ShadowSync, ShadowUse, Step}; use super::shadow_merge::ShadowMerge; use super::sparse::encoder::SparseUpdate; @@ -142,7 +143,7 @@ pub(super) struct Continuation(vk::CommandBuffer); pub(super) struct RecordedSegment { pub(super) raw: vk::CommandBuffer, pub(super) summary: Summary, - pub(super) retained: Vec>, + pub(super) retained: Retained, pub(super) executions: Vec, /// The keys its commands' uses named (`used_resources.rs`). pub(super) keys: BTreeSet, @@ -167,7 +168,7 @@ pub(super) struct EncoderCore { /// The order of the encoder's commands, and its summary. uses: EncoderUses, /// What the encoder's commands use; `end` hands it to the command buffer. - retained: Vec>, + retained: Retained, /// What its dispatches and draws executed; `end` hands it to the command buffer. executions: Vec, /// Where the shadowed textures the encoder used stand. @@ -207,7 +208,7 @@ pub(super) struct EncoderCore { pub(super) struct Replayed { pub(super) raws: Vec, pub(super) summary: Summary, - pub(super) retained: Vec>, + pub(super) retained: Retained, pub(super) executions: Vec, pub(super) keys: BTreeSet, pub(super) taken: Taken, @@ -273,7 +274,7 @@ impl EncoderCore { ended: Vec::new(), segments: Vec::new(), uses: EncoderUses::new(ordered), - retained: Vec::new(), + retained: Retained::default(), executions: Vec::new(), shadows: ShadowSync::default(), keys: BTreeSet::new(), @@ -342,7 +343,7 @@ impl EncoderCore { ended: Vec::new(), segments: Vec::new(), uses: EncoderUses::new(ordered), - retained: Vec::new(), + retained: Retained::default(), executions: Vec::new(), shadows: ShadowSync::default(), keys: BTreeSet::new(), @@ -390,7 +391,13 @@ impl EncoderCore { /// Hold `object` until the command buffer completes: the encoder's commands use it. pub(super) fn retain(&mut self, object: impl Any + Send + Sync) { - self.retained.push(Box::new(object)); + self.retained.boxed(Box::new(object)); + } + + /// Hold `object`, a shared one (`Buffer::held` and its kin), until the command buffer + /// completes: by another reference to it, without a box of its own (`retained.rs`). + pub(super) fn retain_shared(&mut self, object: Arc) { + self.retained.shared(object); } /// Add a dispatch or draw the encoder took to the command buffer's execution record, as @@ -948,12 +955,7 @@ impl EncoderCore { sparse: Vec::new(), }); } - // The command buffer's first encoder hands over its list as it is. - if state.retained.is_empty() { - state.retained = retained; - } else { - state.retained.extend(retained); - } + state.retained.extend(retained.into_entry()); state.executions.extend(executions); if !holds.is_empty() { state.holds.push(holds); @@ -1026,7 +1028,7 @@ impl EncoderCore { record(device, core.raw); // SAFETY: as in `barrier`. unsafe { device.end_command_buffer(core.raw) }.map_err(vulkan)?; - core.retained.push(retained); + core.retained.boxed(retained); let EncoderCore { raw, uses, diff --git a/crates/metal2vulkan-runtime/src/generated_execute.rs b/crates/metal2vulkan-runtime/src/generated_execute.rs index 61e9449ca..b6028f9f9 100644 --- a/crates/metal2vulkan-runtime/src/generated_execute.rs +++ b/crates/metal2vulkan-runtime/src/generated_execute.rs @@ -549,7 +549,8 @@ fn record_total( } // What the executions use: the resident resources each variant's plan reaches. let empty = ArgumentTable::default(); - let tables = binding::Tables::new(vec![(Stage::Kernel, &empty)]).with_residency(residency); + let stages = [(Stage::Kernel, &empty)]; + let tables = binding::Tables::new(&stages).with_residency(residency); let none = binding::Command { descriptor_bytes: &[], descriptor_ranges: &[], diff --git a/crates/metal2vulkan-runtime/src/heap_sets.rs b/crates/metal2vulkan-runtime/src/heap_sets.rs index e786efc63..270994a7a 100644 --- a/crates/metal2vulkan-runtime/src/heap_sets.rs +++ b/crates/metal2vulkan-runtime/src/heap_sets.rs @@ -1443,14 +1443,24 @@ fn same(a: &Info, b: &Info) -> bool { /// (`resource_ids.rs`; one past every array's capacity at `u32::MAX`, which [`fit_samplers`] /// leaves out). pub(super) fn listed(samplers: &[SamplerState]) -> Vec { - samplers - .iter() - .map(|sampler| { - let element = u32::try_from(sampler.heap_element()).unwrap_or(u32::MAX); - ArgumentSampler::new(*sampler.descriptor(), sampler.gpu_resource_id().0) - .at_element(element) + samplers.iter().map(argument_sampler).collect() +} + +/// `sampler` as one of the bind state's argument samplers ([`listed`]). +fn argument_sampler(sampler: &SamplerState) -> ArgumentSampler { + let element = u32::try_from(sampler.heap_element()).unwrap_or(u32::MAX); + ArgumentSampler::new(*sampler.descriptor(), sampler.gpu_resource_id().0).at_element(element) +} + +/// Whether `kept` is `samplers` [`listed`], bit for bit (a float of the other sign, which +/// compares equal, is another listing): what a kept bind state need not take again. +pub(super) fn lists(kept: &[ArgumentSampler], samplers: &[SamplerState]) -> bool { + let bits = |s: &ArgumentSampler| [s.desc.lod_min_clamp, s.desc.lod_max_clamp].map(f32::to_bits); + kept.len() == samplers.len() + && kept.iter().zip(samplers).all(|(kept, sampler)| { + let listed = argument_sampler(sampler); + *kept == listed && bits(kept) == bits(&listed) }) - .collect() } /// Where `plan`'s heap writes go for `state`, each heap array holding the capacity of set 1 of diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 0629d46c7..934eea473 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -157,6 +157,7 @@ mod residency; mod resolve; mod resource; mod resource_ids; +mod retained; mod rotated; mod sample_copy; mod sample_interleave; diff --git a/crates/metal2vulkan-runtime/src/linear_attachment.rs b/crates/metal2vulkan-runtime/src/linear_attachment.rs index a5b2a3b35..4401b348b 100644 --- a/crates/metal2vulkan-runtime/src/linear_attachment.rs +++ b/crates/metal2vulkan-runtime/src/linear_attachment.rs @@ -66,7 +66,7 @@ use super::color_reformat::Routing; use super::command_buffer::CommandBuffer; use super::degradation::Degradation; use super::error::{Error, RuntimeGap}; -use super::render_pass::{ColorTarget, Target}; +use super::render_pass::{ColorTarget, Target, MAX_COLOR_ATTACHMENTS}; use super::render_values::LoadAction; use super::Device; use ash::vk; @@ -134,18 +134,23 @@ impl Coverage { } } +/// What a draw writes of each color, by color index: `Some(reads)` where it writes the color, +/// reading it where `reads`; `None` where it writes none, past its colors too. +pub(super) type ColorWrites = [Option; MAX_COLOR_ATTACHMENTS]; + /// What a draw of a state with color attachments `colors` (by color index) writes of each: /// `Some(reads)` where it writes the color (a present attachment with a write mask), reading it as /// it does where `reads` (a blend, or a write mask that keeps some of its channels). -pub(super) fn writes(colors: &[Option]) -> Vec> { +pub(super) fn writes(colors: &[Option]) -> ColorWrites { let all = metal2vulkan::vk::ColorComponentFlags::known_bits(); - colors - .iter() - .map(|state| { - let state = state.as_ref().filter(|s| !s.write_mask.is_empty())?; - Some(state.blend.is_some() || !state.write_mask.contains(all)) - }) - .collect() + let mut writes = [None; MAX_COLOR_ATTACHMENTS]; + for (write, state) in writes.iter_mut().zip(colors) { + *write = state + .as_ref() + .filter(|s| !s.write_mask.is_empty()) + .map(|state| state.blend.is_some() || !state.write_mask.contains(all)); + } + writes } /// What a draw writes of each of the pass's colors, by pass color index: each state color's @@ -153,18 +158,13 @@ pub(super) fn writes(colors: &[Option]) -> Vec], - routing: &Routing, - zeroed: bool, -) -> Vec> { - let mut out: Vec> = Vec::new(); +pub(super) fn pass_writes(state: &[Option], routing: &Routing, zeroed: bool) -> ColorWrites { + let mut out = [None; MAX_COLOR_ATTACHMENTS]; let mut put = |index: u32, reads: bool| { - let index = index as usize; - if out.len() <= index { - out.resize(index + 1, None); + // A pass color's index: less than its colors'. + if let Some(write) = out.get_mut(index as usize) { + *write = Some(write.unwrap_or(false) || reads); } - out[index] = Some(out[index].unwrap_or(false) || reads); }; for (color, &placed) in &routing.placed { if let Some(Some(reads)) = state.get(*color as usize) { diff --git a/crates/metal2vulkan-runtime/src/live_bind.rs b/crates/metal2vulkan-runtime/src/live_bind.rs index 5219f11ae..527322f47 100644 --- a/crates/metal2vulkan-runtime/src/live_bind.rs +++ b/crates/metal2vulkan-runtime/src/live_bind.rs @@ -9,11 +9,14 @@ //! No `set*` call marks a slot: a bound buffer's pages may be rebound or detached between draws, //! which changes its binding with no call, so deriving the binding is the check. While the same //! slots stay bound, nothing is allocated. -//! - **The shape made again only where it may have changed.** A bind shape is each bound slot's +//! - **The shape found again only where it may have changed.** A bind shape is each bound slot's //! shape beside the shapes of the state's other fields (`BindState::shape`: a stage's tables //! are its slots' shapes, and a stage with none is left out). Where every changed slot keeps its //! shape, no slot was bound or unbound, and no other field changed, the shape is the kept one. -//! Any other change makes it again, whole. +//! After any other change, and at an encoder's first draw, it is one the drawing state settled +//! lately where the state has it (`BindState::has_shape`, compared in place: +//! `GraphicsState::kept_shape`), so a pass that draws as the one before it makes none; else it +//! is made again, whole. use metal2vulkan::bind::{BindShape, BindState}; use std::collections::btree_map::Entry; @@ -84,8 +87,13 @@ impl LiveBind { } } - /// The state's shape: the kept one, else made again (counted in `counts`). - pub(super) fn shape(&mut self, counts: &Counters) -> Arc { + /// The state's shape: the kept one, else the one `found` finds of the state, else made + /// again (counted in `counts`). + pub(super) fn shape( + &mut self, + counts: &Counters, + found: impl FnOnce(&BindState) -> Option>, + ) -> Arc { if let Some(shape) = &self.shape { debug_assert!( **shape == self.state.shape(), @@ -93,8 +101,19 @@ impl LiveBind { ); return Arc::clone(shape); } - counts.draw_shape_made(); - let shape = Arc::new(self.state.shape()); + let shape = match found(&self.state) { + Some(shape) => { + debug_assert!( + *shape == self.state.shape(), + "a bind shape found that is not its state's" + ); + shape + } + None => { + counts.draw_shape_made(); + Arc::new(self.state.shape()) + } + }; self.shape = Some(Arc::clone(&shape)); shape } diff --git a/crates/metal2vulkan-runtime/src/pipeline/graphics.rs b/crates/metal2vulkan-runtime/src/pipeline/graphics.rs index d49ba6d7f..45e14b4b6 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/graphics.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/graphics.rs @@ -51,6 +51,55 @@ pub(crate) struct GraphicsKey { pub(crate) sample_positions: Vec<[u8; 2]>, } +/// A [`GraphicsKey`] of a draw's own values, borrowed: what a draw compares with the key its state +/// last found made, and makes a key of only where it looks one up (`begin_graphics_pipeline`). +/// Each field is the key's of the same name. +#[derive(Clone, Copy)] +pub(crate) struct DrawKey<'a> { + pub(crate) specialization: &'a SpecializationKey, + pub(crate) topology: metal2vulkan::vk::PrimitiveTopology, + pub(crate) primitive_restart: bool, + pub(crate) pass: &'a PassShape, + pub(crate) strides: &'a [(u32, u32)], + pub(crate) fixed: FixedState, + pub(crate) sample_positions: &'a [[u8; 2]], +} + +impl DrawKey<'_> { + /// Whether `key` is this one. + pub(crate) fn is(&self, key: &GraphicsKey) -> bool { + let GraphicsKey { + specialization, + topology, + primitive_restart, + pass, + strides, + fixed, + sample_positions, + } = key; + self.specialization == specialization + && self.topology == *topology + && self.primitive_restart == *primitive_restart + && self.pass == pass + && self.strides == &strides[..] + && self.fixed == *fixed + && self.sample_positions == &sample_positions[..] + } + + /// The key, owned. + pub(crate) fn key(&self) -> GraphicsKey { + GraphicsKey { + specialization: self.specialization.clone(), + topology: self.topology, + primitive_restart: self.primitive_restart, + pass: self.pass.clone(), + strides: self.strides.to_vec(), + fixed: self.fixed, + sample_positions: self.sample_positions.to_vec(), + } + } +} + /// The input assembly a key takes for a draw of `topology` with `primitive_restart` through a /// pipeline making `dynamic` dynamic: where the pipeline makes the topology dynamic, its class's /// list topology, and no restart where it makes the restart dynamic, so every draw of the class diff --git a/crates/metal2vulkan-runtime/src/pipeline/mod.rs b/crates/metal2vulkan-runtime/src/pipeline/mod.rs index a60006e26..788ac5e81 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/mod.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/mod.rs @@ -70,7 +70,7 @@ pub use additions::{ RequiredThreadsProblem, }; pub(super) use dispatch_making::RegionPipeline; -pub(super) use graphics::{keyed_assembly, DepthRange, FixedState, GraphicsKey}; +pub(super) use graphics::{keyed_assembly, DepthRange, DrawKey, FixedState, GraphicsKey}; pub(super) use making::Pending; pub(super) use objects::ShaderModules; pub(super) use objects::{create_set_layout, set_needs, RawPipeline, VariantObjects}; diff --git a/crates/metal2vulkan-runtime/src/pipeline/render.rs b/crates/metal2vulkan-runtime/src/pipeline/render.rs index 25b153ee6..5525ca50c 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render.rs @@ -36,7 +36,7 @@ //! [`Function::function_descriptor`]: crate::Function::function_descriptor use super::creation_log::{self, StateLog}; -use super::graphics::{GraphicsKey, Notices}; +use super::graphics::{DrawKey, GraphicsKey, Notices}; use super::kept::{Compiled, Place}; use super::libraries::Linked; use super::making::{Begun, Making, Pending, Ticket}; @@ -50,10 +50,12 @@ use super::tile::TileState; use super::BufferForms; use super::{compile_error, stand_in, PipelineOptions, PIPELINES, PLANS, VARIANTS}; use crate::binary_archive::{self, Used}; +use crate::color_reformat::Routing; use crate::degradation::{BoundFormats, Degradation, Occurrence}; use crate::device::{device_error, lock}; use crate::error::{internal, invalid, ArchivedPipeline, Error, Problem, RuntimeGap}; use crate::framebuffer_fetch; +use crate::render_pass::MAX_COLOR_ATTACHMENTS; use crate::render_target::RenderPassObject; use crate::residency::{every_render_stage, handle_stages}; use crate::resource_ids::{ @@ -63,7 +65,7 @@ use crate::resource_ids::{ use crate::unique_identifier::UniqueIdentifier; use crate::values::Size; use crate::Device; -use metal2vulkan::bind::{BindShape, BindingPlan, FragmentTests}; +use metal2vulkan::bind::{BindShape, BindState, BindingPlan, FragmentTests}; use metal2vulkan::cache::{PipelineKey, SpecializationKey, VariantKey}; use metal2vulkan::metal::{BindingAccess, PixelFormat, PrimitiveTopologyClass, RenderStages}; use metal2vulkan::pipeline::{ @@ -72,6 +74,7 @@ use metal2vulkan::pipeline::{ TessellationDescriptor, }; use metal2vulkan::reflection::{LinkedUseAnswers, RenderPipelineReflection}; +use std::any::Any; use std::collections::{BTreeSet, VecDeque}; use std::sync::{Arc, Mutex, OnceLock, Weak}; @@ -193,6 +196,8 @@ pub(crate) struct Program { settled: Mutex>, /// The `VkPipeline` its last draw found made (`RenderVariant::begin_graphics_pipeline`). last_pipeline: Mutex>, + /// Its routing into the pass colors it was last set in a pass of (`GraphicsState::routed`). + routed: Mutex, u32>)>>, /// What its pool pieces hold (`piece_holds.rs`): its draws' makings and its capture forms' /// translations, kept here so a pool thread never holds the device's last reference. pieces: Arc>, @@ -225,6 +230,10 @@ pub(crate) enum PieceHeld { Capture(Device), } +/// A pass's color formats, by index: what a state's routing is found for +/// ([`GraphicsState::routed`]). +pub(crate) type PassColors = [Option; MAX_COLOR_ATTACHMENTS]; + /// The `VkPipeline` a state's last draw found made in its variant's memo: the variant (held /// weakly, so the state holds it no longer than before, and its address stays its own while /// held), the key, and where the memo's entry lies. @@ -1532,6 +1541,7 @@ impl GraphicsState { captures: Mutex::new(Lru::counted(CAPTURES)), settled: Mutex::new(VecDeque::with_capacity(SETTLED)), last_pipeline: Mutex::new(None), + routed: Mutex::new(None), pieces: PieceHolds::new(), }; StateShared { @@ -1696,6 +1706,29 @@ impl GraphicsState { Arc::ptr_eq(&self.0, &other.0) } + /// Another reference to the state, which a command buffer holds it by + /// (`EncoderCore::retain_shared`). + pub(crate) fn held(&self) -> Arc { + self.0.clone() + } + + /// Its routing into a pass of the colors `pass` (`RenderCommandEncoder::routing`), as `route` + /// finds it: a function of the state and the pass's colors alone, so it is found once for the + /// latest pass colors and kept, and a pass of other colors finds it again. + pub(crate) fn routed( + &self, + pass: &PassColors, + route: impl FnOnce() -> Result, + ) -> Result, u32> { + let mut routed = lock(&self.0.routed); + if let Some((_, routing)) = routed.as_ref().filter(|(colors, _)| colors == pass) { + return routing.clone(); + } + let routing = route().map(Arc::new); + *routed = Some((*pass, routing.clone())); + routing + } + pub(crate) fn texture_handle_stages(&self) -> RenderStages { self.0.base.handle_stages } @@ -1757,6 +1790,17 @@ impl GraphicsState { Ok((variant, plan)) } + /// The shape of `state` among those of what the state settled lately + /// ([`settle_shape`](Self::settle_shape)), compared with the state in place + /// (`BindState::has_shape`): what a draw of `state` settles where it has one, and finds there, + /// without its shape made (`live_bind.rs`). + pub(crate) fn kept_shape(&self, state: &BindState) -> Option> { + lock(&self.0.settled) + .iter() + .find(|(_, last)| state.has_shape(&last.shape)) + .map(|(_, last)| Arc::clone(&last.shape)) + } + /// What a draw of bind shape `shape` runs on in `forms` ([`settle`](Self::settle)'s answer), /// through what the state settled last for its latest [`SETTLED`] shapes: a draw of an equal /// shape in the same forms (the very one, which its encoder kept, `live_bind.rs`, or an equal @@ -2342,7 +2386,7 @@ impl RenderVariant { pub(crate) fn first_use( &self, made: &RawPipeline, - key: &GraphicsKey, + specialization: &SpecializationKey, formats: BoundFormats<'_>, ) { if made.first_drawn() { @@ -2353,7 +2397,7 @@ impl RenderVariant { .creation_pipeline_drawn(); self.objects.device.degrade_specialized( &self.objects.specialized, - &key.specialization, + specialization, Some(formats), Occurrence::Made, ); @@ -2371,22 +2415,23 @@ impl RenderVariant { pub(crate) fn begin_graphics_pipeline( self: &Arc, device: &Device, - key: &GraphicsKey, + key: &DrawKey<'_>, compatible: &Arc, (state, formats): (&GraphicsState, crate::degradation::BoundFormats<'_>), ) -> DrawPipeline { // A draw of this variant and a key equal to the state's last draw's finds that entry // again, made, where it stays, and uses it as a lookup of the key would: the key is - // compared, not hashed. + // compared, not hashed, nor made. let last = lock(&state.0.last_pipeline) .as_ref() .filter(|last| std::ptr::eq(last.variant.as_ptr(), Arc::as_ptr(self))) - .filter(|last| last.key == *key) + .filter(|last| key.is(&last.key)) .map(|last| last.at); if let Some(made) = last.and_then(|at| self.pipelines.made_at(at)) { return DrawPipeline::Made(made); } device.shared().counts.graphics_pipeline_looked_up(); + let key = &key.key(); match self.pipelines.begin_at(key) { (Begun::Made(made), at) => { if let Some(at) = at { diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 80456632d..91e9bc503 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -287,7 +287,7 @@ use super::pipeline::Settled; use super::pipeline::{BufferForms, DrawPipeline}; use super::pipeline::{DrawDynamic, RawPipeline, RenderVariant, VariantObjects}; use super::pipeline::{ - FixedState, GraphicsKey, GraphicsState as DrawingState, RenderPipelineState, RenderStateKind, + DrawKey, FixedState, GraphicsState as DrawingState, RenderPipelineState, RenderStateKind, TileState, }; use super::rate_mapped_pass::{self, RateMappedPass}; @@ -295,7 +295,7 @@ use super::render_pass::{ self, check_memoryless, AspectTarget, Attachment, DepthStencilTarget, PassLayout, RenderPassDescriptor, RenderPassProblem, Target, HIDDEN_DEPTH_FORMAT, MAX_COLOR_ATTACHMENTS, }; -use super::render_state::{self, DepthBiasRecord, EncoderState}; +use super::render_state::{self, DepthBiasRecord, EncoderState, MAX_VIEWPORTS}; use super::render_state::{Compensation, DepthBiasEffect, WrittenDepthClamp}; use super::render_target::{self, covers, PassShape, Position, RenderPassObject}; use super::render_values::{LoadAction, ScissorRect, StoreAction, StoreActionOptions, Viewport}; @@ -621,6 +621,32 @@ struct DrawState { blend_color: [f32; 4], } +/// The states a draw records with (`draw_resident`): the whole draw's, or in a rate-mapped pass +/// each region's of each amplification drawn alone, in order (`rate_mapped_pass.rs`). +enum DrawStates { + Whole([DrawState; 1]), + Regions(Vec>), +} + +impl DrawStates { + /// The states amplification `a` records with: the last amplification's for any past it. + fn of(&self, a: usize) -> &[DrawState] { + match self { + DrawStates::Whole(whole) => whole, + DrawStates::Regions(regions) => ®ions[a.min(regions.len() - 1)], + } + } + + /// Every state. + fn iter_mut(&mut self) -> impl Iterator { + let (whole, regions) = match self { + DrawStates::Whole(whole) => (&mut whole[..], &mut [][..]), + DrawStates::Regions(regions) => (&mut [][..], &mut regions[..]), + }; + whole.iter_mut().chain(regions.iter_mut().flatten()) + } +} + /// The storage the pixel interlock orders that the draws of a render pass instance reach, kind /// by kind: what a draw reads or writes, or what an instance's draws wrote since its last storage /// barrier. A draw that reaches a kind an earlier draw of its instance wrote records after the @@ -1098,7 +1124,7 @@ pub struct RenderCommandEncoder { /// What a render encoder's last draw retained of its own (its pipeline state, its variant's /// objects, its `VkPipeline` and the samplers its bind named), held: a draw retains each again -/// only where it is another object. What an encoder retains goes to its command buffer, which +/// only where it is another object, by another reference to it (`retained.rs`). What an encoder retains goes to its command buffer, which /// holds it until it completes, so an object retained once is held for every later draw of the /// encoder; and as each is held here, an object seen again is the same one. #[derive(Default)] @@ -1122,7 +1148,7 @@ impl LastRetained { .as_ref() .is_some_and(|kept| kept.same(&pipeline)) { - core.retain(pipeline.clone()); + core.retain_shared(pipeline.held()); self.pipeline = Some(pipeline); } if !self @@ -1130,7 +1156,7 @@ impl LastRetained { .as_ref() .is_some_and(|kept| Arc::ptr_eq(kept, &objects)) { - core.retain(Arc::clone(&objects)); + core.retain_shared(objects.clone()); self.objects = Some(objects); } if let Some(made) = made { @@ -1139,14 +1165,15 @@ impl LastRetained { .as_ref() .is_some_and(|kept| Arc::ptr_eq(kept, &made)) { - core.retain(Arc::clone(&made)); + core.retain_shared(made.clone()); self.made = Some(made); } } } /// Retain into `core` the samplers a draw's bind named, unless they are the ones the last - /// draw's named, in order. + /// draw's named, in order: each by another reference to it, the last first, so they go in + /// their order (`retained.rs`). fn retain_samplers(&mut self, core: &mut EncoderCore, samplers: Vec>) { let same = samplers.len() == self.samplers.len() && samplers @@ -1154,7 +1181,9 @@ impl LastRetained { .zip(&self.samplers) .all(|(a, b)| Arc::ptr_eq(a, b)); if !same { - core.retain(samplers.clone()); + for sampler in samplers.iter().rev() { + core.retain_shared(sampler.clone()); + } self.samplers = samplers; } } @@ -1243,7 +1272,7 @@ impl CommandBuffer { }; let rate_map = RateMappedPass::of(CALL, descriptor, &layout)?; let shape = PassShape::of(&layout)?; - let compatible = Arc::new(render_target::compatible_pass(device, &shape)?); + let compatible = render_target::shared_compatible_pass(device, &shape)?; if again.is_none() { if let Some(problem) = self.state().refusal() { return Err(invalid(CALL, problem)); @@ -1515,7 +1544,7 @@ impl RenderCommandEncoder { if let RenderStateKind::Graphics(graphics) = state.kind() { let pass = self.pass_formats(); self.routed = Some(Routed { - routing: Self::route(graphics, &pass).map(Arc::new), + routing: graphics.routed(&pass, || Self::route(graphics, &pass)), state: graphics.clone(), pass, }); @@ -4158,10 +4187,13 @@ impl RenderCommandEncoder { table.refresh_reading(kept, (stage, interface), maps, &mut reshape); } reshape.field(&mut state.used_resources, self.residency.used_resources()); - reshape.field( - &mut state.argument_samplers, - heap_sets::listed(argument_samplers), - ); + // Listed again only where the device's sampler states changed since. + if !heap_sets::lists(&state.argument_samplers, argument_samplers) { + reshape.field( + &mut state.argument_samplers, + heap_sets::listed(argument_samplers), + ); + } let listed = function_tables .iter() .map(VisibleFunctionTable::listed) @@ -4589,7 +4621,7 @@ impl RenderCommandEncoder { } let compatible = match self.passes.iter().find(|(s, _)| *s == shape) { Some((_, pass)) => Arc::clone(pass), - None => Arc::new(render_target::compatible_pass(device, &shape)?), + None => render_target::shared_compatible_pass(device, &shape)?, }; let draws = self.core.command_buffer().begin_draws(&compatible)?; let instance = Instance { @@ -4864,7 +4896,7 @@ impl RenderCommandEncoder { Some(routed) if routed.state.same(pipeline) && routed.pass == pass => { routed.routing.clone() } - _ => Self::route(pipeline, &pass).map(Arc::new), + _ => pipeline.routed(&pass, || Self::route(pipeline, &pass)), } } @@ -5588,8 +5620,9 @@ impl RenderCommandEncoder { } false => { let selects = selects || self.amplification.offsets_viewports(); - let rects = self.state.vk_scissors(selects); - self.drawn.add(&rects); + let mut scissors = [vk::Rect2D::default(); MAX_VIEWPORTS]; + let rects = self.state.vk_scissors_in(selects, &mut scissors); + self.drawn.add(rects); // What it writes of each color, and blends, inside its Vulkan scissors // (`linear_attachment::Coverage`). // Of each pass color its draws store into: a state color where its routing @@ -5603,7 +5636,7 @@ impl RenderCommandEncoder { let zeroed = !self.zeroed_colors(state, &routing).is_empty(); let writes = linear_attachment::writes(colors); let writes = linear_attachment::pass_writes(&writes, &routing, zeroed); - self.coverage.add(&writes, &rects) + self.coverage.add(&writes, rects) } _ => self.coverage.everywhere(), } @@ -6206,16 +6239,17 @@ impl RenderCommandEncoder { }) .map(|bytes| self.tile_memory.buffer(&device, bytes)) .transpose()?; - let mut tables = binding::Tables::new(vec![ + let stages = [ (Stage::Vertex, pass_start.or(Stage::Vertex, &self.vertex)), (Stage::Fragment, &self.fragment), (Stage::Object, pass_start.or(Stage::Object, &self.object)), (Stage::Mesh, pass_start.or(Stage::Mesh, &self.mesh)), - ]) - .with_pass(layout, views) - .with_residency(&self.residency) - .with_texture_table(texture_table.as_ref()) - .with_sampler_maps(self.sampler_maps(&pipeline, &pass_start)?); + ]; + let mut tables = binding::Tables::new(&stages) + .with_pass(layout, views) + .with_residency(&self.residency) + .with_texture_table(texture_table.as_ref()) + .with_sampler_maps(self.sampler_maps(&pipeline, &pass_start)?); // The listed function tables: set 1's elements, or the snapshot a variant without the // function-table array reads in set 0, which has no heap of its own. tables = tables.with_function_tables(&function_tables); @@ -6424,9 +6458,9 @@ impl RenderCommandEncoder { // slice's, else the draw's one slice, or none known where its primitives choose. // `draw_states` holds the recordings of each amplification drawn alone, in order, or of // the whole draw. - let mut draw_states: Vec> = match &self.rate_map { - None => vec![vec![draw_state]], - Some(pass) => { + let mut draw_states = match &self.rate_map { + None => DrawStates::Whole([draw_state]), + Some(pass) => DrawStates::Regions({ let length = self.render_target_array_length; let slices: Vec> = match pipeline.vertex_chooses_slice() || views.view_mask != 0 { @@ -6467,12 +6501,12 @@ impl RenderCommandEncoder { .collect()) }) .collect::>()? - } + }), }; // A draw that reaches no fragment runs its vertex function alone, through empty scissors, // and so do unsized points, and a capture draw, which writes its records alone. if failing == Some(FailingDraw::Untouched) || unsized_points || capture.is_some() { - for state in draw_states.iter_mut().flatten() { + for state in draw_states.iter_mut() { for scissor in &mut state.scissors { *scissor = vk::Rect2D::default(); } @@ -6485,22 +6519,23 @@ impl RenderCommandEncoder { // The class's list topology where the pipeline makes the topology dynamic. let (keyed_topology, keyed_restart) = super::pipeline::keyed_assembly(topology, primitive_restart, &graphics.dynamic_states); - let key = GraphicsKey { - // A mesh draw's own complete key (its threadgroup size), else the plan's. - specialization: commands - .specialization - .clone() - .unwrap_or_else(|| plan.specialization.clone()), + // A mesh draw's own complete key (its threadgroup size), else the plan's. + let specialization = commands + .specialization + .as_ref() + .unwrap_or(&plan.specialization); + // The draw's graphics key, borrowed: made only where the draw looks it up. + let key = DrawKey { + specialization, topology: keyed_topology, primitive_restart: keyed_restart, - pass: instance.shape.clone(), - strides: if dynamic_strides { - Vec::new() - } else { - commands.vertex_strides.clone() + pass: &instance.shape, + strides: match dynamic_strides { + true => &[], + false => &commands.vertex_strides, }, fixed: FixedState::without_dynamic(fixed, &graphics.dynamic_states), - sample_positions: self.layout.sample_positions.clone(), + sample_positions: &self.layout.sample_positions, }; // The formats the draw binds, which a specialized notice names. let formats = |slot| tables.bound_format(slot); @@ -6509,11 +6544,11 @@ impl RenderCommandEncoder { let quiet = self .quiet_bound_values .as_ref() - .is_some_and(|q| q.holds(&variant, &plan, &key.specialization)); + .is_some_and(|q| q.holds(&variant, &plan, specialization)); if !quiet && device.degrade_bound_values( &variant.pipeline().stages, - &key.specialization, + specialization, &|k| plan.specialized_value(k), Some(&formats), ) @@ -6521,7 +6556,7 @@ impl RenderCommandEncoder { self.quiet_bound_values = Some(QuietBoundValues { variant: Arc::clone(&variant), plan: Arc::clone(&plan), - specialization: key.specialization.clone(), + specialization: specialization.clone(), }); } device.degrade_cross_class(&plan.diagnostics, &formats); @@ -6548,7 +6583,7 @@ impl RenderCommandEncoder { variant.begin_graphics_pipeline(&device, &key, &compatible, (&pipeline, &formats)) } false => DrawPipeline::Made(variant.graphics_pipeline( - &key, + &key.key(), &compatible, (&pipeline, &formats), )?), @@ -6562,32 +6597,34 @@ impl RenderCommandEncoder { // A pipeline made at the state's creation announces its notices at the first draw that // finds it made; a draw that began a making announced them as it began it. if let DrawPipeline::Made(made) = &draw_pipeline { - variant.first_use(made, &key, &formats); + variant.first_use(made, specialization, &formats); } let bound = { let mut state = self.core.command_buffer().state(); let memo = Some(&mut self.bind_memo); binding::bind(call, &device, &mut state, &plan, &command, &tables, memo)? }; - let push = binding::push_writes(&commands.push_constants, &bound.holes)?; + // The draw's push bytes, filled in place. + let push = binding::push_writes(commands.push_constants, &bound.holes)?; // A plan that draws one amplification at a time records the draw once per amplification, // in order, each after that amplification's push writes. - let pushes = match commands.amplifications.is_empty() { - true => vec![push], - false => commands - .amplifications - .iter() - .map(|writes| { - let mut all = push.clone(); - all.extend(binding::push_writes(writes, &[])?); - Ok(all) - }) - .collect::, Error>>()?, + let amplified = commands + .amplifications + .iter() + .map(|writes| { + let mut all = push.clone(); + all.extend(binding::push_writes(writes.clone(), &[])?); + Ok(all) + }) + .collect::, Error>>()?; + let pushes = match amplified.is_empty() { + true => std::slice::from_ref(&push), + false => &lified[..], }; let objects = Arc::clone(variant.objects()); // Set 0 per draw; set 1 the device's (written below, once nothing refuses). - let (heap_writes, writes): (Vec<_>, Vec<_>) = - bound.writes.into_iter().partition(|write| write.set > 0); + let mut writes = bound.writes; + let heap_writes: Vec<_> = writes.extract_if(.., |write| write.set > 0).collect(); let set = objects.set_zero(&mut self.core.command_buffer().state().descriptors)?; // SAFETY: the set was just allocated and no command uses it yet; every buffer, view // and sampler written is live (the command buffer retains them below, and a refusal @@ -6596,11 +6633,10 @@ impl RenderCommandEncoder { // The Vulkan draws: the binder's, the index bounds pass's two, or the index rewrite // pass's one. let sized = device.shared().sized_index_bind; - let vk_draws = match (&rewrite, &bounds, index, &mesh_work, commands.draw) { - (Some(pass), ..) => vec![pass.draw(sized)], - (_, Some(pass), Some(source), _, _) => { - pass.draws(source, commands.draw, sized)?.to_vec() - } + let one = |draw| ([draw; 2], 1); + let (vk_draws, count) = match (&rewrite, &bounds, index, &mesh_work, commands.draw) { + (Some(pass), ..) => one(pass.draw(sized)), + (_, Some(pass), Some(source), _, _) => (pass.draws(source, commands.draw, sized)?, 2), // A scanned emulated mesh draw's arguments are its work buffer's. ( _, @@ -6614,7 +6650,7 @@ impl RenderCommandEncoder { }, ) => { let (raw, at) = work.at(offset); - vec![( + one(( None, Some(raw), metal2vulkan::vk::DrawCommand::DrawIndirect { @@ -6622,14 +6658,15 @@ impl RenderCommandEncoder { draw_count, stride, }, - )] + )) } - _ => vec![( + _ => one(( index.and_then(|source| IndexBind::of(source, commands.draw, sized)), indirect.map(|source| source.raw), commands.draw, - )], + )), }; + let vk_draws = &vk_draws[..count]; // The draw's steps before the pass (its copies, its index bounds or rewrite pass) read // what an earlier draw or tile dispatch of the encoder wrote behind a memory barrier: they // record before the draw's render pass instance instead, which follows the writer's. @@ -7005,8 +7042,8 @@ impl RenderCommandEncoder { // Amplification by amplification, each through its recordings' regions: Metal // renders every primitive of one before the next's, and a pixel's regions are one. for (a, push) in pushes.iter().enumerate() { - for state in &draw_states[a.min(draw_states.len() - 1)] { - for &(index, indirect, draw) in &vk_draws { + for state in draw_states.of(a) { + for &(index, indirect, draw) in vk_draws { if indirect.is_some() && matches!( draw, @@ -7081,7 +7118,7 @@ impl RenderCommandEncoder { encoder, draw: self.draw_calls, variant: variant.key().clone(), - specialization: variant.constants(&key.specialization), + specialization: variant.constants(specialization), storage_barrier, query, recordings: owned, @@ -7143,7 +7180,7 @@ impl RenderCommandEncoder { let compiled = variant.pipeline(); objects.announce_bound( (&compiled.stages, Some(&compiled.requirements)), - [(&key.specialization, Some(&formats as BoundFormats<'_>))], + [(specialization, Some(&formats as BoundFormats<'_>))], ); } // A pipeline being made: its creation times once made, and the pass holds it @@ -7171,10 +7208,10 @@ impl RenderCommandEncoder { self.object.retain(&mut self.core); self.mesh.retain(&mut self.core); for source in index.into_iter().chain(indirect) { - self.core.retain(source.buffer.clone()); + self.core.retain_shared(source.buffer.held()); } if let Some(factors) = factors { - self.core.retain(factors.buffer); + self.core.retain_shared(factors.buffer.held()); } // The pass's tile memory, untracked: live until the command buffer completes. if let Some(buffer) = tile_buffer { @@ -7185,7 +7222,7 @@ impl RenderCommandEncoder { .into_iter() .chain(buffers.control_point_indices) { - self.core.retain(buffer.clone()); + self.core.retain_shared(buffer.held()); } self.last_retained .retain_samplers(&mut self.core, bound.samplers); @@ -7521,7 +7558,8 @@ impl RenderCommandEncoder { reshape.field(&mut state.render_area, render_area); reshape.field(&mut state.tile_threadgroup, tile_threadgroup); live.reshaped(reshape); - let shape = live.shape(&self.core.device().shared().counts); + let counts = &self.core.device().shared().counts; + let shape = live.shape(counts, |state| pipeline.kept_shape(state)); // Through what the pipeline state settled lately (`GraphicsState::settle_shape`). let settled = match pipeline.settle_shape(&shape, self.forms) { // A variant whose shadows the storage form or the bind layer refuses (a mesh diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index 8c1f60d39..2284a90c1 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -1645,10 +1645,11 @@ impl RenderCommandEncoder { sample_positions: self.layout.sample_positions.clone(), }; // The formats the encoder's tables bind, which are the command's own. - let tables = crate::binding::Tables::new(vec![ + let stages = [ (metal2vulkan::pipeline::Stage::Vertex, &self.vertex), (metal2vulkan::pipeline::Stage::Fragment, &self.fragment), - ]); + ]; + let tables = crate::binding::Tables::new(&stages); let formats = |slot| tables.bound_format(slot); self.core .device() @@ -1663,7 +1664,7 @@ impl RenderCommandEncoder { Some(&formats), ); let raw = variant.graphics_pipeline(&key, &self.current.compatible, (state, &formats))?; - variant.first_use(&raw, &key, &formats); + variant.first_use(&raw, &key.specialization, &formats); Ok((variant, Some(raw))) } } diff --git a/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs b/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs index d598f6ded..709bcccb6 100644 --- a/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs +++ b/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs @@ -1041,7 +1041,8 @@ impl RenderCommandEncoder { .collect(), mesh: None, }; - let mut tables = binding::Tables::new(vec![(Stage::Kernel, &self.tile)]) + let stages = [(Stage::Kernel, &self.tile)]; + let mut tables = binding::Tables::new(&stages) .with_pass(&self.layout, ViewSetup::default()) .with_tile_scratch(&staged) .with_residency(&self.residency) @@ -1113,7 +1114,7 @@ impl RenderCommandEncoder { let mut regions = Vec::with_capacity(commands.regions.len()); let mut pipelines = Vec::with_capacity(commands.regions.len()); for region in &commands.regions { - let push = binding::push_writes(®ion.push_constants, &bound.holes)?; + let push = binding::push_writes(region.push_constants.clone(), &bound.holes)?; let pipeline = variant.region_pipeline(region, &|slot| tables.bound_format(slot))?; regions.push((pipeline.raw, push, region.group_count)); pipelines.push(pipeline); diff --git a/crates/metal2vulkan-runtime/src/render_state.rs b/crates/metal2vulkan-runtime/src/render_state.rs index 2b31fc820..f6f5ffdbf 100644 --- a/crates/metal2vulkan-runtime/src/render_state.rs +++ b/crates/metal2vulkan-runtime/src/render_state.rs @@ -636,10 +636,15 @@ impl EncoderState { guard: None, })) }; + // Each viewport's, in order (the first refusal is the answer), compared as they come. let used = self.used_viewports(selects); - let each = used.iter().map(one).collect::, Error>>()?; - let first = each.first().copied().flatten(); - if each.iter().all(|c| *c == first) { + let mut each = used.iter().map(&one); + let first = each.next().transpose()?.flatten(); + let mut same = true; + for compensation in each { + same &= compensation? == first; + } + if same { return Ok(first); } // Viewports that differ in their mirror alone: one compensation of `sx` 1, the vertex @@ -652,8 +657,10 @@ impl EncoderState { Compensation { viewport, ..c } }; let base = unmirrored(first); - if each.iter().any(|c| unmirrored(*c) != base) { - return Err(Error::NotImplemented(RuntimeGap::ViewportDepthRange)); + for viewport in used { + if unmirrored(one(viewport)?) != base { + return Err(Error::NotImplemented(RuntimeGap::ViewportDepthRange)); + } } Ok(Some(base.mirrored_by_index(used))) } @@ -802,12 +809,32 @@ impl EncoderState { /// more (the module docs), each clipped to the pixels its viewport overlaps, Metal's implicit /// scissor ([`viewport_pixels`]). pub(super) fn vk_scissors(&self, selects: bool) -> Vec { + self.each_vk_scissor(selects).collect() + } + + /// [`vk_scissors`](Self::vk_scissors) into `rects`, of [`MAX_VIEWPORTS`] (the most a draw + /// uses), without allocating. + pub(super) fn vk_scissors_in<'a>( + &self, + selects: bool, + rects: &'a mut [vk::Rect2D; MAX_VIEWPORTS], + ) -> &'a [vk::Rect2D] { + let count = rects + .iter_mut() + .zip(self.each_vk_scissor(selects)) + .map(|(rect, scissor)| *rect = scissor) + .count(); + &rects[..count] + } + + /// Each of [`vk_scissors`](Self::vk_scissors), in order. + fn each_vk_scissor(&self, selects: bool) -> impl Iterator + '_ { let extent = self.extent.map(i64::from); let none = ScissorRect::new(0, 0, 0, 0); self.used_viewports(selects) .iter() .enumerate() - .map(|(i, viewport)| { + .map(move |(i, viewport)| { let s = match self.scissors.len() { 1 => &self.scissors[0], _ => self.scissors.get(i).unwrap_or(&none), @@ -835,7 +862,6 @@ impl EncoderState { }, } }) - .collect() } /// The draw's viewport count. More than one needs `multiViewport`, which a pipeline that diff --git a/crates/metal2vulkan-runtime/src/render_target.rs b/crates/metal2vulkan-runtime/src/render_target.rs index d25a75edd..30029f3f0 100644 --- a/crates/metal2vulkan-runtime/src/render_target.rs +++ b/crates/metal2vulkan-runtime/src/render_target.rs @@ -96,11 +96,15 @@ //! and `STORE`: render pass compatibility ignores the operations, so the draws' secondary //! command buffer and the encoder's graphics pipelines record against it while the store //! actions may still change. -//! - Both passes and the framebuffer are made per encoder, but for a kept pass; its command buffer -//! holds them until it completes. +//! - **Made and kept.** The pass `end_encoding` begins and the framebuffer are made per encoder, +//! but for a kept pass; its command buffer holds them until it completes. The compatible pass of +//! a shape the device keeps ([`shared_compatible_pass`]): made when an encoder of the shape +//! first needs one and destroyed with the device, for at most [`KEPT_SHAPES`] shapes; an +//! encoder of a shape past them makes its own, which its command buffer holds so. use super::attachmentless; use super::binding_view::VkView; +use super::device::lock; use super::error::{internal, Error}; use super::exit_guard; use super::framebuffer_fetch; @@ -116,6 +120,8 @@ use crate::release; use ash::vk; use metal2vulkan::bind::ViewSetup; use metal2vulkan::device::{DeviceProfile, DriverFact}; +use std::collections::HashMap; +use std::sync::Arc; /// What makes two passes compatible: each color index's format (`None` without a texture), the /// depth/stencil attachment's format, the samples of every attachment, the draws' subpass's @@ -636,6 +642,47 @@ pub(super) fn compatible_pass( } } +/// The most shapes whose compatible pass a device keeps (the module docs): far more than a +/// program's passes take, which a few formats and sample counts make. +const KEPT_SHAPES: usize = 64; + +/// The compatible passes a device keeps, by shape ([`shared_compatible_pass`]). +#[derive(Default)] +pub(super) struct KeptCompatible(HashMap); + +impl KeptCompatible { + /// Destroy every kept pass; the device is idle, and is destroyed next. + pub(super) fn destroy(&self, raw: &ash::Device) { + for &pass in self.0.values() { + // SAFETY: the device is idle, so no pending command uses the pass, and a pipeline + // made with it does not keep it. + unsafe { release::object(raw, pass) }; + } + } +} + +/// [`compatible_pass`], kept: the device's pass of `shape` (the module docs), made now where it +/// keeps none. Every pass of a shape is compatible with every other, so one serves every encoder. +pub(super) fn shared_compatible_pass( + device: &Device, + shape: &PassShape, +) -> Result, Error> { + let kept = &device.shared().compatible_passes; + if let Some(&raw) = lock(kept).0.get(shape) { + return Ok(Arc::new(RenderPassObject::kept(device, raw))); + } + let pass = compatible_pass(device, shape)?; + let mut passes = lock(kept); + // Another encoder's may have come first; a kept pass (without attachments) is kept already. + if pass.owner == Owner::Holders && passes.0.len() < KEPT_SHAPES && !passes.0.contains_key(shape) + { + let raw = pass.into_kept(); + passes.0.insert(shape.clone(), raw); + return Ok(Arc::new(RenderPassObject::kept(device, raw))); + } + Ok(Arc::new(pass)) +} + /// The pass of `shape` with every operation `LOAD` and `STORE`, made now. pub(super) fn made_compatible_pass( device: &Device, diff --git a/crates/metal2vulkan-runtime/src/retained.rs b/crates/metal2vulkan-runtime/src/retained.rs new file mode 100644 index 000000000..0e5ea869f --- /dev/null +++ b/crates/metal2vulkan-runtime/src/retained.rs @@ -0,0 +1,70 @@ +//! What an encoder holds until its command buffer completes: the objects its commands use, in the +//! order it retained them. +//! +//! - **Without a box each.** A shared object (a buffer, a texture, a sampler state, a pipeline +//! state, a variant's objects, a made `VkPipeline`) is held by another reference to it, which +//! costs no allocation; any other object is boxed. A draw retains several of the first kind. +//! - **One entry.** The holds go to the command buffer as one of its entries, boxed as they +//! began: their storage, made at the first hold with room for [`FIRST_HOLDS`], is that box. +//! - **Let go of last first.** The command buffer lets go of what it holds from the last retained +//! back, one entry at a time (`CommandBuffer`'s release, after its completed handlers): the +//! holds go in that same order, so each object goes where its earliest hold goes, as when each +//! hold was an entry of its own. + +use std::any::Any; +use std::sync::Arc; + +/// The holds an encoder's storage makes room for at its first: a pass's draws of a few pipeline +/// states, each of a few objects, without growing it. +const FIRST_HOLDS: usize = 32; + +/// One object held. +enum Held { + Shared(Arc), + Boxed(Box), +} + +/// The holds, in the order retained. +struct Holds(Vec); + +/// Last retained first, as the command buffer lets go of its own entries. +impl Drop for Holds { + fn drop(&mut self) { + while let Some(held) = self.0.pop() { + match held { + Held::Shared(object) => drop(object), + Held::Boxed(object) => drop(object), + } + } + } +} + +/// An encoder's holds (the module docs): none stored until the first. +#[derive(Default)] +pub(super) struct Retained(Option>); + +impl Retained { + /// Hold `object`, boxed. + pub(super) fn boxed(&mut self, object: Box) { + self.holds().push(Held::Boxed(object)); + } + + /// Hold `object`, a shared one, by another reference to it. + pub(super) fn shared(&mut self, object: Arc) { + self.holds().push(Held::Shared(object)); + } + + /// The holds' storage, made at the first. + fn holds(&mut self) -> &mut Vec { + let holds = self + .0 + .get_or_insert_with(|| Box::new(Holds(Vec::with_capacity(FIRST_HOLDS)))); + &mut holds.0 + } + + /// The holds as one entry of a command buffer's (the module docs), or none where there are + /// none. + pub(super) fn into_entry(self) -> Option> { + self.0.map(|holds| holds as Box) + } +} diff --git a/crates/metal2vulkan-runtime/src/sampler.rs b/crates/metal2vulkan-runtime/src/sampler.rs index 05647fad4..2498ec247 100644 --- a/crates/metal2vulkan-runtime/src/sampler.rs +++ b/crates/metal2vulkan-runtime/src/sampler.rs @@ -83,6 +83,7 @@ use metal2vulkan::metal::{ CompareFunction, SamplerAddressMode, SamplerBorderColor, SamplerMinMagFilter, SamplerMipFilter, SamplerReductionMode, }; +use std::any::Any; use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{Arc, Mutex}; @@ -472,6 +473,17 @@ impl Device { } impl SamplerState { + /// Another reference to the sampler state, which a command buffer holds it by + /// (`EncoderCore::retain_shared`). + pub(super) fn held(&self) -> Arc { + self.0.clone() + } + + /// The sampler state's address: no other object's while it lives. + pub(super) fn address(&self) -> usize { + Arc::as_ptr(&self.0) as usize + } + /// `device`: the device that made the state. pub fn device(&self) -> &Device { &self.0.device diff --git a/crates/metal2vulkan-runtime/src/tests/linear_attachment.rs b/crates/metal2vulkan-runtime/src/tests/linear_attachment.rs index cbc06ce68..ee5fe823c 100644 --- a/crates/metal2vulkan-runtime/src/tests/linear_attachment.rs +++ b/crates/metal2vulkan-runtime/src/tests/linear_attachment.rs @@ -3,7 +3,7 @@ //! [`pass_writes`]) and the box the pass's draws write each in ([`Coverage`]). use super::super::color_reformat::Routing; -use super::super::linear_attachment::{pass_writes, writes, Coverage}; +use super::super::linear_attachment::{pass_writes, writes, ColorWrites, Coverage}; use ash::vk; use metal2vulkan::metal::PixelFormat; use metal2vulkan::pipeline::ColorAttachmentState; @@ -12,6 +12,15 @@ use metal2vulkan::vk::{ColorComponentFlags as Mask, Format}; const BLENDED: Option = Some(true); const OPAQUE: Option = Some(false); +/// `writes` to its last color written. +fn listed(writes: ColorWrites) -> Vec> { + let count = writes + .iter() + .rposition(Option::is_some) + .map_or(0, |at| at + 1); + writes[..count].to_vec() +} + fn rect(x: i32, y: i32, width: u32, height: u32) -> vk::Rect2D { vk::Rect2D { offset: vk::Offset2D { x, y }, @@ -35,7 +44,8 @@ fn a_mask_keeping_channels_reads_and_an_empty_one_writes_nothing() { color(Mask::empty()), None, ]; - assert_eq!(writes(&states), [OPAQUE, BLENDED, None, None]); + assert_eq!(listed(writes(&states)), [OPAQUE, BLENDED]); + assert!(writes(&states)[2..].iter().all(Option::is_none)); } #[test] @@ -66,20 +76,26 @@ fn a_draw_writes_the_pass_colors_its_routing_places_and_its_variant_zeroes() { // Each state color at its own index; one the pass lacks is dropped. let same = Routing::by_index(&[bgra, rg], &[bgra, rg]); assert_eq!( - pass_writes(&[BLENDED, OPAQUE], &same, false), + listed(pass_writes(&[BLENDED, OPAQUE], &same, false)), [BLENDED, OPAQUE] ); let dropped = Routing::by_index(&[bgra, rg], &[bgra]); - assert_eq!(pass_writes(&[OPAQUE, BLENDED], &dropped, false), [OPAQUE]); + assert_eq!( + listed(pass_writes(&[OPAQUE, BLENDED], &dropped, false)), + [OPAQUE] + ); // A state lacking color 0 beside its color 1 stores its color 1 into the pass's color 0. let mut moved = Routing::default(); moved.placed.insert(1, 0); - assert_eq!(pass_writes(&[None, BLENDED], &moved, false), [BLENDED]); + assert_eq!( + listed(pass_writes(&[None, BLENDED], &moved, false)), + [BLENDED] + ); // A state of no color whose variant zeroes the pass's color 0 writes it, reading nothing; // one Metal keeps the color under writes none. let bare = Routing::by_index(&[], &[bgra]); - assert_eq!(pass_writes(&[], &bare, true), [OPAQUE]); - assert_eq!(pass_writes(&[], &bare, false), []); + assert_eq!(listed(pass_writes(&[], &bare, true)), [OPAQUE]); + assert_eq!(listed(pass_writes(&[], &bare, false)), []); // Its writes widen the pass's box: copies of the box would otherwise drop them. let mut coverage = Coverage::default(); coverage.add( diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 3ec75826c..70b570f1b 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -4754,6 +4754,17 @@ impl Texture { } } + /// Another reference to the texture, which a command buffer holds it by + /// (`EncoderCore::retain_shared`). + pub(super) fn held(&self) -> Arc { + self.0.clone() + } + + /// The texture's address: no other object's while it lives. + pub(super) fn address(&self) -> usize { + Arc::as_ptr(&self.0) as usize + } + /// The key the texture's uses name (`bound_use`): its image's, or the bytes' of the buffer /// it is over, where its image aliases them or it has none. pub(super) fn use_key(&self) -> ResourceKey { diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 88a07c3ab..7222e2ec9 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -eee78c1455ebb277a20369af1245c7bea94a52380f562edce1ef652f2da8ff83 +d077af133e55b9ed68869d29612022113e8d92c04237b39c4c586a12f3ca5b7d diff --git a/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs b/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs index fb94c1104..3f9c4573f 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs @@ -7,9 +7,10 @@ //! - **Settles.** A draw whose bind state is its encoder's last draw's makes no bind shape and //! settles no variant (`WorkCounts::draw_shapes_made`, `draws_settled`); nor does one that //! binds another texture of the same type, format and usage, whose slot keeps its shape; one of -//! another shape (a texture of another format, a slot's binding of another class) makes its shape, -//! and settles it unless the state settled it among its latest shapes: draws alternating between -//! two shapes settle each once. +//! another shape (a texture of another format, a slot's binding of another class) finds its +//! shape among those the state settled lately, or makes it and settles it: draws alternating +//! between two shapes make and settle each once, and a pass that draws as the one before it +//! makes and settles none. //! - **Pipelines.** A draw of a pipeline state whose last draw found its `VkPipeline` made, of //! the same variant and an equal key, finds that entry again without looking the key up //! (`WorkCounts::graphics_pipelines_looked_up`), states switched between included. @@ -248,9 +249,9 @@ fn draws_of_other_objects_of_one_shape_make_and_settle_nothing() { }); } -/// Draws that bind textures of two formats in turn make their bind shapes at each draw, a shape of -/// the other format not the last draw's, and settle each shape once: the state keeps the settles -/// of its latest shapes. Before, each draw settled again. Each column is its own draw's texture's. +/// Draws that bind textures of two formats in turn make and settle each bind shape once: the state +/// keeps the settles of its latest shapes, among which a draw finds its shape. Before, each draw +/// made its shape, and before that settled it again. Each column is its own draw's texture's. #[test] fn draws_of_another_shape_settle_again() { on_device(|device, _| { @@ -271,7 +272,7 @@ fn draws_of_another_shape_settle_again() { } let after = device.work_counts(); encoder.end_encoding().unwrap(); - assert_eq!(grew(&before, &after, |c| c.draw_shapes_made), SIDE); + assert_eq!(grew(&before, &after, |c| c.draw_shapes_made), 2); assert_eq!(grew(&before, &after, |c| c.draws_settled), 2); let pixels = scene.pixels(&command_buffer); assert!(pixels.iter().all(|&p| p == GREEN), "{pixels:?}"); @@ -282,10 +283,51 @@ fn draws_of_another_shape_settle_again() { }); } +/// A pass that draws as the one before it, each of its encoder's draws of a bind state a draw of +/// the pass before had, makes no bind shape and settles nothing: its first draw, whose encoder +/// keeps no shape, and its draw of the other shape find theirs among those the state settled. +/// Before, each pass's encoder made its shapes again. Every column is drawn. +#[test] +fn a_pass_that_draws_as_the_one_before_makes_no_shape() { + on_device(|device, _| { + let scene = Scene::new(device); + let textures = [ + solid(device, PixelFormat::RGBA8Unorm, GREEN), + solid(device, PixelFormat::BGRA8Unorm, GREEN), + ]; + let pass = || { + let (command_buffer, mut encoder) = scene.encoder(device); + for c in 0..SIDE { + encoder.set_vertex_bytes(&column(c), 0).unwrap(); + encoder + .set_fragment_texture(Some(&textures[(c % 2) as usize]), 0) + .unwrap(); + draw(&mut encoder); + } + encoder.end_encoding().unwrap(); + command_buffer + }; + let first = pass(); + let pixels = scene.pixels(&first); + assert!(pixels.iter().all(|&p| p == GREEN), "{pixels:?}"); + let before = device.work_counts(); + let second = pass(); + let after = device.work_counts(); + assert_eq!(grew(&before, &after, |c| c.draw_shapes_made), 0); + assert_eq!(grew(&before, &after, |c| c.draws_settled), 0); + let pixels = scene.pixels(&second); + assert!(pixels.iter().all(|&p| p == GREEN), "{pixels:?}"); + let (first, second) = (first.executions(), second.executions()); + assert_eq!(second.len(), SIDE as usize); + assert_eq!(first[0].shape(), second[0].shape()); + assert_eq!(first[1].shape(), second[1].shape()); + }); +} + /// Draws whose vertex buffer slot 0 binds a buffer and inline bytes in turn, a binding of another -/// class at the slot each draw, make their bind shapes at each draw, a slot's class being of its -/// shape, and settle each shape once (the state keeps the settles of its latest shapes). Every -/// column is drawn, from the buffer's corners or the bytes'. +/// class at the slot each draw, a slot's class being of its shape, make and settle each shape +/// once (the state keeps the settles of its latest shapes, among which a draw finds its shape). +/// Every column is drawn, from the buffer's corners or the bytes'. #[test] fn draws_that_change_a_slot_s_class_make_their_shapes_again() { on_device(|device, _| { @@ -307,7 +349,7 @@ fn draws_that_change_a_slot_s_class_make_their_shapes_again() { } let after = device.work_counts(); encoder.end_encoding().unwrap(); - assert_eq!(grew(&before, &after, |c| c.draw_shapes_made), SIDE); + assert_eq!(grew(&before, &after, |c| c.draw_shapes_made), 2); assert_eq!(grew(&before, &after, |c| c.draws_settled), 2); let pixels = scene.pixels(&command_buffer); assert!(pixels.iter().all(|&p| p == RED), "{pixels:?}"); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs index 4feaff800..c2ae2cde9 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs @@ -57,10 +57,11 @@ //! allocator as a consumer's process does (the counting one costs the draw path about a sixth of //! its time), and in one without it for the allocations. //! -//! Two checks run by default where the allocations are counted: +//! Three checks run by default where the allocations are counted: //! `a_frame_s_draws_and_pass_ends_allocate_within_their_bounds` holds a frame's draws to //! [`DRAW_ALLOCATIONS`] on the encoding thread, a draw's state changes and its draw call -//! together, and its passes' ends to [`PASS_END_ALLOCATIONS`], each on average; and +//! together, and its passes' ends to [`PASS_END_ALLOCATIONS`], each on average; +//! `a_frame_s_pass_opens_allocate_within_their_bound` its pass opens to [`OPEN_ALLOCATIONS`]; and //! `a_frame_s_commits_allocate_within_their_bound` holds a checked frame's commits to //! [`COMMIT_ALLOCATIONS`] on the encoding thread and to [`SUBMIT_ALLOCATIONS`] on the others //! (the scheduler's checks and submissions, the completion), per command buffer on average. @@ -114,14 +115,25 @@ const TEXTURE_SIDE: u64 = 64; /// The bytes of `zwd_shapes`' `ZwdShape`: rectangle, fill, outline and shape. const SHAPE_BYTES: usize = 64; /// The most allocations a frame's draw makes on the encoding thread on average, its state changes -/// and its draw call together, once every pipeline is made. Measured: 67.5 on RADV (Radeon 780M) -/// and 67.6 on lavapipe; 97.8 on RADV before each texture kept its storage view formats, each -/// encoder its pipeline state's routing, and the format table its entries. +/// and its draw call together, once every pipeline is made. Measured: 24.5 on RADV (Radeon 780M) +/// and ANV (Iris Xe), 24.7 on lavapipe; 67.5 on RADV before a draw compared its +/// pipeline key and bind shape in place, held what it retains by reference, kept its small lists, +/// descriptor writes and push bytes on the stack, and found its pass colors' routing kept; 97.8 +/// before each texture kept its storage view formats, each encoder its pipeline state's routing, +/// and the format table its entries. #[cfg(not(m2v_system_alloc))] -const DRAW_ALLOCATIONS: f64 = 72.0; +const DRAW_ALLOCATIONS: f64 = 27.0; +/// The most allocations a frame's pass open (`render_command_encoder`) makes on the encoding +/// thread on average, once every pipeline is made. Measured: 13.0 on RADV (Radeon 780M), on +/// lavapipe and on ANV (Iris Xe); 18.0 on RADV and ANV before the device kept each pass shape's +/// compatible render pass. +#[cfg(not(m2v_system_alloc))] +const OPEN_ALLOCATIONS: f64 = 14.0; /// The most allocations a frame's pass end (`end_encoding`) makes on the encoding thread on -/// average, once every pipeline is made. Measured: 35.6 on RADV (Radeon 780M) and ANV (Iris Xe), -/// 37.6 on lavapipe; 52.1 on RADV before a pass end retained what its commands use as one object +/// average, once every pipeline is made. Measured: 36.6 on RADV (Radeon 780M) and ANV (Iris Xe), +/// 38.6 on lavapipe, where an encoder's holds reach its command buffer as one entry, which starts +/// the command buffer's list; 35.6 and 37.6 where the first encoder's list became the command +/// buffer's as it was; 52.1 on RADV before a pass end retained what its commands use as one object /// and stopped making the lists it found empty. #[cfg(not(m2v_system_alloc))] const PASS_END_ALLOCATIONS: f64 = 40.0; @@ -129,16 +141,17 @@ const PASS_END_ALLOCATIONS: f64 = 40.0; /// is made: its primary and its draws' secondary. const PASS_BEGINS: u64 = 2; /// The most allocations a checked frame's commit makes on the encoding thread on average, once -/// every pipeline is made. Measured: 5.0 on RADV (Radeon 780M), on lavapipe and on ANV (Iris Xe); -/// 19.0 on RADV before a commit listed only what it reaches among the live buffers and the -/// scheduler kept its order's lines between passes. +/// every pipeline is made. Measured: 4.7 to 5.0 on RADV (Radeon 780M), 5.0 on lavapipe and on ANV +/// (Iris Xe); 19.0 on RADV before a commit listed only what it reaches among the live buffers and +/// the scheduler kept its order's lines between passes. #[cfg(not(m2v_system_alloc))] const COMMIT_ALLOCATIONS: f64 = 6.0; /// The most allocations the process's other threads make per command buffer of a checked frame: /// its check and its batch's planning and submission on the scheduler thread, its completion and -/// its handlers. Measured: 16.0-16.2 on RADV (Radeon 780M), 17.5 on lavapipe, 15.7 on ANV -/// (Iris Xe); 46.9 on RADV before the hazard tracker planned without per-resource allocations, -/// and 21.2 before the scheduler kept its order's lines between passes. +/// its handlers, which varies with how the threads take turns. Measured: 14.8 to 16.3 on RADV +/// (Radeon 780M), 16.8 to 17.5 on lavapipe, 15.7 to 16.8 on ANV (Iris Xe); 46.9 on RADV before the +/// hazard tracker planned without per-resource allocations, and 21.2 before the scheduler kept its +/// order's lines between passes. #[cfg(not(m2v_system_alloc))] const SUBMIT_ALLOCATIONS: f64 = 20.0; @@ -1129,39 +1142,50 @@ fn frame_costs_announced() { measure(&[Run::ANNOUNCED]); } -/// A frame's draws allocate at most [`DRAW_ALLOCATIONS`] each on average on the encoding thread, -/// once every pipeline is made: what the draw path keeps of what it found before (each texture's -/// storage view formats, the pipeline state's routing into the pass's colors, the settles of its -/// latest bind shapes, the format table) is not made again at each draw. Its passes' ends -/// allocate at most [`PASS_END_ALLOCATIONS`] each: a pass end retains what its commands use as one -/// object, and makes no tile grid where a draw reaches every tile, no sample planes' steps in a -/// pass without planes, and no scrub's list for a texture that is not sparse. +/// One frame of a plain device, once every pipeline is made and every pool piece done, its +/// allocations counted; and the device's name. #[cfg(not(m2v_system_alloc))] -#[test] -fn a_frame_s_draws_and_pass_ends_allocate_within_their_bounds() { +fn counted() -> (String, Frame) { let cache = ScratchCache::new().unwrap(); let heard = Heard::default(); let work = Workload::new(device(&cache, false, &heard), false); - // Every pipeline made, and every pool piece done, before the frame that counts. for _ in 0..WARM { work.frame(); } let frame = work.frame(); - let allocations: u64 = frame.draws.iter().map(|s| s.allocations.unwrap()).sum(); - let each = allocations as f64 / frame.draws.len() as f64; - eprintln!( - "FRAME-COST {}: {each:.2} allocations a draw, at most {DRAW_ALLOCATIONS} kept", - work.device.name() - ); + (work.device.name().to_string(), frame) +} + +/// The allocations each step of `steps` of `frame` made on the encoding thread, on average. +#[cfg(not(m2v_system_alloc))] +fn allocations_each(frame: &Frame, steps: StepsOf) -> f64 { + let steps = steps(frame); + let allocations: u64 = steps.iter().map(|s| s.allocations.unwrap()).sum(); + allocations as f64 / steps.len() as f64 +} + +/// A frame's draws allocate at most [`DRAW_ALLOCATIONS`] each on average on the encoding thread, +/// once every pipeline is made: what the draw path keeps of what it found before (each texture's +/// storage view formats, the pipeline state's routing into the pass's colors, the settles of its +/// latest bind shapes and the shapes themselves, the format table) is not made again at each +/// draw, and what a draw retains, binds and records it holds and builds without allocating where +/// the object or the list allows. Its passes' ends allocate at most [`PASS_END_ALLOCATIONS`] each: +/// a pass end retains what its commands use as one object, and makes no tile grid where a draw +/// reaches every tile, no sample planes' steps in a pass without planes, and no scrub's list for a +/// texture that is not sparse. +#[cfg(not(m2v_system_alloc))] +#[test] +fn a_frame_s_draws_and_pass_ends_allocate_within_their_bounds() { + let (device, frame) = counted(); + let each = allocations_each(&frame, |f| &f.draws); + eprintln!("FRAME-COST {device}: {each:.2} allocations a draw, at most {DRAW_ALLOCATIONS} kept"); assert!( each <= DRAW_ALLOCATIONS, "{each:.2} allocations a draw, more than {DRAW_ALLOCATIONS}" ); - let allocations: u64 = frame.end.iter().map(|s| s.allocations.unwrap()).sum(); - let each = allocations as f64 / frame.end.len() as f64; + let each = allocations_each(&frame, |f| &f.end); eprintln!( - "FRAME-COST {}: {each:.2} allocations a pass end, at most {PASS_END_ALLOCATIONS} kept", - work.device.name() + "FRAME-COST {device}: {each:.2} allocations a pass end, at most {PASS_END_ALLOCATIONS} kept" ); assert!( each <= PASS_END_ALLOCATIONS, @@ -1218,6 +1242,23 @@ fn a_frame_s_passes_and_commits_begin_their_command_buffers_within_their_bound() } } +/// A frame's pass opens (`render_command_encoder`) allocate at most [`OPEN_ALLOCATIONS`] each on +/// average on the encoding thread, once every pipeline is made: an encoder takes the compatible +/// render pass the device keeps for its shape instead of making one. +#[cfg(not(m2v_system_alloc))] +#[test] +fn a_frame_s_pass_opens_allocate_within_their_bound() { + let (device, frame) = counted(); + let each = allocations_each(&frame, |f| &f.open); + eprintln!( + "FRAME-COST {device}: {each:.2} allocations a pass open, at most {OPEN_ALLOCATIONS} kept" + ); + assert!( + each <= OPEN_ALLOCATIONS, + "{each:.2} allocations a pass open, more than {OPEN_ALLOCATIONS}" + ); +} + /// A checked frame's commits allocate at most [`COMMIT_ALLOCATIONS`] each on average on the /// encoding thread, and the process's other threads at most [`SUBMIT_ALLOCATIONS`] per command /// buffer (its check, its batch's planning and submission, its completion), once every pipeline is diff --git a/crates/metal2vulkan/src/bind/state.rs b/crates/metal2vulkan/src/bind/state.rs index a95840d6f..654b08604 100644 --- a/crates/metal2vulkan/src/bind/state.rs +++ b/crates/metal2vulkan/src/bind/state.rs @@ -596,25 +596,9 @@ impl BindState { .map(|(stage, t)| (*stage, t.shape())) .filter(|(_, s)| *s != StageShape::default()) .collect(); - let mut used: BTreeMap = BTreeMap::new(); - for u in &self.used_resources { - let class = match u.class { - ResourceClass::Buffer => UsedClass::Buffer, - ResourceClass::Texture(facts) => UsedClass::Texture(facts.shape()), - ResourceClass::Heap => UsedClass::Heap, - }; - // One token names one resource; listing it twice unions its usage and stages. - let e = used.entry(u.token).or_insert(UsedShape { - class, - usage: metal::ResourceUsage::empty(), - stages: metal::RenderStages::empty(), - }); - e.usage |= u.usage; - e.stages |= u.stages; - } BindShape { stages, - used, + used: self.used_shape(), vertex_amplification: self.vertex_amplification.clone(), imageblock_size: self.imageblock_size, render_target_array_length: self.render_target_array_length, @@ -633,6 +617,78 @@ impl BindState { extended_shadows: self.extended_shadows.clone(), } } + + /// Whether `shape` is this state's shape: `self.shape() == *shape`, answered without making + /// the shape, so a consumer that keeps the shapes it made can find a state's among them + /// without allocating. Its used resources' shape alone is made where it lists any. + pub fn has_shape(&self, shape: &BindShape) -> bool { + let BindShape { + stages, + used, + vertex_amplification, + imageblock_size, + render_target_array_length, + tessellation_factor_buffer, + render_area, + argument_samplers, + function_tables, + tile_threadgroup, + viewport_compensation, + zeroed_colors, + dropped_colors, + kept_imageblock_bytes, + depth_clamp_range, + interlocked_colors, + fragment_tests, + extended_shadows, + } = shape; + let tables = self.stages.iter().filter(|(_, t)| !t.has_empty_shape()); + tables.clone().count() == stages.len() + && tables + .zip(stages) + .all(|((stage, t), (of, s))| stage == of && t.has_shape(s)) + && match self.used_resources.is_empty() { + true => used.is_empty(), + false => self.used_shape() == *used, + } + && self.vertex_amplification == *vertex_amplification + && self.imageblock_size == *imageblock_size + && self.render_target_array_length == *render_target_array_length + && self.tessellation_factors.buffer.is_some() == *tessellation_factor_buffer + && self.render_area == *render_area + && argument_samplers.is_of(&self.argument_samplers) + && FunctionTablesShape::of(&self.function_tables) == *function_tables + && self.tile_threadgroup == *tile_threadgroup + && self.viewport_compensation.map(|c| c.compensation) == *viewport_compensation + && self.zeroed_colors == *zeroed_colors + && self.dropped_colors == *dropped_colors + && self.kept_imageblock_bytes == *kept_imageblock_bytes + && self.depth_clamp_range.is_some() == *depth_clamp_range + && self.interlocked_colors == *interlocked_colors + && self.fragment_tests == *fragment_tests + && self.extended_shadows == *extended_shadows + } + + /// `used_resources` by token ([`BindShape::used`]): one token names one resource, and listing + /// it twice unions its usage and stages. + fn used_shape(&self) -> BTreeMap { + let mut used: BTreeMap = BTreeMap::new(); + for u in &self.used_resources { + let class = match u.class { + ResourceClass::Buffer => UsedClass::Buffer, + ResourceClass::Texture(facts) => UsedClass::Texture(facts.shape()), + ResourceClass::Heap => UsedClass::Heap, + }; + let e = used.entry(u.token).or_insert(UsedShape { + class, + usage: metal::ResourceUsage::empty(), + stages: metal::RenderStages::empty(), + }); + e.usage |= u.usage; + e.stages |= u.stages; + } + used + } } /// A compute encoder's imageblock size in pixels (`setImageblockWidth:height:`): a kernel's @@ -812,6 +868,31 @@ impl StageTable { threadgroup_lengths: self.threadgroup_lengths.clone(), } } + + /// Whether its shape is the empty one, which [`BindState::shape`] leaves out. + fn has_empty_shape(&self) -> bool { + self.buffers.is_empty() + && self.textures.is_empty() + && self.samplers.is_empty() + && self.threadgroup_lengths.is_empty() + } + + /// Whether `shape` is its shape ([`BindState::has_shape`]). + fn has_shape(&self, shape: &StageShape) -> bool { + let StageShape { + buffers, + textures, + samplers, + threadgroup_lengths, + } = shape; + let buffer_shapes = self.buffers.iter().map(|(i, b)| (*i, b.shape())); + let texture_shapes = self.textures.iter().map(|(i, t)| (*i, t.shape())); + let sampler_shapes = self.samplers.iter().map(|(i, s)| (*i, s.shape())); + buffer_shapes.eq(buffers.iter().map(|(i, b)| (*i, *b))) + && texture_shapes.eq(textures.iter().map(|(i, t)| (*i, *t))) + && sampler_shapes.eq(samplers.iter().map(|(i, s)| (*i, *s))) + && self.threadgroup_lengths == *threadgroup_lengths + } } impl BoundBuffer { @@ -1458,6 +1539,30 @@ impl ArgumentSamplersShape { } } + /// Whether it is the shape of `samplers` (`ArgumentSamplersShape::of(samplers) == *self`), + /// answered without making that shape for up to [`SHAPES_AT_ONCE`](Self::SHAPES_AT_ONCE) + /// samplers: each sampler's shape is among `shapes`, and each of `shapes` is some sampler's. + /// More are answered by making it. + fn is_of(&self, samplers: &[ArgumentSampler]) -> bool { + if samplers.len() > Self::SHAPES_AT_ONCE { + return Self::of(samplers) == *self; + } + let mut seen = [None; Self::SHAPES_AT_ONCE]; + for (shape, sampler) in seen.iter_mut().zip(samplers) { + *shape = Some(sampler.desc.shape()); + } + let seen = &seen[..samplers.len()]; + self.class == capacity_class(samplers.len()) + && seen + .iter() + .flatten() + .all(|shape| self.shapes.contains(shape)) + && self.shapes.iter().all(|shape| seen.contains(&Some(*shape))) + } + + /// The most samplers [`is_of`](Self::is_of) answers for without making their shape. + const SHAPES_AT_ONCE: usize = 64; + /// The entries of the class (the null entry included): `MIN_ENTRIES << class`. pub fn entries(&self) -> u64 { Self::MIN_ENTRIES << self.class diff --git a/crates/metal2vulkan/src/tests/bind_shape_of.rs b/crates/metal2vulkan/src/tests/bind_shape_of.rs new file mode 100644 index 000000000..41d6b7b87 --- /dev/null +++ b/crates/metal2vulkan/src/tests/bind_shape_of.rs @@ -0,0 +1,263 @@ +//! `BindState::has_shape` answers `state.shape() == *shape` without making the shape: over states +//! that each differ from a base in one field of the shape (and some in fields the shape leaves +//! out, or in two ways that give one shape), for every pair of them. + +use crate::bind::{ + ArgumentFunctionTable, ArgumentSampler, BindState, BoundBuffer, BoundSampler, BoundTexture, + CompensatedViewport, FragmentTests, ImageblockSize, ResourceClass, SamplerDescriptor, + StageTable, TessellationFactorBuffer, TessellationFactors, TextureFacts, + TileThreadgroupArgument, TileThreadgroupMemory, UsedResource, VertexAmplification, +}; +use crate::metal::{ + CompareFunction, PixelFormat, RenderStages, ResourceUsage, SamplerMinMagFilter, TextureType, +}; +use crate::pipeline::lower_inputs::ViewportCompensation; +use crate::pipeline::sym::Stage; + +/// A buffer of `length` bytes bound at `offset`. +fn buffer(length: u64, offset: u64) -> BoundBuffer { + BoundBuffer::Buffer { + length, + offset, + gpu_address: 0x1000, + device_address: None, + attribute_stride: None, + } +} + +/// A 2D texture of `format`. +fn texture(format: PixelFormat) -> BoundTexture { + BoundTexture::Texture { + facts: TextureFacts::new(TextureType::Type2D, format), + resource_id: Some(7), + } +} + +/// A sampler that filters linearly where `linear`, and compares where `compares`. +fn sampler(linear: bool, compares: bool) -> SamplerDescriptor { + let mut desc = SamplerDescriptor::new(); + if linear { + desc.min_filter = SamplerMinMagFilter::Linear; + desc.mag_filter = SamplerMinMagFilter::Linear; + } + if compares { + desc.compare_function = CompareFunction::Less; + } + desc +} + +/// The base: a vertex buffer, a fragment texture and sampler, and one argument sampler. +fn base() -> BindState { + let mut state = BindState::default(); + let mut vertex = StageTable::default(); + vertex.buffers.insert(0, buffer(256, 0)); + state.stages.insert(Stage::Vertex, vertex); + let mut fragment = StageTable::default(); + fragment + .textures + .insert(0, texture(PixelFormat::RGBA8Unorm)); + fragment + .samplers + .insert(0, BoundSampler::new(sampler(false, false))); + state.stages.insert(Stage::Fragment, fragment); + state + .argument_samplers + .push(ArgumentSampler::new(sampler(false, false), 1)); + state +} + +/// The base changed by `change`. +fn with(change: impl FnOnce(&mut BindState)) -> BindState { + let mut state = base(); + change(&mut state); + state +} + +/// `state`'s vertex table. +fn vertex(state: &mut BindState) -> &mut StageTable { + state.stages.get_mut(&Stage::Vertex).unwrap() +} + +/// `state`'s fragment table. +fn fragment(state: &mut BindState) -> &mut StageTable { + state.stages.get_mut(&Stage::Fragment).unwrap() +} + +/// Each state. +fn states() -> Vec { + let used = |token, usage| { + let mut used = UsedResource::new(ResourceClass::Buffer, token); + used.usage = usage; + used.stages = RenderStages::FRAGMENT; + used + }; + vec![ + BindState::default(), + base(), + // Of the base's shape: another offset of the same alignment, another length of the + // same class, an empty stage table, a per-draw value, and a function table (the tables' + // shape is their capacity and byte classes, which one small table leaves at none's). + with(|s| { + vertex(s).buffers.insert(0, buffer(255, 256)); + }), + with(|s| { + s.stages.insert(Stage::Mesh, StageTable::default()); + }), + with(|s| s.viewport_count = 4), + with(|s| { + s.function_tables.push(ArgumentFunctionTable::new(5, 4)); + }), + // A buffer of another length class, offset alignment or class, or at another slot. + with(|s| { + vertex(s).buffers.insert(0, buffer(1 << 20, 0)); + }), + with(|s| { + vertex(s).buffers.insert(0, buffer(256, 2)); + }), + with(|s| { + vertex(s).buffers.insert( + 0, + BoundBuffer::Bytes { + len: 16, + attribute_stride: None, + }, + ); + }), + with(|s| { + let moved = vertex(s).buffers.remove(&0).unwrap(); + vertex(s).buffers.insert(1, moved); + }), + with(|s| { + vertex(s).buffers.insert(1, buffer(256, 0)); + }), + with(|s| { + vertex(s).buffers.clear(); + }), + // A texture of another format, a sampler of another shape, a threadgroup length. + with(|s| { + fragment(s) + .textures + .insert(0, texture(PixelFormat::BGRA8Unorm)); + }), + with(|s| { + fragment(s) + .samplers + .insert(0, BoundSampler::new(sampler(true, false))); + }), + with(|s| { + fragment(s).threadgroup_lengths.insert(0, 64); + }), + // Used resources, a token listed twice (its usages unioned) and its union listed once. + with(|s| s.used_resources.push(used(3, ResourceUsage::READ))), + with(|s| { + s.used_resources.push(used(3, ResourceUsage::READ)); + s.used_resources.push(used(3, ResourceUsage::WRITE)); + }), + with(|s| { + s.used_resources + .push(used(3, ResourceUsage::READ | ResourceUsage::WRITE)) + }), + // Argument samplers: another of the same shape (same class), of another shape, none, + // and enough to take the next class. + with(|s| { + s.argument_samplers + .push(ArgumentSampler::new(sampler(false, false), 2)) + }), + with(|s| { + s.argument_samplers + .push(ArgumentSampler::new(sampler(false, true), 2)) + }), + with(|s| { + s.argument_samplers[0] = ArgumentSampler::new(sampler(false, true), 1); + }), + with(|s| s.argument_samplers.clear()), + with(|s| { + for id in 2..20 { + s.argument_samplers + .push(ArgumentSampler::new(sampler(false, false), id)); + } + }), + // Past the samplers answered without making their shape, the same shape and another. + with(|s| { + for id in 2..80 { + s.argument_samplers + .push(ArgumentSampler::new(sampler(false, false), id)); + } + }), + with(|s| { + for id in 2..80 { + s.argument_samplers + .push(ArgumentSampler::new(sampler(id == 79, false), id)); + } + }), + // Enough function tables to take the next class. + with(|s| { + for id in 0..16 { + s.function_tables + .push(ArgumentFunctionTable::new(5 + id, 4)); + } + }), + with(|s| s.vertex_amplification = VertexAmplification::new(2, Vec::new())), + with(|s| s.imageblock_size = ImageblockSize::new(32, 32)), + with(|s| s.render_target_array_length = 4), + with(|s| { + let buffer = TessellationFactorBuffer::new(64, 0, 0); + s.tessellation_factors = TessellationFactors::new(Some(buffer), 1.0); + }), + with(|s| s.render_area = [64, 64]), + with(|s| { + let mut memory = TileThreadgroupMemory::new(256); + memory + .arguments + .insert(0, TileThreadgroupArgument::new(64, 0)); + s.tile_threadgroup = memory; + }), + with(|s| { + s.viewport_compensation = Some(CompensatedViewport { + compensation: ViewportCompensation { + depth: true, + ..ViewportCompensation::default() + }, + ..CompensatedViewport::default() + }); + }), + with(|s| { + s.zeroed_colors.insert(1, PixelFormat::RGBA8Unorm); + }), + with(|s| { + s.dropped_colors.insert(1); + }), + with(|s| s.kept_imageblock_bytes = Some(8)), + with(|s| s.depth_clamp_range = Some([0.0, 1.0])), + with(|s| { + s.interlocked_colors.insert(1); + }), + with(|s| { + s.extended_shadows.insert(0); + }), + with(|s| s.fragment_tests = FragmentTests::Pass), + ] +} + +#[test] +fn a_state_has_exactly_the_shape_it_makes() { + let states = states(); + let shapes: Vec<_> = states.iter().map(BindState::shape).collect(); + let mut same = 0; + for (at, state) in states.iter().enumerate() { + assert!(state.has_shape(&shapes[at]), "state {at}: {state:?}"); + for (of, shape) in shapes.iter().enumerate() { + let equal = shapes[at] == *shape; + same += usize::from(equal && at != of); + assert_eq!( + state.has_shape(shape), + equal, + "state {at} against the shape of state {of}" + ); + } + } + // The states of the base's shape (the base, the four its comment names, and the base with + // another argument sampler of the same shape) and the used resources' two of one shape: each + // against the others of its shape. + assert_eq!(same, 6 * 5 + 2, "pairs of one shape"); +} diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index 5a419f477..77ba3c254 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -8,6 +8,7 @@ mod air_abi; mod air_canon; mod air_input; mod argument_buffers; +mod bind_shape_of; mod constant_blob_footprint; mod engine_absent_handles; mod engine_absent_threadgroup; diff --git a/docs/API.md b/docs/API.md index 28c0afe01..da7982e72 100644 --- a/docs/API.md +++ b/docs/API.md @@ -405,7 +405,9 @@ assert!(plan.variant.is_empty(), "this shape needs no other variant"); `state.shape()` keeps only what can change a plan (which slots are bound with what kind of resource, formats, level counts, sampler modes, alignment classes). A plan is a pure function of the -pipeline, the device and the shape: memoize it on `(PipelineKey, BindShape)`. +pipeline, the device and the shape: memoize it on `(PipelineKey, BindShape)`. A consumer that keeps +the shapes it planned can find a state's among them without making it: `state.has_shape(&shape)` +answers `state.shape() == shape`, compared in place. The plan holds one `DescriptorWrite` per layout binding element (the resource at a slot, a buffer the binder synthesizes, or a neutral resource where nothing compatible is bound), the vertex