diff --git a/crates/metal2vulkan-runtime/src/binding.rs b/crates/metal2vulkan-runtime/src/binding.rs index ee08571ea..3ac1c7d92 100644 --- a/crates/metal2vulkan-runtime/src/binding.rs +++ b/crates/metal2vulkan-runtime/src/binding.rs @@ -3147,6 +3147,27 @@ impl CommandUses { pub(super) fn resident(&self) -> &BTreeSet { &self.resident } + + /// Of its uses that [`patch_buffer_uses`] patched for the buffer slots `changed` (those of + /// its list of uses of buffer slots, `CommandUses::slots`), the positions into `at` and the + /// uses into `uses`, both emptied first, in the list's order: every use a call that changed + /// those slots changed. Call it after a patch that patched them. + pub(super) fn slot_uses_into( + &self, + changed: &[SlotRef], + (at, uses): (&mut Vec, &mut Vec>), + ) { + debug_assert!(self.slots_listed, "a command's patched uses read unlisted"); + at.clear(); + uses.clear(); + for &(slot, place) in &self.slots { + if changed.contains(&slot) { + let place = place as usize; + at.push(place); + uses.push(self.uses[place].clone()); + } + } + } } impl Deref for CommandUses { diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index d6519f484..51560a9e0 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -3138,6 +3138,36 @@ impl Device { Ok(()) } + /// [`degrade_attachment_reads`](Self::degrade_attachment_reads) of a draw whose `uses` differ + /// from those of the last draw of its encoder, drawn against the same attachments, only in + /// `moved` (a draw moved: `render/draw_again/rebound.rs`): of those alone, as each other use + /// is that draw's, which the check found sharing none while it ran (checked in builds with + /// debug assertions). + pub(super) fn degrade_moved_attachment_reads( + &self, + call: &'static str, + mut shares: impl FnMut(&[Use]) -> Result, + (moved, uses): (&[Use], &[Use]), + ) -> Result<(), Error> { + let kind = Degradation::AttachmentReadInPlace; + if !self.shared().announced.pending(kind) { + return Ok(()); + } + let shared = shares(moved)?; + #[cfg(debug_assertions)] + assert_eq!( + shared, + shares(uses)?, + "a draw moved's uses but the moved ones share memory with an attachment" + ); + #[cfg(not(debug_assertions))] + let _ = uses; + if shared { + self.degrade(kind, || attachment_read_notice(call)); + } + Ok(()) + } + /// [`degrade_attachment_reads`](Self::degrade_attachment_reads) of a draw whose `uses` begin /// with those of what its encoder made resident of the identity `prefix`: of those, the uses /// past them alone where they were found to share none with a layout of `version` diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index d74d374e3..b2d9fd912 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -1654,6 +1654,53 @@ impl EncoderCore { Ok(()) } + /// [`note_reaching`](Self::note_reaching) a draw with `uses`, of which it reaches the keys + /// `resident` through the resident set alone, whose uses differ from those of the last + /// command `noted` keeps only at the positions `at`, each of the same key and access types + /// there (a draw whose calls moved buffer offsets alone: `render/draw_again/rebound.rs`): + /// where the last command was noted into the encoder's state now, with as many uses + /// (`NotedApart::moves`), only those of the uses at `at` that differ are compared and + /// recorded, with the host aliases' uses beside them, as `note_reaching` records the uses that + /// differ; and none is touched, each key being the one the last command touched at its + /// position. Whether it noted the draw; else it noted nothing, and the caller notes it as + /// `note_reaching` does. + pub(super) fn note_moved( + &mut self, + (uses, resident, at): (&[Use], &BTreeSet, &[usize]), + noted: &mut NotedApart, + ) -> Result { + if self.uses.ordered() { + return Err(super::error::internal( + "a command recorded apart in an ordered encoder", + )); + } + // Read before the host aliases' uses are worked out, so a change made since counts. + let into = self.noted_into(); + if !noted.moves((uses, resident), into) { + return Ok(false); + } + self.observe_fresh(uses, &[]); + self.hold_resident(); + let record = |stages, fresh: &[Use]| self.record_aliased(stages, fresh); + if noted.note_moved((uses, resident), at, record).is_none() { + self.counts().command_noted_as_before(); + } + // Touched already: each key at its position, named as touching it names it. + #[cfg(debug_assertions)] + { + let rebinds = self.device().shared().rebinds.any(); + for (place, used) in uses.iter().enumerate() { + let named = rebinds && !resident.contains(&used.key); + assert!( + self.touched.get(place) == Some(&(used.key, named)), + "a draw noted moved touches a key its last command did not touch there" + ); + } + assert_eq!(self.touched.len(), uses.len()); + } + Ok(true) + } + /// The encoder's state a command noted apart now is noted into (`NotedInto`). pub(super) fn noted_into(&self) -> NotedInto { let shared = self.device().shared(); diff --git a/crates/metal2vulkan-runtime/src/live_bind.rs b/crates/metal2vulkan-runtime/src/live_bind.rs index 093a36a8f..e17409367 100644 --- a/crates/metal2vulkan-runtime/src/live_bind.rs +++ b/crates/metal2vulkan-runtime/src/live_bind.rs @@ -377,6 +377,12 @@ impl ReadFrom { self.moved == moved && self.through(interface) && self.maps == *maps } + /// Whether the tables were read through `interface` at `moved` moves, with the maps they were + /// read with: [`reads`](Self::reads) of its own maps, which it compares with none. + pub(super) fn reads_through(&self, interface: &PipelineInterface, moved: u64) -> bool { + self.moved == moved && self.through(interface) + } + /// The maps the tables were read with. pub(super) fn maps(&self) -> &SamplerMaps { &self.maps @@ -437,6 +443,26 @@ impl ReadFrom { self.tables = stamps.map(Some); self.moved = moved; } + + /// [`read`](Self::read) with the maps the tables were read with, which it neither compares + /// nor copies: the tables of `stamps` read now through `interface` (of the drawing state + /// `state` gives) at `moved` moves. + pub(super) fn read_again( + &mut self, + stamps: [Stamp; 4], + (interface, state): ( + &PipelineInterface, + impl FnOnce() -> Arc, + ), + moved: u64, + ) { + if !self.through(interface) { + let at = std::ptr::from_ref(interface).addr(); + self.interface = Some((at, Arc::downgrade(&state()))); + } + self.tables = stamps.map(Some); + self.moved = moved; + } } impl LiveBind { diff --git a/crates/metal2vulkan-runtime/src/noted_apart.rs b/crates/metal2vulkan-runtime/src/noted_apart.rs index 11b7226da..61aa00e16 100644 --- a/crates/metal2vulkan-runtime/src/noted_apart.rs +++ b/crates/metal2vulkan-runtime/src/noted_apart.rs @@ -181,6 +181,76 @@ impl NotedApart { holds } + /// Whether a command with `uses`, of which it reaches the keys `resident` through the + /// resident set alone, noted into `into`, may be noted as the last one moved + /// ([`note_moved`](Self::note_moved)): the last one was noted into `into`, with no uses of + /// what its encoder made resident, as many uses and the same keys reached so. Its caller + /// knows the positions where its uses may differ from the last one's, each of the same key + /// and access types (a draw whose calls moved buffer offsets alone: + /// `render/draw_again/rebound.rs`). + pub(super) fn moves( + &self, + (uses, resident): (&[Use], &BTreeSet), + into: NotedInto, + ) -> bool { + self.core == Some(into.core) + && self.into() == into + && self.prefix.is_none() + && self.uses.len() == uses.len() + && self.resident.iter().eq(resident) + } + + /// Note the command [`moves`](Self::moves) answers for, whose `uses` (reaching the keys + /// `resident` through the resident set alone) differ from the last one's at the positions + /// `at` alone: `record` records those of them that differ, which the encoder's current part + /// may lack (the module docs), and they are kept in place. What `record` answers; `None` + /// where none differs, the command noted already. Its stages are the last one's, its uses' + /// access types being theirs. + pub(super) fn note_moved( + &mut self, + (uses, resident): (&[Use], &BTreeSet), + at: &[usize], + record: impl FnOnce(vk::PipelineStageFlags2, &[Use]) -> T, + ) -> Option { + self.fresh.clear(); + self.fresh_at.clear(); + for &at in at { + if self.uses[at] != uses[at] { + self.fresh.push(uses[at].clone()); + self.fresh_at.push(at); + } + } + #[cfg(debug_assertions)] + { + let moved = |place: &usize| at.contains(place); + let kept = self.uses.iter().enumerate().zip(uses); + assert!( + kept.filter(|((place, _), _)| !moved(place)) + .all(|((_, kept), used)| kept == used), + "a command noted moved differs from the last one where it did not move" + ); + let stages = (uses.iter()).fold(vk::PipelineStageFlags2::empty(), |all, used| { + all | used.read.stages | used.write.stages + }); + assert!( + stages == self.stages, + "a command noted moved runs in other stages than the last one" + ); + } + if self.fresh.is_empty() { + return None; + } + let answer = record(self.stages, &self.fresh); + for (&at, used) in self.fresh_at.iter().zip(&self.fresh) { + self.uses[at].clone_from(used); + } + #[cfg(debug_assertions)] + self.note_whole((uses, resident)); + #[cfg(not(debug_assertions))] + let _ = resident; + Some(answer) + } + /// Whether the last command was noted into `into`: then a command noted with its stages and /// uses, reaching the same keys through the resident set alone, is noted already /// ([`holds`](Self::holds)). diff --git a/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs b/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs index 5e3c18323..eada1771a 100644 --- a/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs +++ b/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs @@ -31,8 +31,12 @@ //! attachments' reads' refusal is answered here, the last of its checks, which may have //! announced. //! - **What it records and notes.** Its uses noted as any draw notes them (`note_reaching`, the -//! unordered writes, the pass's reads, the instance's gathered uses, indirect reads and geometry -//! writes); the state commands that changed and its draw, recorded through the kept draw's +//! pass's reads, the instance's gathered uses), of the kept draw's access types: none writes or +//! reads indirect arguments (`draw_again::unwritten`), so the unordered writes, indirect reads and +//! geometry writes take none of them, and in a pass whose fragments wrote nothing the pass's +//! reads announce nothing of them; only uses that begin with those of what the encoder made +//! resident are walked there, as those trackers take them by their identity. The state commands +//! that changed and its draw, recorded through the kept draw's //! recording against what its command buffer holds (`render/bound.rs`), which compares none of //! the dynamic states a value there holds where nothing recorded through the record since the //! kept draw, or the draw rebound before, set them (`Kept::settled`): it holds them, of the @@ -40,13 +44,29 @@ //! and its new samplers retained; and the rest as a draw again: kept for recording again (but //! where it met a notice met at each occurrence, as its every step forgets it then), its //! execution record, its counts into its encoder's tally of the device's (`shards.rs`). +//! - **A draw moved.** Where every call since the kept draw moved a buffer slot's offset (or +//! attribute stride) alone, the slot binding the buffer it bound (`argument_table::Changed`), the +//! draw is moved (`WorkCounts::draws_moved`): its tables bind the kept draw's objects, so it +//! looks at no stage's function tables, shadowed texture or detached buffer again; and where its +//! commands' descriptor ranges are the kept draw's, it keeps the kept draw's set-0 writes and +//! dynamic offsets (`binding::rebind_into` writes a buffer's descriptor of its buffer and range +//! alone). One whose uses were patched in place, none of them of what the encoder made resident, +//! is narrowed: its uses differ from the kept draw's only at the moved slots' uses +//! (`CommandUses::slot_uses_into`), which alone it checks against the attachments and the +//! geometry writes, adds to the pass's reads and gathers (`InstanceShadows::add_moved`), and +//! compares and records where the last command noted is the kept draw (`EncoderCore::note_moved`). //! - **Checked in builds with debug assertions.** As a draw again is: the first rebound draw of a //! kept draw and every second after it work out the rebind, then take every step instead, which //! must keep the draw, with the same commands, set-0 writes, dynamic offsets, push bytes, vertex -//! buffers and uses. +//! buffers and uses. What a draw moved skips is asserted where it skips it: its function tables +//! pass, it meets no shadow and no detached buffer, it pushes the kept draw's set-0 writes, its +//! uses are unwritten in a pass whose fragments wrote nothing, and of a draw narrowed, its other +//! uses share no attachment memory, meet no geometry write the moved ones do not, add nothing to +//! the pass's reads, are noted and touched as the last command's, and are the instance's last +//! gathered uses. use ash::vk; -use metal2vulkan::bind::DrawCall; +use metal2vulkan::bind::{DescriptorRange, DrawCall}; use metal2vulkan::pipeline::{SlotClass, SlotRef, Stage}; use std::sync::Arc; @@ -58,7 +78,9 @@ use crate::error::Error; use crate::live_bind::{LiveBind, Reshape}; use crate::pipeline::{RenderStateKind, Settled}; use crate::render::{Assembly, Bound, DrawBuffers, DrawState, Recording}; +use crate::resource::ResourceKey; use crate::texture::Texture; +use crate::tracker::Use; /// The most slots a draw rebound takes changed: a draw after more takes every step. const SLOTS: usize = 8; @@ -78,6 +100,11 @@ pub(crate) struct KeptStorage { unheld: Vec, /// The rest of its recording. recording: Option, + /// A draw moved's storage, kept likewise: its commands' descriptor ranges before it worked + /// them out, and the positions and uses of the moved slots' uses (the module docs). + ranges: Vec, + moved_at: Vec, + moved: Vec>, } /// A kept draw's recording but for what a draw rebound works out again (its set, dynamic @@ -130,8 +157,9 @@ fn settles_kept(encoder: &RenderLowering, live: &LiveBind) -> bool { } /// The buffer, texture and sampler slots calls changed since the kept draw read its tables: at -/// most [`SLOTS`]; and of the vertex stage's buffer slots below 64, those every one of those -/// calls changed by the offset alone, a bit each. +/// most [`SLOTS`]; of the vertex stage's buffer slots below 64, those every one of those calls +/// changed by the offset alone, a bit each; and whether every one of those calls moved a buffer +/// slot's offset alone. struct Changed { slots: [SlotRef; SLOTS], count: usize, @@ -139,6 +167,9 @@ struct Changed { /// otherwise. offsets: u64, whole: u64, + /// Whether every call moved the offset of a buffer slot alone, keeping the buffer bound there + /// (`argument_table::Changed::offset`): the draw is moved (the module docs). + moved: bool, } impl Changed { @@ -154,11 +185,13 @@ impl Changed { count: 0, offsets: 0, whole: 0, + moved: true, } } /// Note a call's change of `slot`, by its offset alone where `offset` (a buffer slot's). fn note(&mut self, slot: SlotRef, offset: bool) { + self.moved &= offset && slot.class == SlotClass::Buffer; if slot.stage != Stage::Vertex || slot.class != SlotClass::Buffer { return; } @@ -201,6 +234,18 @@ impl Changed { } } +/// What a draw rebound worked out of its rebinding (`RenderLowering::rebind`): whether it is moved +/// ([`Changed::moved`]), whether its set-0 writes and dynamic offsets are then the kept draw's +/// (its descriptor ranges are), and whether its uses differ from the kept draw's only at the +/// moved slots' uses, listed in its bind state's kept storage (`KeptStorage::moved`): the draw is +/// narrowed (the module docs). +#[derive(Clone, Copy)] +struct Rebinding { + moved: bool, + writes_kept: bool, + narrowed: bool, +} + impl RenderLowering { /// The kept draw again after calls that bound other buffers, offsets, textures or samplers in /// its tables, whose stamps are now `stamps` (the module docs): recorded, refused, or @@ -221,9 +266,9 @@ impl RenderLowering { let Some(changed) = self.bring_in(live, stamps) else { return Again::No; }; - if !self.rebind(call, live, &changed, (draw, buffers)) { + let Some(rebinding) = self.rebind(call, live, &changed, (draw, buffers)) else { return Again::No; - } + }; #[cfg(debug_assertions)] { let hits = self.again.hits; @@ -242,9 +287,15 @@ impl RenderLowering { let version = self.layout.version(); let (memo, layout) = (&mut self.attached, &*self.layout); let mut shares = |uses: &[_]| memo.shares((layout, version), uses); - let attached = match live.uses.prefix() { - None => device.degrade_attachment_reads(call, shares, &live.uses), - Some(prefix) => { + // Of a draw narrowed, the moved slots' uses alone: every other use is the kept draw's, + // whose check found them sharing none (it was drawn), against the same attachments. + let attached = match (rebinding.narrowed, live.uses.prefix()) { + (true, _) => { + let moved = (&live.kept.moved[..], &live.uses[..]); + device.degrade_moved_attachment_reads(call, shares, moved) + } + (false, None) => device.degrade_attachment_reads(call, shares, &live.uses), + (false, Some(prefix)) => { let shares = (&mut shares, Some(version)); device.degrade_resident_attachment_reads(call, shares, (&mut live.uses, prefix)) } @@ -253,7 +304,8 @@ impl RenderLowering { return Again::Refused(refused); } let counted = (stamps, changed.images()); - let recorded = self.record_rebound(live, (call, assembly, draw), buffers, counted); + let recorded = + self.record_rebound(live, (call, assembly, draw), buffers, (counted, rebinding)); if let Err(refused) = recorded { return Again::Refused(refused); } @@ -276,8 +328,9 @@ impl RenderLowering { let interface = &pipeline.base().interface; let views = pipeline.at_bind_views(); let moved = crate::buffer::host_cells_moved(); - let maps = live.read_from.maps().clone(); - if !live.read_from.reads(interface, &maps, moved) { + // Read with the maps they were read with, which only a changed texture or sampler may + // change (below). + if !live.read_from.reads_through(interface, moved) { return None; } let tables = [&self.vertex, &self.fragment, &self.object, &self.mesh]; @@ -328,7 +381,7 @@ impl RenderLowering { ]; let layout = &pipeline.base().layout; let now = crate::address_map::sampler_maps(layout, &stages, Some(&self.residency)); - if now.ok()? != maps { + if now.ok()? != *live.read_from.maps() { return None; } } @@ -341,15 +394,16 @@ impl RenderLowering { if stamps[at] == under { continue; } + let maps = live.read_from.maps(); let from = (live.state.stages.entry(stage).or_default(), under); - if !table.refresh_changed(from, (stage, interface), (&maps, views), &mut reshape) { + if !table.refresh_changed(from, (stage, interface), (maps, views), &mut reshape) { live.reshaped(reshape); return None; } read += 1; } live.read_from - .read(stamps, (interface, || pipeline.held()), &maps, moved); + .read_again(stamps, (interface, || pipeline.held()), moved); // Read now, whatever the draw does next: a draw that takes every step from here finds // them read, as the draw rebound does. self.core.counts().tables_read_in_part(read); @@ -360,46 +414,61 @@ impl RenderLowering { /// Work out again in `live` what the slots `changed` decide of the kept draw, `draw` of /// `buffers`: its commands, set-0 writes and dynamic offsets, push bytes, vertex buffers and - /// uses, with the checks a draw's steps take of them (the module docs). Whether it did; else - /// the draw takes every step, which writes them all again. + /// uses, with the checks a draw's steps take of them (the module docs). What it worked out + /// where it did ([`Rebinding`]); else `None`, and the draw takes every step, which writes them + /// all again. fn rebind( &mut self, call: &'static str, live: &mut LiveBind, changed: &Changed, (draw, buffers): (&DrawCall, &DrawBuffers<'_>), - ) -> bool { + ) -> Option { let kept = settles_kept(self, live) .then_some(live.settled.as_ref()) .flatten(); - let Some(Settled { + let Settled { variant, plan, facts, .. - }) = kept.map(|here| here.settled()) - else { - return false; - }; + } = kept?.settled(); let slots = changed.list(); + // A draw moved: its commands' descriptor ranges as the kept draw left them, which tell + // whether its set-0 writes are the kept draw's (below). + let moved = changed.moved; + if moved { + live.kept.ranges.clear(); + (live.kept.ranges).extend_from_slice(&live.commands.descriptor_ranges); + } if plan.rebind_draw_slots_into(&live.state, slots, &mut live.commands) != Ok(true) { - return false; + return None; } let compiled = variant.pipeline(); let interface = &compiled.interface; + // A moved offset binds the buffer the kept draw bound there, never a visible-function + // table (`argument_table::Changed::offset`): the tables' function tables are those the + // kept draw's checks passed. + let tables_checked = || { + (self.vertex) + .check_function_tables(call, Stage::Vertex, interface) + .is_ok() + && (self.fragment) + .check_function_tables(call, Stage::Fragment, interface) + .is_ok() + }; + debug_assert!( + !moved || tables_checked(), + "a draw moved binds a function table its kept draw's checks did not pass" + ); let checked = self .check_vertex_reach(&compiled.vertex_input.pulled, draw) .is_ok() - && (self.vertex) - .check_function_tables(call, Stage::Vertex, interface) - .is_ok() - && (self.fragment) - .check_function_tables(call, Stage::Fragment, interface) - .is_ok(); + && (moved || tables_checked()); // The pass's fragment writes, a copy of which a stage before the fragments may read // (`render/pass_start_reads.rs`): none, so each stage reads its encoder's table. if !checked || self.pass_start.fragments_wrote() { - return false; + return None; } // A changed texture: none its plan samples or writes is a color attachment's (a draw // that reads one reads its copy, or a snapshot, or records apart), and no extended-range @@ -410,7 +479,7 @@ impl RenderLowering { || self.storage_colors(facts) != 0 || !live.state.extended_shadows.is_empty()) { - return false; + return None; } let stages = [ (Stage::Vertex, &self.vertex), @@ -441,20 +510,27 @@ impl RenderLowering { mesh: None, tessellation: None, }; + // Set 0's writes and dynamic offsets: a draw moved whose descriptor ranges are the kept + // draw's binds the same buffers over the same ranges (`binding::rebind_into` writes a + // buffer's descriptor of its buffer and range alone), so it keeps them. + let writes_kept = moved && commands.descriptor_ranges == live.kept.ranges; let objects = variant.objects(); - let rebound = { - let device = self.core.device(); - let writes = &mut live.kept.writes[..]; - let set_zero = (writes, objects.dynamic_bindings(), &mut live.offsets[..]); - let samplers = (Some(&mut self.bind_memo), &mut live.samplers); - binding::rebind_into( - call, - device, - (&**plan, &command, &tables), - slots, - set_zero, - samplers, - ) + let rebound = match writes_kept { + true => Ok(true), + false => { + let device = self.core.device(); + let writes = &mut live.kept.writes[..]; + let set_zero = (writes, objects.dynamic_bindings(), &mut live.offsets[..]); + let samplers = (Some(&mut self.bind_memo), &mut live.samplers); + binding::rebind_into( + call, + device, + (&**plan, &command, &tables), + slots, + set_zero, + samplers, + ) + } }; let index = buffers.index.as_ref().map(DrawSource::metal); let uses = (plan, &command, &tables); @@ -469,7 +545,7 @@ impl RenderLowering { || binding::command_uses_into(call, uses, (index, None), &mut live.uses).is_ok()) && binding::push_writes_into(&commands.push_constants, &[], &mut live.pushes).is_ok(); if !rebound { - return false; + return None; } let made = live.uses.made() as u64; if !patched { @@ -479,13 +555,21 @@ impl RenderLowering { } counts.resident_keys_settled(live.uses.settled() as u64); } + // A draw moved whose uses were patched, none of them of what the encoder made resident + // (whose trackers take them by their identity): the moved slots' uses, every use that + // differs from the kept draw's, each of the kept use's key and access types. + let narrowed = moved && patched && live.uses.prefix().is_none(); + if narrowed { + let moved = (&mut live.kept.moved_at, &mut live.kept.moved); + live.uses.slot_uses_into(slots, moved); + } // Its fixed-function vertex buffers at the changed slots, in the plan's order. A slot // whose offset alone moved binds the buffer the kept draw bound there, whose space starts // where it did, as no no-copy buffer moved since (`bring_in`): it is not looked at again // (`LiveBind::vertex_starts`). let kept = (live.vertex_buffers.iter_mut()).zip(&mut live.vertex_starts); if plan.vertex_buffers.len() != kept.len() { - return false; + return None; } for (bind, (at, kept_start)) in plan.vertex_buffers.iter().zip(kept) { let slot = SlotRef { @@ -506,37 +590,66 @@ impl RenderLowering { (true, Some(_), _) => (at.1, *kept_start), (_, Some((buffer, _)), _) => buffer.space(), (_, None, Some(bytes)) => (bytes.region.raw(), bytes.region.offset()), - (_, None, None) => return false, + (_, None, None) => return None, }; let (Some(&(_, offset)), (raw, start)) = (offset, space) else { - return false; + return None; }; at.1 = raw; at.2 = start + offset; *kept_start = start; } - // No shadowed texture among its uses, and no barrier its fragments need after an earlier - // draw's geometry writes. - let textures = (self.vertex.textures.values()) - .chain(self.fragment.textures.values()) - .chain(self.object.textures.values()) - .chain(self.mesh.textures.values()) - .chain(self.residency.textures()); - // Nor a detached buffer, a draw of which records nothing (`EncoderCore::skips`). + // No shadowed texture among its uses, no barrier its fragments need after an earlier + // draw's geometry writes, nor a detached buffer, a draw of which records nothing + // (`EncoderCore::skips`). A draw moved binds the kept draw's textures, and its uses name + // the kept draw's keys, which met no shadow and no detached buffer, as no no-copy buffer + // moved since (`Under`): it looks at neither again. Of a draw narrowed, only the moved + // slots' uses meet the geometry writes anew: every other use is the kept draw's, which + // met none of them, and no draw added any since. let uses = &live.uses; - let named = (uses.iter().map(|used| used.key)).filter(|key| !uses.resident().contains(key)); + let textures = || { + (self.vertex.textures.values()) + .chain(self.fragment.textures.values()) + .chain(self.object.textures.values()) + .chain(self.mesh.textures.values()) + .chain(self.residency.textures()) + }; + let named = + || (uses.iter().map(|used| used.key)).filter(|key| !uses.resident().contains(key)); + debug_assert!( + !moved + || crate::shadow::shadow_uses(textures(), uses).is_empty() + && !self.core.would_skip(named()), + "a draw moved met a shadow or a detached buffer its kept draw did not" + ); + if !moved && !crate::shadow::shadow_uses(textures(), uses).is_empty() { + return None; + } let counts = self.core.counts(); - crate::shadow::shadow_uses(textures, uses).is_empty() - && match uses.prefix() { - None => self.current.geometry_writes.barrier_before(uses).is_none(), - Some(prefix) => { - let (barrier, walked) = - (self.current.geometry_writes).barrier_before_draw((uses, prefix)); - counts.resident_uses_geometry_checked(walked as u64); - barrier.is_none() - } + let unbarriered = match (narrowed, uses.prefix()) { + (true, _) => { + let writes = &self.current.geometry_writes; + let unbarriered = writes.barrier_before(&live.kept.moved).is_none(); + debug_assert!( + unbarriered == writes.barrier_before(uses).is_none(), + "a draw narrowed's other uses meet a geometry write" + ); + unbarriered } - && !self.core.would_skip(named) + (false, None) => self.current.geometry_writes.barrier_before(uses).is_none(), + (false, Some(prefix)) => { + let (barrier, walked) = + (self.current.geometry_writes).barrier_before_draw((uses, prefix)); + counts.resident_uses_geometry_checked(walked as u64); + barrier.is_none() + } + }; + let rebinding = Rebinding { + moved, + writes_kept, + narrowed, + }; + (unbarriered && (moved || !self.core.would_skip(named()))).then_some(rebinding) } /// Record the draw rebound in `live` (the module docs): its set 0, its uses noted, its state @@ -546,28 +659,61 @@ impl RenderLowering { live: &mut LiveBind, (call, assembly, draw): (&'static str, Assembly, &DrawCall), buffers: &DrawBuffers<'_>, - (stamps, images): ([Stamp; 4], bool), + ((stamps, images), rebinding): (([Stamp; 4], bool), Rebinding), ) -> Result<(), Error> { let kept = settles_kept(self, live) .then_some(live.settled.as_ref()) .flatten(); let unsettled = || crate::error::internal("a draw rebound unsettled"); let objects = kept.ok_or_else(unsettled)?.settled().variant.objects(); - let (set, written) = match objects.pushes_set_zero() { - true => { + let narrowed = rebinding.narrowed; + let (set, written) = match (objects.pushes_set_zero(), rebinding.writes_kept) { + // Its set-0 writes the kept draw's (`rebind`): it pushes what the kept draw pushed. + (true, true) => { + #[cfg(debug_assertions)] + { + let pushed = SetWrite::pushed(&live.kept.writes, objects.immutable_pushes()); + let same = (pushed.iter().zip(&live.pushed)).all(|(a, b)| a.same(b)); + assert!( + same && pushed.len() == live.pushed.len(), + "a draw moved pushes other writes than its kept draw" + ); + } + (None, None) + } + (true, false) => { let immutable = objects.immutable_pushes(); SetWrite::push_into(&live.kept.writes, immutable, &mut live.pushed); (None, None) } - false => self.core.set_zero_of(objects, &mut live.kept.writes)?, + (false, _) => self.core.set_zero_of(objects, &mut live.kept.writes)?, }; let pushed: &[SetWrite] = match objects.pushes_set_zero() { true => &live.pushed, false => &[], }; let uses = &live.uses; - match uses.reaching_prefix() { - None => { + let prefix = uses.prefix(); + // Its uses are of the kept draw's access types, its plan's: none writes or reads + // indirect arguments (`draw_again::unwritten`), so none is an unordered write, an + // indirect read or a geometry write, and in a pass whose fragments wrote nothing + // (`rebind`) none meets what the pass's reads announce. Their noting adds them alone. + debug_assert!( + super::unwritten(uses).0 && !self.pass_start.fragments_wrote(), + "a draw rebound writes, or follows a fragment write of its pass" + ); + // Noted: a draw narrowed's moved slots' uses alone where the last command noted is the + // kept draw (`EncoderCore::note_moved`), else the uses as any draw notes them. + let noted = match narrowed { + true => { + let moved = (&**uses, uses.resident(), &live.kept.moved_at[..]); + (self.core).note_moved(moved, &mut live.noted)? + } + false => false, + }; + match (noted, uses.reaching_prefix()) { + (true, _) => {} + (false, None) => { let stages = (uses.iter()).fold(vk::PipelineStageFlags2::empty(), |all, used| { all | used.read.stages | used.write.stages }); @@ -577,50 +723,57 @@ impl RenderLowering { Some(&mut live.noted), )?; } - Some(prefix) => { + (false, Some(prefix)) => { let reaching = (&**uses, uses.resident(), prefix); (self.core).note_draw(reaching, &mut live.noted)?; } } - let resident = uses.prefix().map_or(0, |prefix| prefix.len as u64); - let prefix = uses.prefix(); - match prefix { - None => self.unordered.add(uses), - Some(prefix) => { - if self.unordered.add_draw((uses, prefix)) { - self.core.counts().resident_uses_unordered_writes(resident); + let resident = prefix.map_or(0, |prefix| prefix.len as u64); + if let Some(prefix) = prefix { + if self.unordered.add_draw((uses, prefix)) { + self.core.counts().resident_uses_unordered_writes(resident); + } + } + // The pass's reads, and the instance's gathered uses: of a draw narrowed, the moved slots' + // uses alone, every other use being the kept draw's, which they hold. + match (narrowed, prefix) { + (true, _) => { + self.pass_start.add(&live.kept.moved); + #[cfg(debug_assertions)] + { + let held = super::digest(self.pass_start.held()); + self.pass_start.add(uses); + assert!( + held == super::digest(self.pass_start.held()), + "a draw narrowed's other uses add to the pass's reads" + ); } } - } - match prefix { - None => { - self.pass_start.announce(self.core.device(), uses, false); - self.pass_start.add(uses); + (false, None) => self.pass_start.add(uses), + (false, Some(prefix)) => { + (self.pass_start).draw(self.core.device(), (uses, prefix), false); } - Some(prefix) => (self.pass_start).draw(self.core.device(), (uses, prefix), false), } - match prefix { - None => self.gathering().add(&[], uses), - Some(prefix) => { + match (narrowed, prefix) { + (true, _) => { + let gathering = self.gathering(); + if !gathering.add_moved(uses, &live.kept.moved_at) { + gathering.add(&[], uses); + } + } + (false, None) => self.gathering().add(&[], uses), + (false, Some(prefix)) => { if self.gathering().add_draw(&[], (uses, prefix)) { self.core.counts().resident_uses_gathered(prefix.len as u64); } } } - match prefix { - None => self.current.indirect_reads.add(uses), - Some(prefix) => { - if self.current.indirect_reads.add_draw((uses, prefix)) { - self.core.counts().resident_uses_indirect_reads(resident); - } + if let Some(prefix) = prefix { + if self.current.indirect_reads.add_draw((uses, prefix)) { + self.core.counts().resident_uses_indirect_reads(resident); } - } - match prefix { - None => self.current.geometry_writes.add(uses), - Some(prefix) => { - if self.current.geometry_writes.add_draw((uses, prefix)) { - self.core.counts().resident_uses_geometry_writes(resident); - } + if self.current.geometry_writes.add_draw((uses, prefix)) { + self.core.counts().resident_uses_geometry_writes(resident); } } let owned = (live.kept.recording.as_ref()) @@ -679,6 +832,9 @@ impl RenderLowering { let counts = self.core.counts(); let pushed = (recorded.states, recorded.writes_pushed); counts.draw_rebound((kept.pushes_set_zero, kept.last_vertex), pushed); + if rebinding.moved { + counts.draw_moved(); + } recorded.count_equal_shapes(counts); self.current.recorded = true; let again = kept.again; diff --git a/crates/metal2vulkan-runtime/src/render/pass_start_reads.rs b/crates/metal2vulkan-runtime/src/render/pass_start_reads.rs index 714ca5f6c..e2f44001d 100644 --- a/crates/metal2vulkan-runtime/src/render/pass_start_reads.rs +++ b/crates/metal2vulkan-runtime/src/render/pass_start_reads.rs @@ -562,12 +562,20 @@ impl PassStartReads { /// pass's earlier instances (`compute_after`), as the draw's dispatches before its own /// instance do (`render.rs`). pub(super) fn announce(&self, device: &Device, uses: &[Use], compute_after: bool) { - let in_place = uses.iter().find_map(|used| self.in_place(used)); + let in_place = match self.fragment.is_empty() { + true => None, + false => uses.iter().find_map(|used| self.in_place(used)), + }; if let Some(range) = in_place { device.degrade(Degradation::InPlaceVertexReads, || in_place_notice(range)); } - let stages = (Self::readers(compute_after), Self::writers(compute_after)); - let ordered = uses.iter().find_map(|used| self.ordered(used, stages)); + let ordered = match self.orders_nothing() { + true => None, + false => { + let stages = (Self::readers(compute_after), Self::writers(compute_after)); + uses.iter().find_map(|used| self.ordered(used, stages)) + } + }; if let Some(ordered) = ordered { device.degrade(Degradation::FragmentsBeforeGeometry, || { ordered_notice(ordered) @@ -676,8 +684,14 @@ impl PassStartReads { /// The first of `uses` each kind [`announce`](Self::announce) announces meets ([`Found`]). fn found(&self, uses: &[Use], compute_after: bool) -> Found { - let in_place = (uses.iter().enumerate()) - .find_map(|(at, used)| self.in_place(used).map(|range| (at, range.clone()))); + let in_place = match self.fragment.is_empty() { + true => None, + false => (uses.iter().enumerate()) + .find_map(|(at, used)| self.in_place(used).map(|range| (at, range.clone()))), + }; + if self.orders_nothing() { + return (in_place, None); + } let stages = (Self::readers(compute_after), Self::writers(compute_after)); let ordered = uses.iter().enumerate().find_map(|(at, used)| { let (range, access, fragments) = self.ordered(used, stages)?; @@ -686,6 +700,14 @@ impl PassStartReads { (in_place, ordered) } + /// Whether no fragment stage of the pass read or wrote bytes so far: then no access of a + /// draw's stages before its fragments is one the device may order apart from Metal + /// ([`ordered`](Self::ordered) meets nothing). [`in_place`](Self::in_place) meets nothing + /// once no fragment stage wrote. + fn orders_nothing(&self) -> bool { + self.fragment.is_empty() && self.fragment_reads.is_empty() + } + /// The stages whose reads of bytes a fragment stage of the pass wrote count: a native object /// or mesh stage's, and an emulated one's where its work records after the pass's earlier /// instances (`compute_after`). diff --git a/crates/metal2vulkan-runtime/src/render/shadows.rs b/crates/metal2vulkan-runtime/src/render/shadows.rs index 9db65b573..df424b003 100644 --- a/crates/metal2vulkan-runtime/src/render/shadows.rs +++ b/crates/metal2vulkan-runtime/src/render/shadows.rs @@ -276,24 +276,52 @@ impl InstanceShadows { Some(kept) => kept.clone_from(used), None => self.last.push(used.clone()), } - for (write, access) in [(false, used.read), (true, used.write)] { - if access.is_empty() { - continue; + self.gather(used); + } + } + + /// [`add`](Self::add) a recorded draw's `uses`, which use no shadowed texture, where they + /// differ from the last draw's only at the positions `at` (a draw whose calls moved buffer + /// offsets alone: `render/draw_again/rebound.rs`): those positions alone are looked at, as + /// `add` skips every use equal to the last draw's at its place. Whether it took them so: the + /// last draw's uses were as many; else it changed nothing, and the caller adds them whole. + pub(super) fn add_moved(&mut self, uses: &[Use], at: &[usize]) -> bool { + if self.last.len() != uses.len() { + return false; + } + for &at in at { + let used = &uses[at]; + if self.last[at] != *used { + self.last[at].clone_from(used); + self.gather(used); + } + } + debug_assert!( + *self.last == *uses, + "an instance gathered a draw moved whose other uses differ from the last draw's" + ); + true + } + + /// Gather `used`'s reads and writes ([`add`](Self::add)). + fn gather(&mut self, used: &Use) { + for (write, access) in [(false, used.read), (true, used.write)] { + if access.is_empty() { + continue; + } + match &used.range { + UseRange::Bytes(range) => { + let ranges = ranges_mut(&mut self.bytes, &mut self.held, (used.key, write)); + insert(ranges, range.clone()); } - match &used.range { - UseRange::Bytes(range) => { - let ranges = ranges_mut(&mut self.bytes, &mut self.held, (used.key, write)); - insert(ranges, range.clone()); - } - image => { - let key = (used.key, write); - match self.images.binary_search_by_key(&key, |&(at, _)| at) { - Ok(at) => { - let held = &mut self.images[at].1; - *held = span(held, image); - } - Err(at) => self.images.insert(at, (key, image.clone())), + image => { + let key = (used.key, write); + match self.images.binary_search_by_key(&key, |&(at, _)| at) { + Ok(at) => { + let held = &mut self.images[at].1; + *held = span(held, image); } + Err(at) => self.images.insert(at, (key, image.clone())), } } } diff --git a/crates/metal2vulkan-runtime/src/tests/command_counts.rs b/crates/metal2vulkan-runtime/src/tests/command_counts.rs index c506fc645..b954ba1a2 100644 --- a/crates/metal2vulkan-runtime/src/tests/command_counts.rs +++ b/crates/metal2vulkan-runtime/src/tests/command_counts.rs @@ -23,8 +23,9 @@ const DRAWS: u64 = 4000; /// The command counts the encoders' draws add, by name: those that follow from an encoder's own /// calls alone, so that each encoder of the same calls adds the same. -const COUNTS: [(&str, fn(&WorkCounts) -> u64); 10] = [ +const COUNTS: [(&str, fn(&WorkCounts) -> u64); 11] = [ ("draws_rebound", |counts| counts.draws_rebound), + ("draws_moved", |counts| counts.draws_moved), ("draws_as_before", |counts| counts.draws_as_before), ("stage_tables_read", |counts| counts.stage_tables_read), ("stage_tables_read_in_part", |counts| { diff --git a/crates/metal2vulkan-runtime/src/tests/draw_again.rs b/crates/metal2vulkan-runtime/src/tests/draw_again.rs index 273f1e408..e21e657a6 100644 --- a/crates/metal2vulkan-runtime/src/tests/draw_again.rs +++ b/crates/metal2vulkan-runtime/src/tests/draw_again.rs @@ -702,6 +702,8 @@ fn draws_after_buffer_changes_rebind_what_every_step_binds() { }); assert_eq!(rebound.counted(rebound_count), drawn_alone(HITS)); assert_eq!(rebound.counted(as_before), 0); + // Bytes bound at each draw: no draw is moved. + assert_eq!(rebound.counted(|counts| counts.draws_moved), 0); assert_eq!(every.counted(rebound_count), 0); assert_eq!(sampled.counted(rebound_count), 0); assert_eq!(rebound.commands, every.commands); @@ -727,6 +729,83 @@ fn draws_after_buffer_changes_rebind_what_every_step_binds() { } } +/// [`DRAWS`] draws of `state`'s rectangles from `rectangles` as [`offset_rectangles`] draws them, +/// the `at`th in the color at `16 * at` bytes of `colors` (fragment buffer 0, bound again at that +/// offset before each draw but the first), with `between` called after the binds. +fn moved_rectangles( + encoder: &mut RenderCommandEncoder, + (state, rectangles, colors): (&RenderPipelineState, &Buffer, &Buffer), + between: impl Fn(&mut RenderCommandEncoder), +) { + encoder.set_render_pipeline_state(state).unwrap(); + encoder.set_vertex_buffer(Some(rectangles), 0, 0).unwrap(); + encoder.set_fragment_buffer(Some(colors), 0, 0).unwrap(); + for at in 0..DRAWS { + if at > 0 { + encoder.set_vertex_buffer_offset(16 * at, 0).unwrap(); + encoder + .set_fragment_buffer(Some(colors), 16 * at, 0) + .unwrap(); + between(encoder); + } + rectangle(encoder); + } +} + +/// Draws after calls that moved only the offsets of the buffers bound at their slots, the vertex +/// buffer's and the fragment buffer's (`set_vertex_buffer_offset`, and `set_fragment_buffer` of +/// the buffer bound there), are moved (`WorkCounts::draws_moved`: their tables bind the objects +/// the draw before bound, and their uses differ only at the moved slots'), with the same commands +/// of every kind, state commands, noted uses and pixels as the same draws with a call between each +/// that changes nothing for them, each of which takes every step; each at another offset of both +/// buffers, in another color each, as each column's count of draws and each draw's color show. +#[test] +fn draws_after_offsets_alone_moved_bind_what_every_step_binds() { + let scratch = Scratch::new("draw-again-moved"); + let heard = Heard::default(); + let device = device(&scratch.0, &[], &heard); + let state = adding_state(&device); + let rectangles = rectangles_from_columns(&device); + let colors: Vec = (0..DRAWS) + .flat_map(|at| [(at + 1) as f32 / 64.0; 4]) + .collect(); + let colors = bytes_of(&colors, f32::to_le_bytes); + let colors = (device.new_buffer_with_bytes(&colors, ResourceOptions::shared())).unwrap(); + let drawn = (&state, &rectangles, &colors); + let same_color = + |encoder: &mut RenderCommandEncoder| encoder.set_blend_color(0.0, 0.0, 0.0, 0.0); + warm(&device, |encoder| moved_rectangles(encoder, drawn, |_| {})); + let rebound = run(&device, |encoder| moved_rectangles(encoder, drawn, |_| {})); + let every = run(&device, |encoder| { + moved_rectangles(encoder, drawn, same_color) + }); + let moved_count = |counts: &WorkCounts| counts.draws_moved; + assert_eq!(rebound.counted(moved_count), drawn_alone(HITS)); + assert_eq!( + rebound.counted(|counts| counts.draws_rebound), + drawn_alone(HITS) + ); + assert_eq!(every.counted(moved_count), 0); + assert_eq!(rebound.commands, every.commands); + assert_eq!(rebound.commands["cmd_draw"], DRAWS); + assert_eq!(rebound.words, every.words, "the pixels of the draws"); + let counts: [(&str, fn(&WorkCounts) -> u64); 3] = [ + ("draw_states_recorded", |counts| counts.draw_states_recorded), + ("commands_noted_as_before", |counts| { + counts.commands_noted_as_before + }), + ("draws_pushing_set_zero", |counts| { + counts.draws_pushing_set_zero + }), + ]; + for (name, count) in counts { + assert_eq!(rebound.counted(count), every.counted(count), "{name}"); + } + // Column 0 holds the first draw's color alone; the last column every draw's. + let last = SIDE as usize - 1; + assert_ne!(rebound.words[0], rebound.words[last], "the draws' offsets"); +} + /// [`DRAWS`] 4x4 `RGBA8Unorm` textures, the `at`th's texel in column `x` of the bytes /// `(2 * (at + 1), 2 * (x + 1), 0, 1)`: what a draw sampled tells which texture and which of its /// columns. diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index daef77ad8..e96caac2a 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -514,6 +514,7 @@ struct CommandCounters { set_zero_writes_pushed: AtomicU64, draws_as_before: AtomicU64, draws_rebound: AtomicU64, + draws_moved: AtomicU64, resident_uses_made: AtomicU64, argument_tables_held_at_bind: AtomicU64, bound_offsets_moved: AtomicU64, @@ -921,6 +922,11 @@ impl Counting<'_> { Self::kept_draw(&counts, kept); } + /// A render draw rebound that was moved (`WorkCounts::draws_moved`). + pub(crate) fn draw_moved(&self) { + self.0.add(|counts| &counts.draws_moved, 1); + } + /// `tables` stage tables read into a kept draw's bind state, each bringing in only the slots /// calls changed (`render/draw_again/rebound.rs`), whether the draw is then rebound or takes /// every step, which finds them read. @@ -5468,6 +5474,13 @@ pub struct WorkCounts { /// does, and records the state commands that changed (`draw_states_recorded`) and its draw; /// it takes nothing of the shape memo (`draw_shapes_reused`) and settles nothing. pub draws_rebound: u64, + /// Of `draws_rebound`, those moved: each call since the draw they repeat moved a buffer slot's + /// offset alone, the slot binding the buffer it bound (`render/draw_again/rebound.rs`). A + /// draw moved looks at no visible-function table, shadow or detached buffer again, its slots + /// binding the objects that draw bound; keeps that draw's set-0 writes and dynamic offsets + /// where its descriptor ranges are that draw's; and where its moved slots' uses were patched + /// in place, checks, notes and gathers those uses alone, every other use being that draw's. + pub draws_moved: u64, /// The uses of resources a render encoder made resident (`useResource:usage:stages:`, /// `useHeap:stages:`) that its draws' binding plans list, as its draws worked them out for /// hazard tracking: a draw keeps the last draw's where its plan is the last draw's, or lists @@ -7042,6 +7055,7 @@ impl Device { draw_shapes_carried: commands(|counts| &counts.draw_shapes_carried), draws_as_before: commands(|counts| &counts.draws_as_before), draws_rebound: commands(|counts| &counts.draws_rebound), + draws_moved: commands(|counts| &counts.draws_moved), resident_uses_made: commands(|counts| &counts.resident_uses_made), resident_keys_settled: commands(|counts| &counts.resident_keys_settled), resident_uses_gathered: commands(|counts| &counts.resident_uses_gathered), diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 1f57b2b58..2a7bd067b 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2651,6 +2651,7 @@ field metal2vulkan-runtime::WorkCounts.draw_states_recorded pub draw_states_reco field metal2vulkan-runtime::WorkCounts.draws_as_before pub draws_as_before: u64 field metal2vulkan-runtime::WorkCounts.draws_dropped_still_making pub draws_dropped_still_making: u64 field metal2vulkan-runtime::WorkCounts.draws_dropped_unmade pub draws_dropped_unmade: u64 +field metal2vulkan-runtime::WorkCounts.draws_moved pub draws_moved: u64 field metal2vulkan-runtime::WorkCounts.draws_pushing_set_zero pub draws_pushing_set_zero: u64 field metal2vulkan-runtime::WorkCounts.draws_rebound pub draws_rebound: u64 field metal2vulkan-runtime::WorkCounts.draws_settled pub draws_settled: u64