diff --git a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs index 6fc9d65fe..4fa9cf5cd 100644 --- a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs +++ b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs @@ -1310,6 +1310,7 @@ impl Gpu for Runtime { c.render_passes_begun_inline_splits, ), ("passes_begun_resolves", c.render_passes_begun_resolves), + ("passes_continued", c.render_passes_continued), ("splits_barrier", c.instance_splits_barrier), ("splits_tile_dispatch", c.instance_splits_tile_dispatch), ("splits_tile_memory", c.instance_splits_tile_memory), diff --git a/crates/metal2vulkan-runtime/src/command_buffer/fold.rs b/crates/metal2vulkan-runtime/src/command_buffer/fold.rs index 49514cd3e..3a0cebac4 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/fold.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/fold.rs @@ -5,6 +5,7 @@ use super::{FailedEncoders, FailedSignals, Failure, State}; use crate::encoder::Overwrite; use crate::encoder_fold::{Fold, FoldEnd, FoldOrder, Joining, Refusal, Stashed}; +use crate::render_target::PassKey; use crate::replay::Replay; use crate::resource::ResourceKey; use crate::tracker::Summary; @@ -12,6 +13,7 @@ use crate::used_resources::EncoderKind; use crate::work_counts::Counters; use std::collections::BTreeSet; use std::ops::Range; +use std::sync::Arc; impl State { /// The group the encoder opening now joins, asking `joining`, where its @@ -63,6 +65,54 @@ impl State { if let Some(order) = order { fold.order = order; } + // It records into the tail outside any render pass instance (`encoder_fold.rs`'s + // **Continued passes**). + fold.end_open(); + Some(fold) + } + + /// What the render pass instance the group the tail holds left open renders, where it left + /// one (`encoder_fold.rs`'s **Continued passes**): what a render encoder opening now may + /// continue. + pub(crate) fn open_pass(&self) -> Option> { + let fold = self.fold.as_ref()?; + let open = fold.open.as_ref()?; + (self.tail == Some(fold.tail)).then(|| Arc::clone(open.key())) + } + + /// The group whose tail holds the render pass instance `key` renders open, taken for the + /// encoder that continues it (`encoder_fold.rs`'s **Continued passes**), as + /// [`join_fold`](Self::join_fold) gives a joining encoder its group, its order noted + /// after the instance's draws so far: where the tail still holds that instance and the group + /// admits an encoder (its tail and batch, the command buffer's command predication and + /// protection options; the encoder trail is the caller's). `None` else, the group left in + /// place. + pub(crate) fn continue_pass(&mut self, key: &PassKey, counts: &Counters) -> Option> { + let fold = self.fold.as_ref()?; + let open = fold.open.as_ref()?; + let admits = **open.key() == *key + && self.tail == Some(fold.tail) + && self.batches.all().len() == fold.batches + && !self.batches.signals_pending() + && !self.predicated + && self.protection.options() == 0; + if !admits { + return None; + } + let order = match fold.members.len() { + 1 => Some(FoldOrder::after(&self.recorded.get(fold.leader)?.summary)), + _ => None, + }; + self.tail = None; + let mut fold = self.fold.take()?; + if let Some(order) = order { + fold.order = order; + } + fold.order.continued(); + // The instance is the encoder's own from here: its pass holds it, and ends it or leaves + // it open again as it ends. + fold.open = None; + counts.render_pass_continued(); Some(fold) } @@ -82,7 +132,14 @@ impl State { ends, summary, log, + open, } = end; + // The group a render encoder that might have continued its open render pass instance + // kept, where it did not (`encoder_fold.rs`'s **Continued passes**), closes first. + let mut unkept = match fold.is_some() { + true => Vec::new(), + false => self.close_fold(counts), + }; // Why no group goes on past it, where none may. self.unfolded = match (ends, joining) { (Some(why), _) => Some(why), @@ -98,7 +155,15 @@ impl State { log, executions, }); - let mut unkept = Vec::new(); + // The render pass instance it left open in its last `VkCommandBuffer`, the tail, goes on + // with its group, where the group goes on past it; else it ends here. + let mut open = match open { + Some(open) if Some(open.raw()) != self.tail => { + open.end(); + None + } + open => open, + }; if let Some(mut fold) = fold { fold.members.end = encoder + 1; if let Some(record) = self.ended.get_mut(encoder) { @@ -109,11 +174,12 @@ impl State { if let (Some(joining), Some(summary), true) = (leads, &summary, goes_on) { fold.went_on(joining, summary); fold.batches = self.batches.all().len(); + fold.open = open; self.fold = Some(fold); return unkept; } self.fold = Some(fold); - unkept = self.close_fold(counts); + unkept.extend(self.close_fold(counts)); } match (leads, self.tail) { (Some(joining), Some(tail)) => { @@ -125,11 +191,12 @@ impl State { // Its stash takes the room the command buffer's lists keep (`spare_states.rs`). let mut stashed = self.stash_room.take().unwrap_or_default(); stashed.extend(log); + let open = open.take(); self.fold = Some(Box::new(Fold::begun( tail, (leader, encoder), (batches, joining), - stashed, + (stashed, open), ))); } (Some(_), None) => { @@ -138,6 +205,9 @@ impl State { } (None, _) => unkept.extend(log.map(|stashed| stashed.log)), } + if let Some(open) = open { + open.end(); + } unkept } @@ -168,9 +238,10 @@ impl State { /// (`replay.rs`). A group of more gives the room of its stash back, emptied, for the next /// group's (`spare_states.rs`). pub(crate) fn close_fold(&mut self, counts: &Counters) -> Vec { - let Some(fold) = self.fold.take() else { + let Some(mut fold) = self.fold.take() else { return Vec::new(); }; + fold.end_open(); let Fold { members, mut stashed, diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index c066037fe..6c24e08ad 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -5935,6 +5935,11 @@ impl CommandBufferShared { let Some(raw) = state.tail.take() else { return; }; + // A render pass instance its group left open in it ends first (`encoder_fold.rs`'s + // **Continued passes**). + if let Some(fold) = state.fold.as_mut().filter(|fold| fold.tail == raw) { + fold.end_open(); + } let part = joined.unwrap_or(state.recorded.len()).saturating_sub(1); let batch = state.batch_of(part); let ended = joined.is_none_or(|joined| state.batch_of(joined) != batch); diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 4a98bd617..7525887c2 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -55,7 +55,7 @@ use super::compute::Parked; use super::copy_run::CopyRun; use super::deferred::{Deferred, StepInputs}; use super::degradation::NoticesFor; -use super::encoder_fold::{self, Fold, FoldEnd, Joining, Refusal}; +use super::encoder_fold::{self, Fold, FoldEnd, Joining, OpenPass, Refusal}; use super::error::{ internal, invalid, vulkan, CommandBufferError, CopyQueueProblem, Error, VkResultCode, }; @@ -76,6 +76,7 @@ use super::pending_dispatch::PendingDispatch; use super::pipeline::VariantObjects; use super::rebind::{Holds, Taken}; use super::render::face_swap::Turns; +use super::render_target::PassKey; use super::replay::Replay; use super::residency::{Residency, Used}; use super::resource::ResourceKey; @@ -418,6 +419,19 @@ pub(super) struct EncoderCore { /// commands meanwhile record into `raw`, which goes before it in submission order, as they go /// before a pass recorded at its end. pass: Option, + /// Whether `pass` is the `VkCommandBuffer` the encoder opened in, taken with nothing + /// recorded into it: what a pass that continues the render pass instance its command + /// buffer's tail holds open gives up unsubmitted ([`continue_pass`](Self::continue_pass)). + pass_own: bool, + /// The render pass instance its pass left open in `raw` as it ended + /// ([`leave_pass_open`](Self::leave_pass_open)): its next command ends it first; where none + /// comes, the group its end begins or goes on in keeps it open (`encoder_fold.rs`'s + /// **Continued passes**). + open_pass: Option, + /// What the render pass instance its command buffer's tail held open as it opened renders, + /// whose group it left in place for its pass to continue (`encoder_fold.rs`'s **Continued + /// passes**); `None` once its pass continued it or let it go, and for every other encoder. + continuable: Option>, /// The `VkCommandBuffer` the encoder opened in, which [`open`](Self::open) began with a /// barrier from everything before: past the first [`PLANNED_BARRIERS`] encoders of its /// command buffer. Not `recorded`: a pass may hold it, and what records before that pass @@ -795,8 +809,27 @@ impl EncoderCore { // the group it joined), under the state lock, and only this encoder records it now; the // device made by the runtime enables `hostQueryReset` (`gpu_time.rs`). let times = unsafe { shared.timing.encoders().open(shared.vk(), raw) }; + // A render encoder whose first instance may record inline keeps the group whose tail + // holds a render pass instance open, for its pass to continue (`encoder_fold.rs`'s + // **Continued passes**): where it began its own `VkCommandBuffer` with nothing in it, and + // the device times no encoder, keeps no trail and splits at no alias. + let continues = matches!( + joining, + Some(Joining::Render { + continues: true, + .. + }) + ) && fold.is_none() + && barriered.is_none() + && times.is_none() + && !shared.encoder_trail + && !shared.splits_at_aliases; + let continuable = continues.then(|| state.open_pass()).flatten(); // A group of encoders it did not join takes no encoder from here. - let unkept = state.close_fold(&shared.counts); + let unkept = match continuable { + Some(_) => Vec::new(), + None => state.close_fold(&shared.counts), + }; state.encoder_open = true; // Made under the protection options set now (`command_buffer/protection.rs`). state.protected_made(); @@ -825,6 +858,9 @@ impl EncoderCore { raw, recorded: false, pass: None, + pass_own: false, + open_pass: None, + continuable, barriered, joining, fold, @@ -1006,6 +1042,9 @@ impl EncoderCore { raw, recorded: false, pass: None, + pass_own: false, + open_pass: None, + continuable: None, barriered: None, joining: None, fold: None, @@ -1480,6 +1519,7 @@ impl EncoderCore { /// [`recording`](Self::recording) before the open gather runs record into it. fn raw_recording(&mut self) -> Option { + self.settle_open_pass(); if self.raw == vk::CommandBuffer::null() { match self.continuation() { Ok(next) => self.raw = next.0, @@ -1522,6 +1562,7 @@ impl EncoderCore { false => { let own = self.raw; self.raw = vk::CommandBuffer::null(); + self.pass_own = self.ended.is_empty(); own } }; @@ -1529,6 +1570,71 @@ impl EncoderCore { Ok(held) } + /// Where the encoder's pass may continue the render pass instance its command buffer's tail + /// held open as the encoder opened (`encoder_fold.rs`'s **Continued passes**): what that + /// instance renders, which the pass's first instance must render too. + pub(super) fn continuable(&self) -> Option<&PassKey> { + self.continuable.as_deref() + } + + /// Continue the render pass instance its command buffer's tail holds open, which renders + /// what `key` says, with the pass the encoder holds (`encoder_fold.rs`'s **Continued + /// passes**): its pass took the `VkCommandBuffer` the encoder opened in with nothing recorded + /// into it, and nothing recorded before the pass since; and the tail's group admits it + /// (`State::continue_pass`). Then the encoder joins that group, its pass holding the tail + /// inside that instance, and the `VkCommandBuffer` it opened in ends unsubmitted. Whether it + /// did; where it did not, the group closes, the instance ended, and the pass records as + /// before. + pub(super) fn continue_pass(&mut self) -> bool { + let own = match (self.pass, &self.continuable) { + (_, None) => return false, + (Some(own), Some(_)) if self.pass_own && self.raw == vk::CommandBuffer::null() => own, + (_, Some(_)) => { + self.let_go_of_group(); + return false; + } + }; + let Some(key) = self.continuable.take() else { + return false; + }; + let shared = self.open.command_buffer.device().shared(); + let mut state = self.open.command_buffer.state(); + let Some(fold) = state.continue_pass(&key, &shared.counts) else { + let unkept = state.close_fold(&shared.counts); + drop(state); + for log in unkept { + shared.scheduler.spare_logs().give(log); + } + return false; + }; + drop(state); + // SAFETY: the encoder's own `VkCommandBuffer` is recording, nothing recorded into it, and + // only this encoder records it; it is never submitted, and its pool begins it again + // (`spares.rs`). + if unsafe { self.open.command_buffer.end_raw(own) }.is_err() { + self.open.command_buffer.state().abandoned = true; + } + self.pass = Some(fold.tail); + self.pass_own = false; + self.in_tail = true; + self.fold = Some(fold); + true + } + + /// Close the group of encoders the encoder left in place for its pass to continue, where it + /// left one, ending the render pass instance its tail holds open (`encoder_fold.rs`'s + /// **Continued passes**): its pass records its own. + pub(super) fn let_go_of_group(&mut self) { + if self.continuable.take().is_none() { + return; + } + let shared = self.open.command_buffer.device().shared(); + let unkept = self.open.command_buffer.state().close_fold(&shared.counts); + for log in unkept { + shared.scheduler.spare_logs().give(log); + } + } + /// End the hold [`hold_pass`](Self::hold_pass) took: the render pass instance recorded in /// the held command buffer ends there, whatever the encoder's commands record from here on /// (a command that names a detached buffer records nothing, [`skips`](Self::skips)); the @@ -1536,13 +1642,42 @@ impl EncoderCore { /// it; and the encoder's commands record on into the pass's, after it. Refused only where /// that one does not end, which abandons the command buffer. pub(super) fn release_pass(&mut self) -> Result<(), Error> { + self.release_pass_ending(true) + } + + /// [`release_pass`](Self::release_pass), but the render pass instance stays open in the + /// pass's command buffer, which renders what `key` says (`encoder_fold.rs`'s **Continued + /// passes**): the encoder's next command ends it first, and where none comes, the group its + /// end begins or goes on in keeps it open for the next render encoder. + pub(super) fn leave_pass_open(&mut self, key: Arc) -> Result<(), Error> { + let Some(pass) = self.pass else { + return Ok(()); + }; + self.release_pass_ending(false)?; + self.open_pass = Some(OpenPass::new(self.device(), pass, key)); + Ok(()) + } + + /// End the render pass instance the encoder's pass left open in its command buffer + /// ([`leave_pass_open`](Self::leave_pass_open)), where it left one: before anything else + /// records into it. + fn settle_open_pass(&mut self) { + if let Some(open) = self.open_pass.take() { + open.end(); + } + } + + /// [`release_pass`](Self::release_pass), the render pass instance ended where `ends`. + fn release_pass_ending(&mut self, ends: bool) -> Result<(), Error> { self.flush_gathers(); let Some(pass) = self.pass.take() else { return Ok(()); }; - // SAFETY: the held command buffer is recording inside the render pass instance its pass - // began, and only this encoder records it. - unsafe { self.device().shared().vk().cmd_end_render_pass(pass) }; + if ends { + // SAFETY: the held command buffer is recording inside the render pass instance its + // pass began, and only this encoder records it. + unsafe { self.device().shared().vk().cmd_end_render_pass(pass) }; + } if self.raw != vk::CommandBuffer::null() { // SAFETY: as in `barrier`. if let Err(error) = unsafe { self.open.command_buffer.end_raw(self.raw) } { @@ -1564,6 +1699,7 @@ impl EncoderCore { /// command begins another command buffer. Refused only where it does not end, which abandons /// the command buffer. pub(super) fn hand_over_pass(&mut self) -> Result { + self.settle_open_pass(); self.flush_gathers(); let pass = self.raw; if pass == vk::CommandBuffer::null() { @@ -1601,6 +1737,7 @@ impl EncoderCore { /// apart from what follows, and go on in a new one, begun with a barrier from everything /// before. Refused where the current one does not end or the new one cannot be begun. pub(super) fn cut_piece(&mut self) -> Result<(), Error> { + self.settle_open_pass(); // SAFETY: as in `barrier`. unsafe { self.open.command_buffer.end_raw(self.raw) }.map_err(vulkan)?; self.ended.push(self.raw); @@ -1610,6 +1747,30 @@ impl EncoderCore { Ok(()) } + /// [`command`](Self::command) of a command that records nothing: its uses tracked as hers + /// are, and where they need a barrier after the encoder's earlier commands, that barrier + /// recorded, after the render pass instance the encoder's pass left open ends + /// ([`leave_pass_open`](Self::leave_pass_open)); else nothing records, and the instance stays + /// open. A render pass's end notes its uses so, its one instance left open + /// (`encoder_fold.rs`'s **Continued passes**). + pub(super) fn command_recording_nothing( + &mut self, + stages: vk::PipelineStageFlags2, + uses: &[Use], + ) { + let none = BTreeSet::new(); + let Some(Some(barrier)) = self.track(stages, uses, (&none, Reach::Unnamed), &[]) else { + return; + }; + let Some(raw) = self.recording_ordered() else { + return; + }; + let device = self.open.command_buffer.device().shared().vk(); + let reads = self.open.command_buffer.memory_reads(); + // SAFETY: as in `barrier`. + unsafe { barrier.record_reading(device, raw, reads) }; + } + /// Record one command that ran in `stages` with `uses`: the barrier the uses need after the /// encoder's earlier commands (in an ordered encoder), then the command through `record`. /// Call it once every check of the command passed: recording cannot fail. @@ -1801,6 +1962,7 @@ impl EncoderCore { if self.raw == vk::CommandBuffer::null() || self.pass.is_some() { return true; } + self.settle_open_pass(); self.flush_gathers(); // SAFETY: as in `barrier`. if unsafe { self.open.command_buffer.end_raw(self.raw) }.is_err() { @@ -3188,6 +3350,7 @@ impl EncoderCore { /// it reads, and a barrier from everything before at its start. Its handle. Refused where the /// current one does not end, or none can be made, which abandons the command buffer. pub(super) fn cut_reusable(&mut self) -> Result { + self.settle_open_pass(); let copies = self.shadows.leave(); let copies = self.sample_moves(copies); self.shadow_copies(&copies); @@ -3241,6 +3404,7 @@ impl EncoderCore { /// current one does not end, which abandons the command buffer. pub(super) fn leave_out_recorded(&mut self) -> Result<(), Error> { self.release_pass()?; + self.settle_open_pass(); self.flush_gathers(); let next = self.continuation()?; if self.raw != vk::CommandBuffer::null() { @@ -3289,6 +3453,7 @@ impl EncoderCore { /// at its next command ([`raw_recording`](Self::raw_recording)): refused only where the /// current `VkCommandBuffer` does not end, which abandons the command buffer. fn defer_into(&mut self, next: Option, work: Deferred) -> Result<(), Error> { + self.settle_open_pass(); self.flush_gathers(); if work.leaves_shadows() { let copies = self.shadows.leave(); @@ -3579,6 +3744,7 @@ impl EncoderCore { joining, fold, in_tail, + open_pass, mut ended, mut segments, left_out, @@ -3800,19 +3966,28 @@ impl EncoderCore { } state.tail = Some(raw); // It begins a group of encoders, goes on in the one it joined, or closes - // it (`encoder_fold.rs`). - if joining.is_some() { - let shared = open.command_buffer.device().shared(); - let end = FoldEnd { - joining: joining.filter(|_| !shared.encoder_trail), - fold, - in_tail, - encoder, - ends, - summary: fold_summary, - log: held_log.map(|log| (log, executed)), - }; - unkept.extend(state.fold_ended(end, &shared.counts)); + // it (`encoder_fold.rs`), which keeps the render pass instance its pass left open or ends + // it (**Continued passes**). + match joining { + Some(_) => { + let shared = open.command_buffer.device().shared(); + let end = FoldEnd { + joining: joining.filter(|_| !shared.encoder_trail), + fold, + in_tail, + encoder, + ends, + summary: fold_summary, + log: held_log.map(|log| (log, executed)), + open: open_pass, + }; + unkept.extend(state.fold_ended(end, &shared.counts)); + } + None => { + if let Some(open) = open_pass { + open.end(); + } + } } state.held_lately = retained.lately(); state.retained.extend(retained.into_entry()); diff --git a/crates/metal2vulkan-runtime/src/encoder_fold.rs b/crates/metal2vulkan-runtime/src/encoder_fold.rs index a50bbae41..d2d41cfd5 100644 --- a/crates/metal2vulkan-runtime/src/encoder_fold.rs +++ b/crates/metal2vulkan-runtime/src/encoder_fold.rs @@ -54,6 +54,55 @@ //! commands: `deferred.rs` segments) or a write it judges by its part //! (`Overwrite`) ends the group after it, as for any encoder; a late resolve target //! (`render/late_resolve.rs`) is the pass's own, recorded at its end in its `VkCommandBuffer`. +//! - **Continued passes.** A render encoder whose pass recorded its one instance inline and whose +//! end records nothing after it leaves that render pass instance open in its last +//! `VkCommandBuffer`, which goes on as the group's tail ([`OpenPass`], `Fold::open`), where its +//! pass touched nothing but its attachments: no draw wrote anything else (a storage write) or +//! used the attachments' images or bytes another way, and no command reached memory it does not +//! name (a root or handle table, a heap, a memory barrier inside the pass, an execution of +//! render commands); its loads and stores are `Load` or `Clear` and `Store`, as an instance +//! recorded inline has (`render/inline_first.rs`), with no resolve, visibility result or +//! rasterization-rate map, and the device times no encoder. The next render encoder, whose +//! first instance may record inline (`Joining::Render`'s `continues`), keeps that group as it +//! opens; where its first instance renders what the open one does +//! (`render_target::PassKey`: compatible render passes of one shape, the same views over the +//! same extent and layers) and loads every attachment (`Load`), its draws are kept as they come +//! (`render/inline_splits.rs`'s `Kept`), and at its first split or its end it records them into +//! the open instance, with no end, barrier or begin between, where its encoder recorded no +//! command before the pass (its pass took its own `VkCommandBuffer`, unbegun by anything, past +//! no barrier at its open) and the instance has no copy or step before it, its draws touched +//! nothing but its attachments either, and the group admits it as it admits a joining encoder +//! (its tail and batch unchanged, no command predication, no protection options, no encoder +//! trail, no device that splits at aliases): it joins the group there, its uses joining the +//! group's first part's summary, its own `VkCommandBuffer` ended unsubmitted. Else it closes +//! the group, ending the open instance in the tail, and records its own as before. Anything +//! else that records into the tail ends the instance first: an encoder that joins the group, +//! the group's close, the tail's end. Counted: `WorkCounts::render_passes_continued`. +//! +//! Why it is Metal's answer. Metal runs the two passes one after the other, the second loading +//! what the first stored. In one subpass, "for a given (x,y,layer,sample) sample location, the +//! following operations are guaranteed to execute in rasterization order, for each separate +//! primitive that includes that sample location: Fragment operations, in the order defined; +//! Blending, logic operations, and color writes" (Rasterization Order), and rasterization order +//! follows primitive order, of which "Submission order determines the initial ordering" +//! (Primitive Order): every fragment operation of the later encoder's draws comes after the +//! earlier's at each sample, as its load (`VK_ATTACHMENT_LOAD_OP_LOAD`, "the previous contents +//! of the image within the render area will be preserved as the initial values") after the +//! earlier's store (`VK_ATTACHMENT_STORE_OP_STORE`, "the contents generated during the render +//! pass and within the render area are written to memory") would have it. Neither pass wrote +//! anything else, so nothing else of the earlier one needs ordering before the later one's +//! draws, nor anything a fence between them covers; what reads the attachments otherwise (a +//! sampled read of a target, a copy) records after a split or the instance's end, behind a +//! barrier as before. The later encoder's draws record every state they take into the +//! `VkCommandBuffer` from nothing bound (`render/bound.rs`), as into a new one, so each starts +//! from Metal's defaults (its viewport, scissor, depth bias, stencil reference, blend color, +//! cull mode, winding and fill mode, its own or Metal's). Its label and place among the +//! command buffer's ended encoders are its own, as every encoder's of a group. A rebind or a +//! failure encodes or splits the group as any (**Encoded again**, **Failed**): its encoders +//! encode again apart, each its own pass, from their logs. "There is no implicit ordering +//! between separate render passes, even in the same command buffer, and even when the +//! attachments match" (Render Pass), so two passes ordered only by one instance's +//! rasterization order must be one instance. //! - **The barrier between them** is recorded as the encoder records, by the rule the tracker //! applies between two encoders of one batch: from each earlier write of a tracked resource's //! overlapping range to a later read or write, its accesses made visible, and from each earlier @@ -154,13 +203,16 @@ //! dispatch) hold about 320 bytes, so 2,300 such encoders hold about 0.7 MiB until their command buffer completes. use crate::key_hash::KeyMap; +use crate::render_target::PassKey; use crate::replay::Replay; use crate::resource::ResourceKey; use crate::tracker::{Access, Barrier, Summary, Use, UseRange, ENTRIES_PER_KEY}; +use crate::Device; use ash::vk; use metal2vulkan::metal::DispatchType; use std::hash::Hash; use std::ops::Range; +use std::sync::Arc; /// What a group's earlier encoders did to one range of one tracked resource, and what the /// barriers recorded since ordered after it. @@ -365,6 +417,28 @@ impl FoldOrder { } } + /// Note a render pass instance continued (**Continued passes** in the module docs): every + /// access of the group's earlier encoders not yet ordered to a resource they wrote is an + /// attachment access of the instance (no encoder that touched anything else so left it open), + /// which rasterization order orders before the attachment accesses of every later draw of + /// the instance, its writes visible to them; so too their fenced writes. + pub(crate) fn continued(&mut self) { + let attachments = unnamed_access(ATTACHMENT_STAGES); + for prior in self.priors.values_mut().flatten() { + if attachments.covers(prior.write) { + prior.visible = prior.visible.union(attachments); + } + // Their attachment reads (a load) come before every later draw's attachment writes + // at each sample too. + if ATTACHMENT_STAGES.contains(prior.reads) { + prior.after_reads |= ATTACHMENT_STAGES; + } + } + if !self.fenced.is_empty() { + self.fenced_visible = self.fenced_visible.union(attachments); + } + } + /// The barrier from every access of the group's earlier encoders not yet ordered, and their /// fenced writes, to every later access: what a recording that bypasses the per-command order /// records first. `None` where none is left to order. @@ -519,12 +593,14 @@ pub(crate) struct Stashed { /// encoder joins one whose compute encoders are of its dispatch type (or that holds none), as a /// unit of command predication holds compute encoders of one dispatch type (`predication.rs`); a /// blit encoder joins any; a render encoder joins any where `joins`, else none, and may begin one -/// either way (the module docs, **Render encoders**). +/// either way (the module docs, **Render encoders**). One whose first instance may record inline +/// (`continues`) may continue the render pass instance a group's tail holds open, as it decides +/// later (**Continued passes** in the module docs). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Joining { Compute(DispatchType), Blit, - Render { joins: bool }, + Render { joins: bool, continues: bool }, } impl Joining { @@ -586,6 +662,10 @@ pub(crate) struct Fold { pub(crate) order: FoldOrder, /// Its members' logs not kept by themselves. pub(crate) stashed: Vec, + /// The render pass instance its last encoder left open in the tail, which the next render + /// encoder may continue (**Continued passes** in the module docs); ended before anything else + /// records into the tail. + pub(crate) open: Option, } impl Fold { @@ -596,7 +676,7 @@ impl Fold { .dispatch_type .is_none_or(|group| group == dispatch_type), Joining::Blit => true, - Joining::Render { joins } => joins, + Joining::Render { joins, .. } => joins, } } @@ -606,7 +686,7 @@ impl Fold { tail: vk::CommandBuffer, (leader, encoder): (usize, usize), (batches, joining): (usize, Joining), - stashed: Vec, + (stashed, open): (Vec, Option), ) -> Fold { Fold { tail, @@ -617,6 +697,15 @@ impl Fold { blits_alone: joining == Joining::Blit, order: FoldOrder::none(), stashed, + open, + } + } + + /// End the render pass instance the tail holds open, where it holds one: before anything + /// else records into the tail, and before the tail ends. + pub(crate) fn end_open(&mut self) { + if let Some(open) = self.open.take() { + open.end(); } } @@ -697,4 +786,46 @@ pub(crate) struct FoldEnd { pub(crate) summary: Option>, /// Its log, which it did not keep, with its executions' place. pub(crate) log: Option<(Replay, Range)>, + /// The render pass instance it left open in its last `VkCommandBuffer`, where it left one + /// (**Continued passes** in the module docs): the group it begins or goes on in keeps it; + /// else it ends here. + pub(crate) open: Option, +} + +/// A render pass instance a render encoder left open at its end in its group's tail, for the +/// next render encoder to continue (**Continued passes** in the module docs). +pub(crate) struct OpenPass { + device: Device, + /// The tail, recording inside the instance. + raw: vk::CommandBuffer, + /// What the instance renders. + key: Arc, +} + +impl OpenPass { + /// The instance `raw` records inside, which renders what `key` says. + pub(crate) fn new(device: &Device, raw: vk::CommandBuffer, key: Arc) -> OpenPass { + OpenPass { + device: device.clone(), + raw, + key, + } + } + + /// What it renders. + pub(crate) fn key(&self) -> &Arc { + &self.key + } + + /// The tail it records inside. + pub(crate) fn raw(&self) -> vk::CommandBuffer { + self.raw + } + + /// End it: `vkCmdEndRenderPass` into the tail. + pub(crate) fn end(self) { + // SAFETY: the tail is recording inside the instance, and only the caller records it now + // (the command buffer's state lock, or the encoder that holds its group). + unsafe { self.device.shared().vk().cmd_end_render_pass(self.raw) }; + } } diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 61fde4483..e2ee6c4a1 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -1948,6 +1948,10 @@ pub(crate) struct RenderLowering { unreadable: crate::pvrtc::ResidentUnreadable, /// Whether the pass's first instance records inline (`render/inline_first.rs`). inline: inline_first::Inline, + /// Where its first instance waits to continue the render pass instance its command buffer's + /// tail holds open, its draws kept until the pass's end (`encoder_fold.rs`'s **Continued + /// passes**): the instances planned meanwhile, recorded after it (`render/inline_splits.rs`). + continuing: Option>, /// What the draws recorded inline into the pass's command buffer bound there, in its every /// render pass instance (`render/inline_splits.rs`). held_bound: Bound, @@ -2345,7 +2349,10 @@ impl CommandBuffer { device.shared().textures.held.holds(key) }); let joining = (log.is_some() && rate_map.is_none() && groups == 1 && !held_attachment) - .then_some(super::encoder_fold::Joining::Render { joins: !inline }); + .then_some(super::encoder_fold::Joining::Render { + joins: !inline, + continues: inline, + }); // A refusal past here leaves the secondary command buffer unused, freed with the pool. let mut core = match again { None => EncoderCore::open(self, CALL, EncoderKind::Render, (false, joining), |_| ())?.0, @@ -2652,6 +2659,7 @@ impl RenderLowering { None => inline_first::Inline::Never, }, held_bound: Bound::default(), + continuing: None, again: draw_again::DrawAgain::default(), grouped, pinned_through: 0, @@ -4654,6 +4662,22 @@ impl RenderLowering { // The last instance recorded inline after a split, its commands still kept: recorded // now, before the pass's plan of the instances after it (`render/inline_splits.rs`). self.flush_inline()?; + // What its one render pass instance renders, recorded inline, where it touched nothing + // but its attachments: it may stay open at the pass's end for the next render encoder to + // continue, where nothing records after it (`encoder_fold.rs`'s **Continued passes**). + let open_key = match &self.inline { + inline_first::Inline::Begun(begun) + if self.earlier.is_empty() + && !self.core.device().shared().splits_at_aliases + && self.first_touches_attachments_alone(None) => + { + Some(Arc::new(render_target::PassKey::of( + &begun.shape, + &begun.framebuffer, + ))) + } + _ => None, + }; // Whether a command of the pass may read an attachment's bytes it did not name. let unnamed_reads = self.barrier_inside || self.reaches_unnamed || !self.executions.is_empty(); @@ -6420,6 +6444,7 @@ impl RenderLowering { // An inline first instance's steps before it go before the pass, into the command buffer // before the pass's, as the end records them before the pass's first instance; the // encoder then records on in the pass's, after that instance (`render/inline_first.rs`). + let (mut open_key, mut left_open) = (open_key, false); if inline { if steps .instances @@ -6433,7 +6458,27 @@ impl RenderLowering { unsafe { steps.before(raw, command_buffer, 0) } }); } - core.release_pass()?; + // Its one instance stays open where nothing records after it: no step after it or at + // the pass's end, no copy or merge of a stand-in, visibility result or tile dispatch + // (`encoder_fold.rs`'s **Continued passes**). + let quiet_after = count == 1 + && inlined == 1 + && inline_moved.is_empty() + && results.is_none() + && executions.is_empty() + && pending.is_empty() + && tiles_made.as_ref().is_some_and(|tiles| tiles.is_empty()) + && stand_ins_after_first.is_none() + && kept_after_first.is_empty() + && backings_after_first.is_none() + && steps.records_nothing_after(0); + match open_key.take().filter(|_| quiet_after) { + Some(key) => { + core.leave_pass_open(key)?; + left_open = true; + } + None => core.release_pass()?, + } if !inline_moved.is_empty() { let family = core.queue_flags(); core.command(vk::PipelineStageFlags2::NONE, &[], |raw, command_buffer| { @@ -6475,7 +6520,11 @@ impl RenderLowering { Some(tiles) if executions.is_empty() && pending.is_empty() => Some(tiles), Some(_) | None => None, }; - if let Some(tiles) = now { + if let (Some(_), true) = (now, left_open) { + // Its uses noted, the closure below records nothing (`quiet_after`). + core.command_recording_nothing(render_target::ATTACHMENT_STAGES, &uses); + recorded_steps = Some(steps); + } else if let Some(tiles) = now { core.command( render_target::ATTACHMENT_STAGES, &uses, diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index d9cf340b1..7fb2bf8e9 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -3355,6 +3355,7 @@ impl RenderExecution { unreadable: Default::default(), inline: super::inline_first::Inline::Never, held_bound: Default::default(), + continuing: None, again: Default::default(), // No pass of several color groups executes render commands // (`render/color_groups.rs`). diff --git a/crates/metal2vulkan-runtime/src/render/inline_first.rs b/crates/metal2vulkan-runtime/src/render/inline_first.rs index e37190ee0..70bd9b3d2 100644 --- a/crates/metal2vulkan-runtime/src/render/inline_first.rs +++ b/crates/metal2vulkan-runtime/src/render/inline_first.rs @@ -229,6 +229,24 @@ pub(super) struct InlineBegin { splits: bool, /// The extent its render area and framebuffer cover ([`inline_area`]). area: [u32; 2], + /// It renders what the render pass instance its command buffer's tail holds open renders, + /// loading every attachment: its draws are kept, to record into that instance where the + /// pass may continue it (`encoder_fold.rs`'s **Continued passes**). + continues: bool, +} + +/// Whether every attachment of `layout`, each color and each aspect of its depth/stencil +/// attachment it names, loads with `Load`: a pass whose first instance may continue a render pass +/// instance left open (`encoder_fold.rs`'s **Continued passes**), which loads nothing. +fn loads_all(layout: &PassLayout) -> bool { + let colors = layout.colors.iter().flatten().map(|color| color.load); + let aspects = (layout.depth_stencil.iter()).flat_map(|ds| { + ds.depth + .iter() + .map(|d| d.load) + .chain(ds.stencil.iter().map(|s| s.load)) + }); + colors.chain(aspects).all(|load| load == LoadAction::Load) } /// Whether a pass of `layout` on `device`, rate-mapped where `rate_mapped` says, with the @@ -546,14 +564,25 @@ impl RenderLowering { let views = instance.views; let framebuffer = render_target::framebuffer_over(device, &pass, &self.layout, shape, views, none, area)?; + // Where the render pass instance its command buffer's tail holds open renders what this + // one would, and the pass loads every attachment, its draws may go on in that instance + // (`encoder_fold.rs`'s **Continued passes**); else the group that holds it closes now. + let continues = (self.core.continuable()).is_some_and(|open| { + *open == render_target::PassKey::of(shape, &framebuffer) && loads_all(&self.layout) + }); + let shape = instance.shape.clone(); + if !continues { + self.core.let_go_of_group(); + } let held = self.core.hold_pass()?; Ok(Some(InlineBegin { pass, framebuffer, held, - shape: instance.shape.clone(), + shape, splits, area, + continues, })) } @@ -568,8 +597,10 @@ impl RenderLowering { held, shape, splits, - area: [width, height], + area, + continues, } = begin; + let [width, height] = area; let shared = self.core.device().shared(); let raw = shared.vk(); if self.current.draws != vk::CommandBuffer::null() { @@ -580,6 +611,28 @@ impl RenderLowering { shared.counts.unrun_instance_ended(); } } + // Its draws kept, to record into the render pass instance its command buffer's tail holds + // open, or into one of its own begun then (`render/inline_splits.rs`), at its first split + // or its end. + if continues { + let objects = (pass.raw, framebuffer.raw); + self.current.draws = vk::CommandBuffer::null(); + self.current.inline = true; + let room = &shared.kept_rooms; + self.current.kept = Some(super::inline_splits::Kept::first(room, objects, area)); + self.current.rerecord = None; + self.continuing = Some(Box::default()); + self.inline = Inline::Begun(Box::new(Begun { + pass, + framebuffer, + shape, + splits, + later: Vec::new(), + stood: 0, + })); + shared.counts.inline_pass(); + return; + } let clear_values = render_target::clear_values(&self.layout); let info = vk::RenderPassBeginInfo::default() .render_pass(pass.raw) diff --git a/crates/metal2vulkan-runtime/src/render/inline_splits.rs b/crates/metal2vulkan-runtime/src/render/inline_splits.rs index 3699394ac..574b5a557 100644 --- a/crates/metal2vulkan-runtime/src/render/inline_splits.rs +++ b/crates/metal2vulkan-runtime/src/render/inline_splits.rs @@ -121,6 +121,19 @@ pub(super) struct Kept { /// begins and back right after it ends (`render_target::moved_images`); none for an instance /// of no such color. moved: Vec, + /// It is the pass's first instance, kept to continue the render pass instance its command + /// buffer's tail holds open (`encoder_fold.rs`'s **Continued passes**): the extent its own + /// render pass instance renders over from the origin, where it begins one. + first: Option<[u32; 2]>, +} + +/// The instances of a pass whose first instance waits to continue the render pass instance its +/// command buffer's tail holds open (`Kept::first`), planned while it waits, each with its +/// copies, in order: at its index among the pass's earlier instances, or the current one +/// (`None`). Recorded after the first, at the pass's end. +#[derive(Default)] +pub(super) struct Waiting { + later: Vec<(Option, Vec)>, } /// Where a [`Kept`] keeps its draws and commands, which the device keeps once its pass ended @@ -196,6 +209,29 @@ enum KeptCommand { } impl Kept { + /// The pass's first instance, kept to continue the render pass instance its command buffer's + /// tail holds open (`encoder_fold.rs`'s **Continued passes**), in a room of `rooms`'; where it + /// begins one of its own, it does in `objects` over `area` from the origin. + pub(super) fn first( + rooms: &SpareKept, + objects: (vk::RenderPass, vk::Framebuffer), + area: [u32; 2], + ) -> Kept { + Kept { + room: rooms.take(), + draws: 0, + objects, + clears: None, + moved: Vec::new(), + first: Some(area), + } + } + + /// Whether it is the pass's first instance, kept to continue an open one ([`Kept::first`]). + pub(super) fn is_first(&self) -> bool { + self.first.is_some() + } + /// Its colors in the feedback loop layout, which move back to `GENERAL` right after its render /// pass instance ends. pub(super) fn moved(&self) -> &[MovedImage] { @@ -434,7 +470,7 @@ impl RenderLowering { clears, moved, } = begin; - self.record_flushed(before, &copies); + self.flush_planned(Some(before), copies); let device = self.core.device().clone(); self.current.inline = true; self.current.kept = Some(Kept { @@ -443,6 +479,7 @@ impl RenderLowering { objects, clears, moved, + first: None, }); self.current.rerecord = None; device.shared().counts.inline_split_instance(); @@ -455,20 +492,117 @@ impl RenderLowering { let waiting = |instance: &Instance| instance.kept.is_some() && !instance.planned; if waiting(&self.current) { let copies = self.plan_one(None)?; - let bound = &mut self.held_bound; - let ended = ended_moves(self.earlier.last()); - let kept = (&self.current, &copies[..], ended); - record_kept(&mut self.core, bound, kept, &self.layout); - self.current.planned = true; - return Ok(()); - } - if let Some(at) = self.earlier.iter().position(waiting) { + self.flush_planned(None, copies); + } else if let Some(at) = self.earlier.iter().position(waiting) { let copies = self.plan_one(Some(at))?; - self.record_flushed(at, &copies); + self.flush_planned(Some(at), copies); + } + // The pass's first instance, waiting to continue the render pass instance its command + // buffer's tail holds open, and the instances planned after it. + if let Some(waiting) = self.continuing.take() { + self.record_waiting(*waiting); } Ok(()) } + /// Whether the pass's first instance, at `at` among its earlier instances or the current one + /// (`None`), touched nothing but its attachments as attachments, so it may continue a render + /// pass instance whose draws touched nothing else either (`encoder_fold.rs`'s **Continued + /// passes**): no draw wrote memory or used the attachments' images or bytes another way, and + /// no command of the pass reached memory it does not name (a memory barrier inside it, a root + /// or handle table, a heap, an execution of render commands), recorded later (a draw whose + /// pipeline is being made) or dispatched tiles. + pub(super) fn first_touches_attachments_alone(&self, at: Option) -> bool { + let instance = at.map_or(&self.current, |at| &self.earlier[at]); + let Ok(attached) = render_target::attachment_uses(&self.layout) else { + return false; + }; + !self.barrier_inside + && !self.reaches_unnamed + && self.executions.is_empty() + && self.pending.is_empty() + && !self.dispatched + && !self.core.reached_heaps() + && (instance.shadows).touches_alone(self.core.device(), &attached) + } + + /// Record the earlier instance at `at`, or the current one (`None`), whose copies `copies` + /// were just planned, and mark it planned: the pass's first instance recorded inline as its + /// draws came takes its copies before the pass; one kept after a split, between the instance + /// before it and it, with its kept commands; one that waits to continue the render pass + /// instance its command buffer's tail holds open (`Kept::first`) waits on where it has no + /// copy or step before it and touched nothing but its attachments, else records as the + /// pass's own first instance now; and every instance planned while it waits waits with it. + fn flush_planned(&mut self, at: Option, copies: Vec) { + let instance = at.map_or(&self.current, |at| &self.earlier[at]); + let first = (instance.kept.as_ref()).is_some_and(Kept::is_first); + if first { + let waits = copies.is_empty() + && instance.before.is_empty() + && self.first_touches_attachments_alone(at); + if !waits { + self.continuing = None; + self.core.let_go_of_group(); + // Its copies before the pass, as the pass's first instance's go. + self.core.shadow_copies(&copies); + let instance = at.map_or(&self.current, |at| &self.earlier[at]); + record_first(&mut self.core, &mut self.held_bound, instance, true); + } + } else if let Some(waiting) = self.continuing.as_mut() { + waiting.later.push((at, copies)); + } else if instance.kept.is_none() { + // The pass's first instance: its copies go before the pass, into the command buffer + // before the pass's, as the pass's end records them before its first instance. + self.core.shadow_copies(&copies); + } else { + let before = match at { + Some(at) => at.checked_sub(1).map(|before| &self.earlier[before]), + None => self.earlier.last(), + }; + let (bound, ended) = (&mut self.held_bound, ended_moves(before)); + record_kept( + &mut self.core, + bound, + (instance, &copies, ended), + &self.layout, + ); + } + match at { + Some(at) => self.earlier[at].planned = true, + None => self.current.planned = true, + } + } + + /// Record the pass's first instance, which waited to continue the render pass instance its + /// command buffer's tail holds open (`Kept::first`), and the instances planned after it, + /// `waiting`, in order: into that instance with no end, barrier or begin between, where the + /// pass continues it (`EncoderCore::continue_pass`), its draws still touching nothing but its + /// attachments; else into a render pass instance of its own, begun in the pass's own command + /// buffer, the group that held the open one closed. + fn record_waiting(&mut self, waiting: Waiting) { + let at = (!self.earlier.is_empty()).then_some(0); + let continues = self.first_touches_attachments_alone(at) && self.core.continue_pass(); + if !continues { + self.core.let_go_of_group(); + } + let first = at.map_or(&self.current, |at| &self.earlier[at]); + record_first(&mut self.core, &mut self.held_bound, first, !continues); + for (at, copies) in waiting.later { + let instance = at.map_or(&self.current, |at| &self.earlier[at]); + let before = match at { + Some(at) => at.checked_sub(1).map(|before| &self.earlier[before]), + None => self.earlier.last(), + }; + let (bound, ended) = (&mut self.held_bound, ended_moves(before)); + record_kept( + &mut self.core, + bound, + (instance, &copies, ended), + &self.layout, + ); + } + } + /// The copies before the head of a group, the current instance (`at` `None`) or the earlier /// one at `at`, through the encoder's shadowed textures, as the pass's end plans them for it /// (`shadows::plan`). Its writes of the colors the pass loads are bounded by its draws' @@ -517,27 +651,6 @@ impl RenderLowering { )?; Ok(planned.into_iter().next().unwrap_or_default()) } - - /// Record the copies `copies` planned for the earlier instance at `at`, and mark it - /// planned: before the pass for the pass's first instance, recorded inline as its draws - /// came; else between the instance before it and it, with its kept commands. - fn record_flushed(&mut self, at: usize, copies: &[ShadowCopy]) { - if self.earlier[at].kept.is_none() { - // The pass's first instance: its copies go before the pass, into the command buffer - // before the pass's, as the pass's end records them before its first instance. - self.core.shadow_copies(copies); - } else { - let (bound, instance) = (&mut self.held_bound, &self.earlier[at]); - let ended = ended_moves(at.checked_sub(1).map(|before| &self.earlier[before])); - record_kept( - &mut self.core, - bound, - (instance, copies, ended), - &self.layout, - ); - } - self.earlier[at].planned = true; - } } /// Whether `shape`, a new instance's, is `first`'s, the pass's first instance's, but for the @@ -642,7 +755,6 @@ fn record_kept( extent: vk::Extent2D { width, height }, }) .clear_values(clear_values.as_slice()); - let mut recorded = Recorded::default(); // SAFETY: the held command buffer is recording outside a render pass instance, and only this // encoder records it; the steps' objects are live until it completes (retained at their // draws); the pass and framebuffer are live until it completes (the encoder holds them to its @@ -661,6 +773,74 @@ fn record_kept( raw.cmd_begin_render_pass(held, &info, vk::SubpassContents::INLINE); let begun = crate::work_counts::PassBegun::InlineSplit; shared.counts.render_pass_begun(begun); + record_kept_commands(shared, held, kept, bound); + } +} + +/// Record the pass's first instance, kept to continue the render pass instance its command +/// buffer's tail holds open (`Kept::first`), into the pass's command buffer: into that +/// instance, which the pass holds once it continued it (`EncoderCore::continue_pass`), or into a +/// render pass instance of its own, begun there in its render pass and framebuffer over its area +/// (`begins`); its commands through `bound`, the record of what the command buffer bound, which +/// is nothing where it continues another encoder's instance (the encoder's own record). Its +/// copies and steps before it went before the pass, where it had any: it continues no instance +/// then. +fn record_first(core: &mut EncoderCore, bound: &mut Bound, instance: &Instance, begins: bool) { + let (Some(held), Some(kept)) = (core.held_pass(), instance.kept.as_ref()) else { + return; + }; + let Some([width, height]) = kept.first else { + return; + }; + let device = core.device().clone(); + let shared = device.shared(); + let raw = shared.vk(); + if begins { + let (pass, framebuffer) = kept.objects; + // It loads every attachment (`inline_first::loads_all`): no clear value is read. + let info = vk::RenderPassBeginInfo::default() + .render_pass(pass) + .framebuffer(framebuffer) + .render_area(vk::Rect2D { + offset: vk::Offset2D { x: 0, y: 0 }, + extent: vk::Extent2D { width, height }, + }); + // SAFETY: the held command buffer, the encoder's own, is recording outside a render pass + // instance, and only this encoder records it; the pass and framebuffer are live until it + // completes (the encoder holds them to its end, which retains them), the render area is + // the framebuffer's extent, and every image rests in `GENERAL`. + unsafe { raw.cmd_begin_render_pass(held, &info, vk::SubpassContents::INLINE) }; + shared + .counts + .render_pass_begun(crate::work_counts::PassBegun::Inline); + } + // SAFETY: the held command buffer is recording inside a render pass instance of a render pass + // compatible with every kept draw's pipeline (made for the instance's shape, as the open + // instance's is: `render_target::PassKey`), over the same attachments, and only this encoder + // records it; every kept draw's objects are live until the command buffer completes + // (retained at the draw), and `bound` is the record of what the draws recorded into it bound: + // the encoder's own, of nothing recorded before its first draw. + unsafe { record_kept_commands(shared, held, kept, bound) }; +} + +/// Record `kept`'s commands into `held`, through `bound`. +/// +/// # Safety +/// +/// `held` is recording inside a render pass instance its kept draws' pipelines are compatible +/// with, of the instance's attachments, and only the caller records it; the kept draws' objects +/// are live until it completes, and `bound` is the record of what the draws recorded into it +/// bound. +unsafe fn record_kept_commands( + shared: &crate::device::DeviceShared, + held: vk::CommandBuffer, + kept: &Kept, + bound: &mut Bound, +) { + let raw = shared.vk(); + let mut recorded = Recorded::default(); + // SAFETY: the caller's. + unsafe { let mut draws = kept.room.recordings[..kept.draws].iter(); for command in &kept.room.commands { match command { diff --git a/crates/metal2vulkan-runtime/src/render/pass_steps.rs b/crates/metal2vulkan-runtime/src/render/pass_steps.rs index 1d00ae996..9d35a8d42 100644 --- a/crates/metal2vulkan-runtime/src/render/pass_steps.rs +++ b/crates/metal2vulkan-runtime/src/render/pass_steps.rs @@ -359,6 +359,24 @@ impl PassSteps { } } + /// Whether [`after`](Self::after) records nothing after instance `index`, nor + /// [`end`](Self::end) after the pass's instances: what a pass whose one instance may stay open + /// for the next render encoder asks (`encoder_fold.rs`'s **Continued passes**). Each check is + /// one those record by. + pub(super) fn records_nothing_after(&self, index: usize) -> bool { + let instance = self.instances.get(index); + let reformat = instance.is_some_and(|i| i.reformat_out.is_some()); + let shadow = instance.is_some_and(|i| i.shadow) && self.shadow_copies.is_some(); + let tests = instance.is_some_and(|i| i.shader_tests) && self.stand_in_copies.is_some(); + let pins = (self.after_pins.as_ref()).is_some_and(|pins| pins.at == index); + let dispatches = (self.dispatches.iter()).any(|s| s.dispatch.after == index + 1); + let end = self.planes.is_some() + || self.resolve_source.is_some() + || self.resolve_instance.is_some() + || !self.later_resolves.is_empty(); + !(reformat || shadow || tests || pins || dispatches || end) + } + /// Record the copies back that go after instance `index` (the module docs), once it ended: /// all of [`after`](Self::after) but the tile dispatches. A pass that records later records /// these after its instances recorded inline as the encoder ends, and their dispatches with its diff --git a/crates/metal2vulkan-runtime/src/render/shadows.rs b/crates/metal2vulkan-runtime/src/render/shadows.rs index 56e092809..2f14d4b20 100644 --- a/crates/metal2vulkan-runtime/src/render/shadows.rs +++ b/crates/metal2vulkan-runtime/src/render/shadows.rs @@ -457,6 +457,25 @@ impl InstanceShadows { writes.iter().any(|used| copies.meets(used)) } + /// Whether its draws touched nothing but `attached`, a pass's attachments' uses, as + /// attachments (`encoder_fold.rs`'s **Continued passes**): they wrote nothing (no storage + /// write, and none through a shadowed texture), and used none of the attachments' images or + /// bytes, through the device's aliases of them too (a buffer over the same host pages). + pub(super) fn touches_alone(&self, device: &Device, attached: &[Use]) -> bool { + if self.shadows.iter().any(|shadow| shadow.writes) { + return false; + } + let uses: Vec> = self.uses().collect(); + if uses.iter().any(|used| !used.write.is_empty()) { + return false; + } + let aliases = &device.shared().aliases; + let (uses_aliased, attached_aliased) = (aliases.augment(&uses), aliases.augment(attached)); + let uses = uses_aliased.as_deref().unwrap_or(&uses); + let attached = attached_aliased.as_deref().unwrap_or(attached); + !(uses.iter()).any(|used| attached.iter().any(|a| a.key == used.key)) + } + /// How many uses [`uses`](Self::uses) gives. fn uses_len(&self) -> usize { let bytes: usize = self.held().iter().map(|(_, ranges)| ranges.len()).sum(); diff --git a/crates/metal2vulkan-runtime/src/render_target.rs b/crates/metal2vulkan-runtime/src/render_target.rs index 4d8b9b299..4f1532c84 100644 --- a/crates/metal2vulkan-runtime/src/render_target.rs +++ b/crates/metal2vulkan-runtime/src/render_target.rs @@ -649,6 +649,41 @@ pub(super) struct FramebufferObject { device: Device, pub(super) raw: vk::Framebuffer, placeholders: Vec>, + /// Its attachments' views, in its order, its extent and its layers: what a render pass + /// instance begun in it renders ([`PassKey`]). + views: Vec, + extent: [u32; 2], + layers: u32, +} + +/// What a render pass instance renders, for a later pass that continues it +/// (`encoder_fold.rs`'s **Continued passes**): the shape its render pass and pipelines are +/// compatible by, its framebuffer's views, which name the images, levels and layers it renders, +/// in order, and its framebuffer's extent and layers, which its render area covers from the +/// origin. Two instances of equal keys render the same subresources of the same images through +/// compatible render passes ("Two render passes are compatible if their corresponding color, +/// input, resolve, and depth/stencil attachment references are compatible and if they are +/// otherwise identical except for: Initial and final image layout in attachment descriptions; +/// Load and store operations in attachment descriptions; Image layout in attachment references", +/// Render Pass Compatibility), so a draw recorded against the one's records against the other's. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct PassKey { + shape: PassShape, + views: Vec, + extent: [u32; 2], + layers: u32, +} + +impl PassKey { + /// The key of an instance of `shape` begun in `framebuffer` over its whole extent. + pub(super) fn of(shape: &PassShape, framebuffer: &FramebufferObject) -> PassKey { + PassKey { + shape: shape.clone(), + views: framebuffer.views.clone(), + extent: framebuffer.extent, + layers: framebuffer.layers, + } + } } impl Drop for FramebufferObject { @@ -2334,6 +2369,9 @@ fn made_framebuffer( device: device.clone(), raw, placeholders: Vec::new(), + views: attachments.to_vec(), + extent: [width, height], + layers, }) } diff --git a/crates/metal2vulkan-runtime/src/tests/render_fold.rs b/crates/metal2vulkan-runtime/src/tests/render_fold.rs index e592da03a..267193333 100644 --- a/crates/metal2vulkan-runtime/src/tests/render_fold.rs +++ b/crates/metal2vulkan-runtime/src/tests/render_fold.rs @@ -1,7 +1,9 @@ //! Render encoders in groups of encoders recorded into one `VkCommandBuffer` (`encoder_fold.rs`, //! **Render encoders**): one whose pass records at its end joins the group before it, one whose //! first instance records inline only begins one, each after one barrier from everything of the -//! group's earlier encoders, and what a pass leaves for later ends the group after it. A render +//! group's earlier encoders, and what a pass leaves for later ends the group after it; one whose +//! first instance records inline over what the render pass instance the group left open renders +//! continues that instance (**Continued passes**). A render //! encoder takes a group only with a log of its calls, which the device keeps where it has a //! buffer over host pages: each lane but [`a_render_encoder_without_a_log_takes_no_group`] makes //! one first. @@ -404,6 +406,202 @@ fn a_render_encoder_that_records_inline_begins_a_group_and_joins_none() { ); } +/// What moved of the counts a continued render pass instance names (`encoder_fold.rs`'s +/// **Continued passes**). +#[derive(Debug, PartialEq, Eq)] +struct Continued { + /// `render_passes_begun_inline`. + begun: u64, + /// `render_passes_continued`. + continued: u64, + /// `commands_recorded.cmd_begin_render_pass`. + begins: u64, + /// `command_buffers_submitted`. + submitted: u64, +} + +impl Continued { + fn of(before: &WorkCounts, after: &WorkCounts) -> Continued { + Continued { + begun: after.render_passes_begun_inline - before.render_passes_begun_inline, + continued: after.render_passes_continued - before.render_passes_continued, + begins: after.commands_recorded.cmd_begin_render_pass + - before.commands_recorded.cmd_begin_render_pass, + submitted: after.command_buffers_submitted - before.command_buffers_submitted, + } + } +} + +/// A `Shared` buffer of the colors of every vertex the quad takes, each `color`. +fn colored(lane: &Lane, color: [f32; 4]) -> Buffer { + floats(&lane.device, (0..VERTICES).flat_map(|_| color)) +} + +/// [`STEPS`] render encoders over one target, the first clearing it and the rest loading it, +/// each storing it and drawing the quad over all of it in a color of its own, the last +/// [`DRAWN`]: each after the first continues the first's render pass instance, which begins +/// once, and the texels are the last draw's, as Metal's passes in order leave them. Without the +/// continuation each encoder begins an instance of its own, in a `VkCommandBuffer` of its own. +#[test] +fn render_encoders_over_one_target_continue_one_render_pass_instance() { + let scratch = Scratch::new("render-fold-continued"); + let Some(lane) = Lane::at_call(&scratch) else { + return; + }; + let queue = lane.device.new_command_queue().unwrap(); + let target = lane.target(); + let back = lane.back(); + let colors: Vec = (0..STEPS - 1) + .map(|step| colored(&lane, [0.0, 0.1 * step as f32, 1.0, 1.0])) + .chain([lane.colors.clone()]) + .collect(); + let before = lane.device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + for (step, colors) in colors.iter().enumerate() { + let load = match step { + 0 => LoadAction::Clear, + _ => LoadAction::Load, + }; + lane.draw(&command_buffer, &target, load, colors); + } + lane.copy_back(&command_buffer, &target, &back); + run(&command_buffer); + let continued = Continued::of(&before, &lane.device.work_counts()); + let wrong = wrong_texels(&back); + println!("RENDER-FOLD-CONTINUED {continued:?} wrong texels {wrong}"); + assert_eq!(wrong, 0, "every texel is the last draw's"); + assert_eq!( + (continued.begun, continued.continued, continued.begins), + (1, STEPS - 1, 1), + "one render pass instance began, every later encoder continued it: {continued:?}" + ); + assert!( + continued.submitted < STEPS, + "the encoders went out in fewer command buffers than one each: {continued:?}" + ); +} + +/// The same chain with a compute encoder after its third render encoder, which writes the +/// colors the fourth draws with: the compute encoder joins the group and ends the open render +/// pass instance first, the fourth render encoder begins one of its own, which the rest continue, +/// and every texel is the last draw's: the colors the dispatch wrote. +#[test] +fn a_dispatch_between_render_encoders_ends_the_continued_instance() { + let scratch = Scratch::new("render-fold-continued-dispatch"); + let Some(lane) = Lane::at_call(&scratch) else { + return; + }; + let queue = lane.device.new_command_queue().unwrap(); + let target = lane.target(); + let back = lane.back(); + let written = lane.zeros(COLOR_WORDS); + let blue = colored(&lane, [0.0, 0.0, 1.0, 1.0]); + let before = lane.device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + for _ in 0..3 { + lane.draw(&command_buffer, &target, LoadAction::Load, &blue); + } + lane.dispatch(&command_buffer, &written); + for _ in 0..3 { + lane.draw(&command_buffer, &target, LoadAction::Load, &written); + } + lane.copy_back(&command_buffer, &target, &back); + run(&command_buffer); + let continued = Continued::of(&before, &lane.device.work_counts()); + let wrong = wrong_texels(&back); + println!("RENDER-FOLD-CONTINUED-DISPATCH {continued:?} wrong texels {wrong}"); + assert_eq!( + wrong, 0, + "every texel is the last draw's, of the dispatch's colors" + ); + assert_eq!( + (continued.begun, continued.continued, continued.begins), + (2, 4, 2), + "the dispatch ended the first instance: {continued:?}" + ); +} + +/// Render encoders that continue one render pass instance, committed behind an event wait only +/// the host signals, the last drawing with colors from a buffer over host pages that is rebound +/// before the signal: the rebind encodes the group again, each encoder apart, refusing none, and +/// the last draw takes its colors from the new pages (`encoder_fold.rs`'s **Encoded again**). +#[test] +fn a_rebind_encodes_continued_render_encoders_again() { + // Declared before the lane, so dropped after it. + let pages = [Page::new(), Page::new()]; + let scratch = Scratch::new("render-fold-continued-rebind"); + let Some(lane) = Lane::at_call(&scratch) else { + return; + }; + let queue = lane.device.new_command_queue().unwrap(); + let target = lane.target(); + let words: Vec = (0..VERTICES) + .flat_map(|_| DRAWN) + .flat_map(f32::to_le_bytes) + .collect(); + pages[1].write(&words); + // SAFETY: each page outlives every buffer over it (dropped after the lane), and only the + // buffer's commands use it while it lives. + let colors = unsafe { + lane.device.new_buffer_with_bytes_no_copy( + pages[0].memory(), + BYTES as u64, + ResourceOptions::shared(), + None, + ) + } + .unwrap(); + let blue = colored(&lane, [0.0, 0.0, 1.0, 1.0]); + let gate = lane.device.new_shared_event().unwrap(); + let before = lane.device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + command_buffer + .encode_wait_for_event(EventRef::Shared(&gate), 1) + .unwrap(); + lane.draw(&command_buffer, &target, LoadAction::Load, &blue); + lane.draw(&command_buffer, &target, LoadAction::Load, &blue); + lane.draw(&command_buffer, &target, LoadAction::Load, &colors); + command_buffer.commit().unwrap(); + assert_eq!(colors.detach_backing(), Ok(true)); + // SAFETY: as above. + unsafe { colors.rebind_bytes_no_copy(pages[1].memory(), None, None) }.unwrap(); + // Read before the signal: the rebind encodes again in its own call. + let after = lane.device.work_counts(); + gate.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!( + command_buffer.status(), + CommandBufferStatus::Completed, + "{:?}", + command_buffer.error() + ); + let back = lane.back(); + let copy = queue.command_buffer().unwrap(); + lane.copy_back(©, &target, &back); + run(©); + let continued = after.render_passes_continued - before.render_passes_continued; + let reencoded = after.encoders_reencoded - before.encoders_reencoded; + let refused = after.reencodes_refused - before.reencodes_refused; + println!( + "RENDER-FOLD-CONTINUED-REBIND continued {continued} reencoded {reencoded} refused \ + {refused}" + ); + assert_eq!( + continued, 2, + "both later encoders continued the first's instance" + ); + assert_eq!( + (reencoded, refused), + (3, 0), + "the rebind encoded the group's three encoders again" + ); + assert_eq!( + wrong_texels(&back), + 0, + "the last draw took its colors from the new pages" + ); +} + /// On a device with no buffer over host pages a render encoder logs no call, so it takes no /// group: the compute encoder's, its own and the copy's `VkCommandBuffer`s, as before. #[test] diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index d5929309f..651825850 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -414,6 +414,7 @@ pub(crate) struct Counters { encoders_none_kept_next: [AtomicU64; NoneKeptNext::COUNT], encoders_last_draw_empty: AtomicU64, inline_split_instances: AtomicU64, + render_passes_continued: AtomicU64, inline_memoryless_write_splits: AtomicU64, passes_not_inline: [AtomicU64; NotInline::COUNT], passes_not_inline_actions_by: [AtomicU64; ActionsRefused::COUNT], @@ -4107,6 +4108,12 @@ impl Counters { self.inline_split_instances.fetch_add(1, Ordering::Relaxed); } + /// A render encoder's first instance recorded into the render pass instance the encoder + /// before it left open (`encoder_fold.rs`, **Continued passes**). + pub(crate) fn render_pass_continued(&self) { + self.render_passes_continued.fetch_add(1, Ordering::Relaxed); + } + /// A pass whose first instance recorded inline split before a draw that writes a memoryless /// color attachment, which no instance recorded inline writes (`render/inline_first.rs`). pub(crate) fn inline_memoryless_write_split(&self) { @@ -8421,6 +8428,11 @@ pub struct WorkCounts { pub render_passes_begun_inline_splits: u64, /// Instances of no draws that resolve a pass after its last (`render/pass_steps.rs`). pub render_passes_begun_resolves: u64, + /// Render encoders' first instances recorded into the render pass instance the render + /// encoder before them left open, with no end, barrier or begin between: one Vulkan render + /// pass instance for both encoders' draws (`encoder_fold.rs`, **Continued passes**). None + /// of the begun fields counts them. + pub render_passes_continued: u64, /// Splits of render encoders' passes, each a new render pass instance after one that /// recorded, or that runs the pass's load actions alone (`render.rs`, **Instances**), at a /// memory barrier of the program's (`fence.rs`). @@ -12235,6 +12247,7 @@ impl Device { render_passes_begun_inline: pass_begun(PassBegun::Inline), render_passes_begun_inline_splits: pass_begun(PassBegun::InlineSplit), render_passes_begun_resolves: pass_begun(PassBegun::Resolve), + render_passes_continued: counters.render_passes_continued.load(Ordering::Relaxed), instance_splits_barrier: split(Split::Barrier), instance_splits_tile_dispatch: split(Split::TileDispatch), instance_splits_tile_memory: split(Split::TileMemory), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/walk_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/walk_costs.rs index 1ecd28f86..711ec293b 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/walk_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/walk_costs.rs @@ -119,6 +119,8 @@ enum Kind { A, B, Reader, + /// A's state sampling the target, an area of which the pass renders (`walk_glass_frame`). + Area, } /// What draw R reads the target with. @@ -167,6 +169,9 @@ struct Workload { over_pages: Option<(Texture, Buffer)>, indices: Buffer, fence: Fence, + /// A visibility result buffer, which keeps a glass frame's passes from recording inline + /// ([`Form::Folded`]). + visibility: Buffer, chunk: Buffer, /// The host pages under `chunk` and under `over_pages`, which outlive them (dropped after /// them). @@ -309,6 +314,7 @@ impl Workload { over_pages, indices, fence: device.new_fence(), + visibility: device.new_buffer(4096, ResourceOptions::private()).unwrap(), chunk, _pages: pages, _target_pages: target_pages, @@ -413,7 +419,7 @@ impl Workload { slot: usize, ) { let state = match (kind, reader) { - (Kind::A, _) => &self.a, + (Kind::A | Kind::Area, _) => &self.a, (Kind::B, _) => &self.b, (Kind::Reader, Reader::Snapshot) => &self.reader, (Kind::Reader, Reader::Branch) => &self.branch, @@ -431,7 +437,7 @@ impl Workload { .set_fragment_buffer_offset((slot * SLOT + 128) as u64, 0) .unwrap(), Kind::Reader if reader == Reader::Fetch => {} - Kind::Reader => encoder.set_fragment_texture(Some(target), 0).unwrap(), + Kind::Reader | Kind::Area => encoder.set_fragment_texture(Some(target), 0).unwrap(), } encoder .set_vertex_buffer_offset((slot * SLOT) as u64, 0) @@ -722,6 +728,234 @@ fn walk_costs_frame_profiled() { ); } +/// What an encoder of a glass frame draws (`walk_glass_frame`): five draws each. +#[derive(Clone, Copy, PartialEq)] +enum Recipe { + /// A, B, A, B, B: no read of the target. + Plain, + /// A, B, a barrier, R through the reader, A, B. + Own(Reader), + /// A, B, a barrier, A's state sampling the target ([`Kind::Area`]), A, B. + Area, +} + +impl Recipe { + /// Its draws in order, and what a reader among them reads with. + fn draws(self) -> ([Kind; 5], Reader) { + match self { + Recipe::Plain => ( + [Kind::A, Kind::B, Kind::A, Kind::B, Kind::B], + Reader::Snapshot, + ), + Recipe::Own(reader) => (DRAWS, reader), + Recipe::Area => ( + [Kind::A, Kind::B, Kind::Area, Kind::A, Kind::B], + Reader::Snapshot, + ), + } + } +} + +/// The glass frames' untimed and counted frames. +const GLASS_WARM: usize = 5; +const GLASS_COUNTED: usize = 10; + +/// How a glass frame encodes its recipes (`walk_glass_frame`), to take an encoder's cost apart. +#[derive(Clone, Copy, PartialEq)] +enum Form { + /// An encoder each, between a fence wait and update. + Encoders, + /// An encoder each, with no fence. + NoFences, + /// An encoder each, between a fence wait and update, each pass with a visibility result + /// buffer: no pass records inline (`render/inline_first.rs`), so each records its draws in a + /// secondary at its end and joins the encoder before it (`encoder_fold.rs`). + Folded, + /// One encoder of every recipe's draws, between a fence wait and update. + OneEncoder, + /// [`Form::OneEncoder`] with a memory barrier over the render targets, fragment to fragment, + /// between one recipe's draws and the next's. + OneEncoderBarriers, +} + +impl Workload { + /// One glass frame (`walk_glass_frame`) into `target`: an encoder of each of `recipes`, in + /// one command buffer, each as [`encode`](Self::encode)'s between its fence wait and update, + /// committed with `commit_and_submit` and waited for. + fn encode_glass(&self, target: Target, recipes: &[Recipe], form: Form) -> Frame { + let target = self.target(target).unwrap(); + let command_buffer = self.queue.command_buffer().unwrap(); + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(target.clone()); + color.load_action = LoadAction::Load; + color.store_action = StoreAction::Store; + if form == Form::Folded { + pass.visibility_result_buffer = Some(self.visibility.clone()); + } + let one = matches!(form, Form::OneEncoder | Form::OneEncoderBarriers); + let fenced = form != Form::NoFences; + let open = || { + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + if fenced { + encoder + .wait_for_fence(&self.fence, RenderStages::FRAGMENT) + .unwrap(); + } + encoder + .set_fragment_sampler_state(Some(&self.sampler), 0) + .unwrap(); + encoder.set_vertex_buffer(Some(&self.chunk), 0, 0).unwrap(); + encoder + .set_fragment_buffer(Some(&self.chunk), 128, 0) + .unwrap(); + encoder + }; + let close = |mut encoder: RenderCommandEncoder| { + if fenced { + encoder + .update_fence(&self.fence, RenderStages::FRAGMENT) + .unwrap(); + } + encoder.end_encoding().unwrap(); + }; + let cpu_start = thread_cpu(); + let mut shared = one.then(open); + for (at, &recipe) in recipes.iter().enumerate() { + let (kinds, reader) = recipe.draws(); + let mut own = None; + let encoder = match &mut shared { + Some(encoder) => { + if form == Form::OneEncoderBarriers && at > 0 { + encoder.memory_barrier_with_scope( + BarrierScope::RENDER_TARGETS, + RenderStages::FRAGMENT, + RenderStages::FRAGMENT, + ); + } + encoder + } + None => own.insert(open()), + }; + let mut last = None; + for (n, &kind) in kinds.iter().enumerate() { + let slot = (at * kinds.len() + n) % SLOTS; + if matches!(kind, Kind::Reader | Kind::Area) { + encoder.memory_barrier_with_scope( + BarrierScope::RENDER_TARGETS, + RenderStages::FRAGMENT, + RenderStages::FRAGMENT, + ); + } + self.draw(encoder, (kind, reader), target, last != Some(kind), slot); + last = Some(kind); + } + if let Some(encoder) = own { + close(encoder); + } + } + if let Some(encoder) = shared { + close(encoder); + } + let cpu = thread_cpu().saturating_sub(cpu_start); + command_buffer.commit_and_submit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + let gpu = command_buffer.gpu_end_time().unwrap() - command_buffer.gpu_start_time().unwrap(); + Frame { + cpu, + commit: Duration::ZERO, + gpu, + } + } +} + +/// `walk_glass_frame`: a compositor's frame of a glass panel as the consumer's guest draws it, +/// [`FRAME_ENCODERS`] render encoders in one command buffer, each of five draws by a [`Recipe`]: +/// every encoder of one recipe, then the recipes in turn (`glass`); and the plain recipe's and the +/// mix's draws in the other [`Form`]s, which take an encoder's cost apart (its fences, its own +/// `VkCommandBuffer`, its pass). Printed per shape and target (`WALK-GLASS`): an encoder's render +/// pass instances, pipeline barriers and copies, and the GPU time a frame; and every work count a +/// frame moved (`WALK-MOVED`). +#[test] +#[ignore = "a measurement, not a check: run by name with --run-ignored all"] +fn walk_glass_frame() { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let work = workload(&cache, &messages); + let name = work.device.name().to_owned(); + let mix = [ + Recipe::Plain, + Recipe::Own(Reader::Snapshot), + Recipe::Own(Reader::Branch), + Recipe::Area, + ]; + let plain = [Recipe::Plain; FRAME_ENCODERS].to_vec(); + let glass: Vec = (0..FRAME_ENCODERS).map(|at| mix[at % mix.len()]).collect(); + let shapes = [ + ("plain", plain.clone(), Form::Encoders), + ("plain no fences", plain.clone(), Form::NoFences), + ("plain folded", plain.clone(), Form::Folded), + ("plain one encoder", plain.clone(), Form::OneEncoder), + ( + "plain one encoder barriers", + plain, + Form::OneEncoderBarriers, + ), + ( + "snapshot", + [mix[1]; FRAME_ENCODERS].to_vec(), + Form::Encoders, + ), + ("branch", [mix[2]; FRAME_ENCODERS].to_vec(), Form::Encoders), + ( + "area", + [Recipe::Area; FRAME_ENCODERS].to_vec(), + Form::Encoders, + ), + ("glass", glass.clone(), Form::Encoders), + ("glass folded", glass, Form::Folded), + ]; + for (target, place) in [ + (Target::OverPages, "over pages"), + (Target::Private, "private"), + ] { + if work.target(target).is_none() { + eprintln!("WALK-GLASS {name} {place}: the device imports no host memory"); + continue; + } + for (shape, recipes, form) in &shapes { + for _ in 0..GLASS_WARM { + work.encode_glass(target, recipes, *form); + } + let before = work.device.work_counts(); + let frames: Vec = (0..GLASS_COUNTED) + .map(|_| work.encode_glass(target, recipes, *form)) + .collect(); + let after = work.device.work_counts(); + let encoders = (GLASS_COUNTED * FRAME_ENCODERS) as f64; + let per = + |count: fn(&WorkCounts) -> u64| (count(&after) - count(&before)) as f64 / encoders; + let [_, gpu, _] = percentiles(frames.iter().map(|f| f.gpu * 1e3).collect()); + eprintln!( + "WALK-GLASS {name} {shape} {place}: an encoder {:.2} render pass instances, {:.2} \ + pipeline barriers, {:.2} image copies, {:.2} buffer-image copies, {:.2} \ + executed secondaries; a frame {gpu:.2} ms of GPU", + per(|c| c.commands_recorded.cmd_begin_render_pass), + per(|c| c.commands_recorded.cmd_pipeline_barrier), + per(|c| c.commands_recorded.cmd_copy_image), + per(|c| { + c.commands_recorded.cmd_copy_buffer_to_image + + c.commands_recorded.cmd_copy_image_to_buffer + }), + per(|c| c.commands_recorded.cmd_execute_commands), + ); + let moved = super::video_frames::moved_per_frame(&before, &after, GLASS_COUNTED); + eprintln!("WALK-MOVED {name} glass {shape} {place}: a frame: {moved}"); + } + } +} + /// The work counts a `WALK-READER` line prints, by name. const READER_COUNTS: [Count; 12] = [ ("render_passes_begun_instances", |c| { diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 7da8094f3..78ba17fcd 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2403; +pub const RUNTIME_VERSION: u32 = 2404; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 08f1505f6..7ed08a4c1 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3539,6 +3539,7 @@ field metal2vulkan-runtime::WorkCounts.render_passes_begun_inline pub render_pas field metal2vulkan-runtime::WorkCounts.render_passes_begun_inline_splits pub render_passes_begun_inline_splits: u64 field metal2vulkan-runtime::WorkCounts.render_passes_begun_instances pub render_passes_begun_instances: u64 field metal2vulkan-runtime::WorkCounts.render_passes_begun_resolves pub render_passes_begun_resolves: u64 +field metal2vulkan-runtime::WorkCounts.render_passes_continued pub render_passes_continued: u64 field metal2vulkan-runtime::WorkCounts.render_passes_made pub render_passes_made: u64 field metal2vulkan-runtime::WorkCounts.render_pipeline_create_nanos pub render_pipeline_create_nanos: u64 field metal2vulkan-runtime::WorkCounts.replay_log_bytes pub replay_log_bytes: u64