From 788aa9ee967d00c7d7ae34a9f4b29841fb08240b Mon Sep 17 00:00:00 2001 From: abdelrahman fahmy <104788132+Apdelrahman1911@users.noreply.github.com> Date: Sun, 6 Dec 2026 12:13:08 +0000 Subject: [PATCH 1/2] perf(runtime): pre-open feedback-hinted attachments (P3-1) and elide upload clears on full-clear first passes (P3-3) - P3-1: Add sticky Image.feedback_hint set in RenderCommandEncoder::feedback_moves(). On subsequent passes, single-mip/single-layer 2D non-storage color render targets with feedback_hint open directly in ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT and pre-seed encoder.moved, eliminating mid-pass vkCmdEndRendering + ALL_COMMANDS other_barriers + vkCmdBeginRendering(LOAD) (~5,500 interrupts/150s on Lavapipe). - P3-3: Track segment-0 full-extent Clear/DontCare single-2D first overwrites in Gpu.first_overwrites and transition those targets directly from UNDEFINED at PassStartBarriers. WorkState::close/take_uploads skips eager Upload::home GPU zeroing clears when no earlier command in the batch references the image (~2,400 clears / ~260 MB / ~1,450 texture_clear_barriers per 150s on Lavapipe), preserving full safety for dropped or reordered command buffers and LoadAction::Load textures. - Add Lavapipe device tests for both P3-1 and P3-3 and update draw_depth barrier count. --- crates/metal2vulkan-runtime/src/command.rs | 36 ++- crates/metal2vulkan-runtime/src/pass.rs | 5 + .../src/render_encoder.rs | 149 ++++++++++++- crates/metal2vulkan-runtime/src/submit.rs | 31 ++- crates/metal2vulkan-runtime/src/tests/draw.rs | 207 +++++++++++++++++- crates/metal2vulkan-runtime/src/texture.rs | 79 ++++++- 6 files changed, 483 insertions(+), 24 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/command.rs b/crates/metal2vulkan-runtime/src/command.rs index 997796627..153fa69d2 100644 --- a/crates/metal2vulkan-runtime/src/command.rs +++ b/crates/metal2vulkan-runtime/src/command.rs @@ -419,6 +419,11 @@ pub(crate) struct Gpu { /// boxed from its make. `None` where the type is host-coherent: one pointer, as each hand-off /// moves the command buffer by value. pub(crate) coherence: Option>, + /// Images whose very first use in segment 0 of this command buffer is a full-extent + /// `LoadAction::Clear` or `LoadAction::DontCare` render pass transitioning from `UNDEFINED`. + /// When the submit thread sees no earlier command in the same batch reading the image, it + /// skips the eager `Upload::home` clear and marks the image homed (`Image::claim_homed`). + pub(crate) first_overwrites: Vec>, } /// Whether `segments` hold nothing for the GPU: no commands, wait or signal ([`Gpu::is_empty`]). @@ -568,6 +573,7 @@ impl CommandBuffer { queries: Queries::default(), sets: crate::bound::Sets::default(), coherence, + first_overwrites: Vec::new(), }, handlers: Handlers { scheduled: Vec::new(), @@ -1705,6 +1711,33 @@ impl Building { self.gpu.coherence.as_deref_mut() } + /// Whether the encoder is still recording into the command buffer's first segment (segment 0). + pub(crate) fn is_first_segment(&self) -> bool { + self.gpu.segments.len() == 1 + } + + /// Whether any earlier command in this command buffer has already referenced `image`. + pub(crate) fn keeps_image(&self, image: &Arc) -> bool { + self.gpu + .kept + .textures + .iter() + .any(|texture| texture.image_of().is_some_and(|held| Arc::ptr_eq(held, image))) + || self.gpu.images.iter().any(|held| Arc::ptr_eq(held, image)) + } + + /// Records `image` as fully overwritten before any prior use in segment 0 of this command buffer. + pub(crate) fn record_first_overwrite(&mut self, image: Arc) { + if !self + .gpu + .first_overwrites + .iter() + .any(|held| Arc::ptr_eq(held, &image)) + { + self.gpu.first_overwrites.push(image); + } + } + /// A dispatch wrote: an indirect dispatch after it needs a barrier that reaches its /// argument read. pub(crate) fn wrote(&mut self) { @@ -2429,12 +2462,13 @@ pub(crate) fn retire( queries, sets, coherence: _, + first_overwrites, } = gpu; if let Some(recorder) = recorder { core.recorders.give_back(core, recorder); } ring.give_back(core); - drop((segments, blocks, images, fences, executed)); + drop((segments, blocks, images, fences, executed, first_overwrites)); queries.give_back(core); sets.give_back(core); kept.clear(); diff --git a/crates/metal2vulkan-runtime/src/pass.rs b/crates/metal2vulkan-runtime/src/pass.rs index a41cb5c2b..e78b6f69d 100644 --- a/crates/metal2vulkan-runtime/src/pass.rs +++ b/crates/metal2vulkan-runtime/src/pass.rs @@ -664,6 +664,11 @@ impl Target { self.layout != self.attachment.home } + /// The Vulkan load operation recorded for this attachment on the pass's first begin. + pub(crate) fn load_op(&self) -> vk::AttachmentLoadOp { + self.load + } + /// The colour the pass clears it to, as its rendering's load clears it: `None` for an /// attachment the pass loads or does not care for, and for the stencil attachment. pub(crate) fn clear_color(&self) -> Option { diff --git a/crates/metal2vulkan-runtime/src/render_encoder.rs b/crates/metal2vulkan-runtime/src/render_encoder.rs index 515c6de3b..ab1c88a4f 100644 --- a/crates/metal2vulkan-runtime/src/render_encoder.rs +++ b/crates/metal2vulkan-runtime/src/render_encoder.rs @@ -1023,7 +1023,7 @@ impl CommandBuffer { let mut scratch = building.take_render_scratch(); let colors = std::mem::take(&mut scratch.colors); match begin(&mut building, &core, descriptor, colors) { - Ok((pass, command, visibility)) => { + Ok((pass, command, visibility, pre_moved)) => { let [width, height] = pass.area; let raster = Raster { positions: pass.positions.is_some(), @@ -1094,7 +1094,7 @@ impl CommandBuffer { drew: false, pass_drew: false, owed: false, - moved: Vec::new(), + moved: pre_moved, shadowed: Vec::new(), shadow_slots: Vec::new(), facts, @@ -1123,8 +1123,125 @@ fn begin( core: &Arc, descriptor: &RenderPassDescriptor, colors: Vec>, -) -> Result<(Pass, vk::CommandBuffer, Option), Error> { - let pass = Pass::check(core, descriptor, colors)?; +) -> Result<(Pass, vk::CommandBuffer, Option, Vec), Error> { + let mut pass = Pass::check(core, descriptor, colors)?; + // P3-1: Single-mip, single-layer 2D non-storage color render targets previously moved into the + // feedback layout (`Image.feedback_hint`) begin directly in `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT` + // so the first feedback draw in subsequent passes needs no mid-pass `vkCmdEndRendering`. + let mut pre_moved = Vec::new(); + if core.attachment_reads && core.feedback_loop { + let looped = vk::ImageLayout::ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT; + let eligible: Vec = pass + .colors + .iter() + .flatten() + .filter_map(|t| { + let hazard = t.texture.hazard_id(); + let eligible = t.stand_in.is_none() + && t.texture.looped() + && t.texture.attachment_reads() + && t.texture.feedback_hint() + && !t.texture.has_storage() + && t.texture.is_single_2d() + && t.attachment.home != looped + && pass + .targets() + .filter(|other| other.texture.hazard_id() == hazard) + .count() + == 1 + && (!pass.resolving + || !pass + .resolves() + .any(|r| r.texture.hazard_id() == hazard)); + eligible.then_some(hazard) + }) + .collect(); + for t in pass.colors.iter_mut().flatten() { + let hazard = t.texture.hazard_id(); + if eligible.contains(&hazard) { + t.layout = looped; + pre_moved.push(Moved { + hazard, + image: t.attachment.image, + whole: t.texture.whole(), + home: t.attachment.home, + }); + } + } + } + // P3-3: Newly created single-mip/single-layer 2D textures whose very first use in segment 0 is + // a full-extent `CLEAR` or `DONT_CARE` pass covering all aspects transition directly from + // `UNDEFINED` here, letting `WorkState::close` skip their eager `Upload::home` clear. + let mut elided_zero: Vec = Vec::new(); + if building.is_first_segment() && pass.layers == 1 { + let overwrites = |load: vk::AttachmentLoadOp| { + matches!(load, vk::AttachmentLoadOp::CLEAR | vk::AttachmentLoadOp::DONT_CARE) + }; + let mut try_elide = |t: &Target, expected_aspects: vk::ImageAspectFlags| { + if t.stand_in.is_some() + || !t.texture.has_zero() + || t.texture.is_homed() + || !t.texture.is_single_2d() + || t.texture.image_aspects() != expected_aspects + || pass.area != t.attachment.extent + || pass.reach != t.attachment.extent + { + return; + } + let Some(image) = t.texture.image_arc() else { + return; + }; + if building.keeps_image(image) { + return; + } + let key = Arc::as_ptr(image) as usize; + let unique_target = pass + .targets() + .filter(|other| { + other + .texture + .image_arc() + .is_some_and(|held| Arc::as_ptr(held) as usize == key) + }) + .count() + == 1; + let unique_resolve = !pass.resolving + || !pass.resolves().any(|r| { + r.texture + .image_arc() + .is_some_and(|held| Arc::as_ptr(held) as usize == key) + }); + if unique_target && unique_resolve && !elided_zero.contains(&key) { + elided_zero.push(key); + building.record_first_overwrite(Arc::clone(image)); + } + }; + for t in pass.colors.iter().flatten() { + if overwrites(t.load_op()) { + try_elide(t, vk::ImageAspectFlags::COLOR); + } + } + match (&pass.depth, &pass.stencil) { + (Some(d), Some(s)) + if d.texture + .image_arc() + .zip(s.texture.image_arc()) + .is_some_and(|(di, si)| Arc::ptr_eq(di, si)) => + { + if overwrites(d.load_op()) && overwrites(s.load_op()) { + try_elide(d, vk::ImageAspectFlags::DEPTH | vk::ImageAspectFlags::STENCIL); + } + } + (depth, stencil) => { + if let Some(d) = depth.as_ref().filter(|d| overwrites(d.load_op())) { + try_elide(d, vk::ImageAspectFlags::DEPTH); + } + if let Some(s) = stencil.as_ref().filter(|s| overwrites(s.load_op())) { + try_elide(s, vk::ImageAspectFlags::STENCIL); + } + } + } + } // The attachments, and where the pass resolves the resolve textures, which the pass writes: // a pass that resolves nothing walks no resolve. let resolves = || { @@ -1195,11 +1312,22 @@ fn begin( building.overs_after(overs(), false); building.count(Metric::Passes); let mut away = building.take_pass_barriers(); - away.extend( - (pass.targets()) - .filter(|t| t.moves()) - .map(|t| t.barrier(t.attachment.home, t.layout)), - ); + for t in pass.targets() { + let elided = t + .texture + .image_arc() + .is_some_and(|image| elided_zero.contains(&(Arc::as_ptr(image) as usize))); + if elided { + away.push(layout_barrier( + t.attachment.image, + t.texture.whole(), + vk::ImageLayout::UNDEFINED, + t.layout, + )); + } else if t.moves() { + away.push(t.barrier(t.attachment.home, t.layout)); + } + } if pass.resolving { away.extend( (pass.resolves()) @@ -1263,7 +1391,7 @@ fn begin( if let Some(id) = first_discard { building.cancel_first_discard_lean(id); } - Ok((pass, command, visibility)) + Ok((pass, command, visibility, pre_moved)) } impl RenderCommandEncoder { @@ -2293,6 +2421,7 @@ impl RenderCommandEncoder { for t in self.pass.colors.iter_mut().flatten() { if (moves.iter()).any(|m| m.moved.hazard == t.texture.hazard_id()) { t.layout = looped; + t.texture.mark_feedback_hint(); } } // A read declaration that covers an attachment now held out of its home layout. diff --git a/crates/metal2vulkan-runtime/src/submit.rs b/crates/metal2vulkan-runtime/src/submit.rs index 448affb95..c0d9e29a7 100644 --- a/crates/metal2vulkan-runtime/src/submit.rs +++ b/crates/metal2vulkan-runtime/src/submit.rs @@ -81,7 +81,7 @@ use crate::staging::{At, Oldest, Region, Stage, Staging, REGION_LEN}; use crate::texture::{Homing, Image, OverCopy, TextureInner, TextureObject, Zeroing}; use crate::times; use ash::vk; -use std::collections::VecDeque; +use std::collections::{HashSet, VecDeque}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, Weak}; @@ -614,6 +614,11 @@ struct Batch { /// The first failed call recording a command buffer of moves that leads a segment of it /// (`crate::alias::stage`), which loses the device. lost: Option, + /// Images already referenced by earlier segments staged into this batch (`Arc::as_ptr` as `usize`). + seen_images: HashSet, + /// Un-homed images whose first use in this batch is a full-extent `Clear`/`DontCare` pass + /// transitioning from `UNDEFINED`, allowing `take_uploads` to skip their eager upload clear. + elided_homes: HashSet, } /// What a batch flushes before it is submitted, where the Shared type is not host-coherent @@ -1632,6 +1637,7 @@ impl WorkState { released: &AtomicU64, value: u64, through: u64, + elided_homes: Option<&HashSet>, ) -> Vec { let within = (self.sealed.iter()) .take_while(|upload| upload.number <= through) @@ -1661,6 +1667,10 @@ impl WorkState { } } for image in upload.homes.drain(..).filter_map(|home| home.upgrade()) { + if elided_homes.is_some_and(|set| set.contains(&(Arc::as_ptr(&image) as usize))) { + image.claim_homed(); + continue; + } // One an upload copied to or from was moved before its copy, and is held. if let Some(homing) = image.homing() { homes.push(homing); @@ -2040,6 +2050,8 @@ impl WorkState { handed: Vec::new(), flushes: None, lost: None, + seen_images: HashSet::new(), + elided_homes: HashSet::new(), }); if leads { group.run = group.run.saturating_add(run.unwrap_or(u64::MAX)); @@ -2050,6 +2062,17 @@ impl WorkState { group.unseen = 0; } group.unseen += 1; + for image in &pending.gpu.first_overwrites { + let key = Arc::as_ptr(image) as usize; + if !group.seen_images.contains(&key) { + group.elided_homes.insert(key); + } + } + } + for texture in &pending.gpu.kept.textures { + if let Some(image) = texture.image_of() { + group.seen_images.insert(Arc::as_ptr(image) as usize); + } } group.leans.join(&segment.overs); if let Some(coherence::Recorded { @@ -2263,7 +2286,7 @@ impl WorkState { .extend((batch.finished.iter()).map(|(_, pending, _)| (pending.seq, pending.value))); (self.carried) .extend((batch.finished.iter()).map(|(_, pending, _)| (pending.seq, pending.value))); - let uploads = self.take_uploads(core, released, value, through); + let uploads = self.take_uploads(core, released, value, through, Some(&batch.elided_homes)); Some((value, uploads, batch)) } @@ -2586,7 +2609,7 @@ fn pass<'a>(core: &'a Core, mut state: MutexGuard<'a, WorkState>) -> MutexGuard< } if state.flush > 0 && !sent { let value = state.progress + 1; - let uploads = state.take_uploads(core, &work.released, value, 0); + let uploads = state.take_uploads(core, &work.released, value, 0, None); if !uploads.is_empty() { state.progress = value; drop(state); @@ -2658,6 +2681,8 @@ impl Batch { handed: Vec::new(), flushes: None, lost: None, + seen_images: HashSet::new(), + elided_homes: HashSet::new(), } } } diff --git a/crates/metal2vulkan-runtime/src/tests/draw.rs b/crates/metal2vulkan-runtime/src/tests/draw.rs index 2c50b7a4a..181f934d3 100644 --- a/crates/metal2vulkan-runtime/src/tests/draw.rs +++ b/crates/metal2vulkan-runtime/src/tests/draw.rs @@ -2887,12 +2887,11 @@ pub(crate) mod on_device { let queue = device.new_command_queue(4).expect("a queue"); let draw = |result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}")); let counters = device.counters(); - // The first command buffer's submission records two barriers more than the second's: - // its upload's, which moves the two new images from undefined to their home layouts - // in one and ends in the other, and one more where it clears a new image the runtime - // placed between its move and its home. + // Both new single-2D attachments are fully cleared by the first pass (`LoadAction::Clear`), + // so `WorkState::close` elides the eager `Upload::home` clears and upload barriers: both + // passes record the same 3 barriers (pass start, pass home, segment end). for (load, first, color_of, barriers) in [ - (crate::LoadAction::Clear, 3, BLUE, 5), + (crate::LoadAction::Clear, 3, BLUE, 3), (crate::LoadAction::Load, 6, WHITE, 3), ] { settled(&device); @@ -2907,7 +2906,11 @@ pub(crate) mod on_device { encoder.end_encoding(); run(name, &command_buffer); let after = counters.metrics(); - let cleared = after.texture_clears > before.texture_clears; + assert_eq!( + after.texture_clears - before.texture_clears, + 0, + "{name}: {load:?}: full-extent clear elides eager upload zeroing" + ); assert_eq!( ( after.submissions - before.submissions, @@ -2915,9 +2918,8 @@ pub(crate) mod on_device { after.passes - before.passes, after.bytes_copied - before.bytes_copied, ), - (1, barriers + u64::from(cleared), 1, 0), - "{name}: {load:?}: submissions, barriers (the first command buffer's upload \ - moves the new images from undefined to home and ends), passes, bytes copied" + (1, barriers, 1, 0), + "{name}: {load:?}: submissions, barriers, passes, bytes copied" ); assert_eq!(read(&color, 4), texels(|_, _| color_of), "{name}: {load:?}"); if depth.unit().is_some() { @@ -5213,6 +5215,193 @@ define <4 x float> @fragment(<4 x float> %rgba) { }); } + /// P3-1: Once a single-mip, single-layer 2D non-storage colour target has moved into the + /// attachment feedback layout in an earlier pass (`Image.feedback_hint`), subsequent passes + /// begin directly in `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT` with zero mid-pass + /// `rendering_interrupts` and zero `other_barriers` on the first feedback draw, while still + /// ordering a later feedback draw after a prior write via `memory_barrier()`. + #[test] + fn every_device_reuses_feedback_layout_on_subsequent_passes_without_interrupt() { + let Some(library) = examples() else { + return; + }; + let plain = descriptor(&library, "colored_fragment", PixelFormat::RGBA8Unorm); + let own = descriptor(&library, "own_pixel_fragment", PixelFormat::RGBA8Unorm); + each_device("feedback_hint", |name, _, device| { + if !device.core().feedback_loop { + println!("{name}: no feedback loop"); + return; + } + (device.grant_indices(IndexClass::Texture, 4096, 2)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let plain = state(name, &device, &plain); + let reading = state(name, &device, &own); + let mut buffers = Buffers::new(&device); + let whole = [-1.0, -1.0, 3.0, -1.0, -1.0, 3.0]; + let positions = buffers.of(&device, &floats(&[whole; 2].concat())); + let colors: Vec = [BLUE, [0.0, 1.0, 0.0, 0.0]] + .iter() + .flat_map(|c| [*c; 3].concat()) + .collect(); + let colors = buffers.of(&device, &floats(&colors)); + let queue = device.new_command_queue(4).expect("a queue"); + let color = readable(&device, PixelFormat::RGBA8Unorm, 1, 4096); + let counters = device.counters(); + + // Pass 1: first feedback read triggers feedback_moves and sets `feedback_hint`. + let cb1 = queue.command_buffer().expect("a command buffer"); + let mut enc1 = (cb1.render_command_encoder(&pass(&color, None))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + enc1.set_vertex_buffer(Some(&positions), 0, 0).unwrap(); + enc1.set_vertex_buffer(Some(&colors), 0, 1).unwrap(); + enc1.set_fragment_texture(Some(&color), 0).unwrap(); + enc1.set_render_pipeline_state(&reading).unwrap(); + enc1.draw_primitives(PrimitiveType::Triangle, 3, 3, 1, 0) + .unwrap(); + enc1.end_encoding(); + run(name, &cb1); + assert_eq!( + read(&color, 4), + texels(|_, _| [0.0, 1.0, 0.0, 1.0]), + "{name}: pass 1 clear black + green" + ); + + // Pass 2: target opens directly in ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT -> 0 interrupts. + settled(&device); + let before = counters.metrics(); + let mut load_pass = pass(&color, None); + load_pass.color_attachments[0].load_action = crate::LoadAction::Load; + let cb2 = queue.command_buffer().expect("a command buffer"); + let mut enc2 = (cb2.render_command_encoder(&load_pass)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + enc2.set_vertex_buffer(Some(&positions), 0, 0).unwrap(); + enc2.set_vertex_buffer(Some(&colors), 0, 1).unwrap(); + enc2.set_fragment_texture(Some(&color), 0).unwrap(); + enc2.set_render_pipeline_state(&reading).unwrap(); + enc2.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) + .unwrap(); + enc2.end_encoding(); + run(name, &cb2); + let after = counters.metrics(); + assert_eq!( + ( + after.rendering_interrupts - before.rendering_interrupts, + after.other_barriers - before.other_barriers, + after.attachment_loop_reads - before.attachment_loop_reads, + ), + (0, 0, 1), + "{name}: pass 2 feedback read needs zero interrupts and zero other_barriers" + ); + assert_eq!( + read(&color, 4), + texels(|_, _| [0.0, 1.0, 1.0, 1.0]), + "{name}: pass 2 loaded green + blue" + ); + + // Pass 3: prior draw + memory_barrier + feedback draw still orders via `ordered()`. + settled(&device); + let before3 = counters.metrics(); + let cb3 = queue.command_buffer().expect("a command buffer"); + let mut enc3 = (cb3.render_command_encoder(&pass(&color, None))) + .unwrap_or_else(|error| panic!("{name}: {error}")); + enc3.set_vertex_buffer(Some(&positions), 0, 0).unwrap(); + enc3.set_vertex_buffer(Some(&colors), 0, 1).unwrap(); + enc3.set_fragment_texture(Some(&color), 0).unwrap(); + enc3.set_render_pipeline_state(&plain).unwrap(); + enc3.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) + .unwrap(); + enc3.memory_barrier().unwrap(); + enc3.set_render_pipeline_state(&reading).unwrap(); + enc3.draw_primitives(PrimitiveType::Triangle, 3, 3, 1, 0) + .unwrap(); + enc3.end_encoding(); + run(name, &cb3); + let after3 = counters.metrics(); + assert_eq!( + ( + after3.rendering_interrupts - before3.rendering_interrupts, + after3.other_barriers - before3.other_barriers, + ), + (1, 1), + "{name}: pass 3 orders read after prior draw with exactly one ordered() interrupt" + ); + assert_eq!( + read(&color, 4), + texels(|_, _| [0.0, 1.0, 1.0, 1.0]), + "{name}: pass 3 blue + green" + ); + }); + } + + /// P3-3: A newly created single-2D texture whose very first pass clears the whole extent + /// elides the eager `Upload::home` GPU clear (`texture_clears == 0`), while a fresh texture + /// whose first pass uses `LoadAction::Load` still zeroes first. + #[test] + fn every_device_elides_initial_texture_clear_when_first_pass_clears_whole_image() { + each_device("lazy_texture_clear", |name, _, device| { + let counters = device.counters(); + let queue = device.new_command_queue(4).expect("a queue"); + + // Case 1: full-extent `LoadAction::Clear` elides `Upload::home` clear. + settled(&device); + let before_clear = counters.metrics(); + let cleared = target( + &device, + PixelFormat::RGBA8Unorm, + TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, + ); + let mut clear_desc = pass(&cleared, None); + clear_desc.color_attachments[0].clear_color = + crate::ClearColor::new(0.0, 0.0, 1.0, 1.0); + let cb1 = queue.command_buffer().expect("a command buffer"); + cb1.render_command_encoder(&clear_desc) + .unwrap_or_else(|error| panic!("{name}: {error}")) + .end_encoding(); + run(name, &cb1); + let after_clear = counters.metrics(); + assert_eq!( + ( + after_clear.texture_clears - before_clear.texture_clears, + after_clear.texture_clear_barriers - before_clear.texture_clear_barriers, + ), + (0, 0), + "{name}: full-extent Clear pass elides upload clear" + ); + assert_eq!( + read(&cleared, 4), + texels(|_, _| BLUE), + "{name}: cleared pixels written cleanly from UNDEFINED" + ); + + // Case 2: `LoadAction::Load` on a fresh texture still runs the initial zero clear. + settled(&device); + let before_load = counters.metrics(); + let loaded = target( + &device, + PixelFormat::RGBA8Unorm, + TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ, + ); + let mut load_desc = pass(&loaded, None); + load_desc.color_attachments[0].load_action = crate::LoadAction::Load; + let cb2 = queue.command_buffer().expect("a command buffer"); + cb2.render_command_encoder(&load_desc) + .unwrap_or_else(|error| panic!("{name}: {error}")) + .end_encoding(); + run(name, &cb2); + let after_load = counters.metrics(); + assert_eq!( + after_load.texture_clears - before_load.texture_clears, + 1, + "{name}: LoadAction::Load still zeroes the fresh texture first" + ); + assert_eq!( + read(&loaded, 4), + texels(|_, _| [0.0, 0.0, 0.0, 0.0]), + "{name}: loaded fresh texture reads exact zeros" + ); + }); + } + /// Where device creation enabled the attachment feedback loop, every render pipeline takes the /// loop's colour flag, `VK_PIPELINE_CREATE_COLOR_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT`: that of a /// fragment function that reads no texture as much as that of one that reads its pass's diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index c03e34630..bd161b924 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -598,6 +598,10 @@ pub(crate) struct Image { /// exported surface's plane in place is moved by its making's command buffer instead, on the /// submit thread ([`making_move`](Self::making_move)). homed: AtomicBool, + /// Sticky hint set once a render pass moves this image into `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT` + /// (`RenderCommandEncoder::feedback_moves`), allowing subsequent single-2D passes to begin + /// directly in the feedback layout and avoid mid-pass `vkCmdEndRendering` interrupts. + feedback_hint: AtomicBool, /// How the move home zeroes it, for an image the runtime places for a texture of its own /// (`Source::Plain` and `Source::Managed`); `None` for every other image. zero: Option, @@ -1089,6 +1093,13 @@ impl Image { self.homed.store(false, Ordering::Relaxed); } + /// Marks the image as moved out of its initial layout by a full-extent overwrite pass in the + /// submitted command buffer so [`WorkState::take_uploads`](crate::submit) skips the eager + /// upload clear and move home. + pub(crate) fn claim_homed(&self) -> bool { + self.homed.swap(true, Ordering::Relaxed) + } + /// The layout a copy names the image in, for `transfer`, its role's transfer layout: home, /// general, for an image whose move home starts preinitialized (a linear image over a buffer /// in place), which stays in a host-accessible layout through every use, copies included, so @@ -1158,6 +1169,7 @@ impl Image { stand_ins: None, first: vk::ImageLayout::UNDEFINED, homed: AtomicBool::new(false), + feedback_hint: AtomicBool::new(false), released: Mutex::new(None), zero: None, foreign: None, @@ -1791,6 +1803,7 @@ impl Device { first: vk::ImageLayout::UNDEFINED, // No move home until the consumer acquires it. homed: AtomicBool::new(true), + feedback_hint: AtomicBool::new(false), released: Mutex::new(None), foreign: None, zero: None, @@ -2126,6 +2139,7 @@ impl Device { foreign, // Unmoved, it owes the uploads no move (`crate::alias`). homed: AtomicBool::new(unmoved), + feedback_hint: AtomicBool::new(false), released: Mutex::new(None), zero, drawable: None, @@ -4814,7 +4828,7 @@ impl TextureInner { } /// Its image: its own, or a view's parent's; `None` for a texture buffer. - fn image_of(&self) -> Option<&Arc> { + pub(crate) fn image_of(&self) -> Option<&Arc> { match &self.body { Body::Image(image) => Some(image), Body::Texels(_) => None, @@ -5832,6 +5846,68 @@ pub(crate) trait TextureObject { self.object().image_of().is_some_and(|image| image.looped()) } + /// Sticky hint indicating a prior render pass already moved this image to the feedback layout. + fn feedback_hint(&self) -> bool { + self.object() + .image_of() + .is_some_and(|image| image.feedback_hint.load(Ordering::Relaxed)) + } + + /// Records that a render pass moved this image into `ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT`. + fn mark_feedback_hint(&self) { + if let Some(image) = self.object().image_of() { + image.feedback_hint.store(true, Ordering::Relaxed); + } + } + + /// Whether the underlying image carries a storage view (whose layout is `GENERAL`). + fn has_storage(&self) -> bool { + self.object() + .image_of() + .is_some_and(|image| image.storage.is_some()) + } + + /// Whether the underlying root image is a single-mip, single-layer 2D (or 2D multisample) image. + fn is_single_2d(&self) -> bool { + let root = match &self.object().view { + Some(view) => &view.parent.descriptor, + None => &self.object().descriptor, + }; + root.mipmap_level_count == 1 + && root.array_length == 1 + && root.depth == 1 + && matches!( + root.texture_type, + TextureType::Type2D | TextureType::Type2DMultisample + ) + } + + /// Whether the underlying image queues an initial zeroing clear on its first move home. + fn has_zero(&self) -> bool { + self.object() + .image_of() + .is_some_and(|image| image.zero.is_some()) + } + + /// Whether the underlying image has already been moved out of its initial layout. + fn is_homed(&self) -> bool { + self.object() + .image_of() + .is_some_and(|image| image.homed.load(Ordering::Relaxed)) + } + + /// Every aspect of the underlying image's format. + fn image_aspects(&self) -> vk::ImageAspectFlags { + self.object() + .image_of() + .map_or(vk::ImageAspectFlags::empty(), |image| image.aspects) + } + + /// The underlying image handle, or `None` for a texture buffer. + fn image_arc(&self) -> Option<&Arc> { + self.object().image_of() + } + /// Its resource id while a draw reads an attachment through it: its second element's, at its /// index plus [`TEXTURES`](crate::floor::TEXTURES), with its own word. Nil for a /// texture no shader reaches. @@ -7548,6 +7624,7 @@ impl Device { // A Direct3D 11 plane owes no move: each acquire takes it from the general layout // (`Image::handed`). An exported one's is its making's (`Image::making_move`). homed: AtomicBool::new(general), + feedback_hint: AtomicBool::new(false), released: Mutex::new(None), foreign: None, zero: None, From f3db5316b3e025d399828990c6bbdc38eed98eae Mon Sep 17 00:00:00 2001 From: abdelrahman fahmy <104788132+Apdelrahman1911@users.noreply.github.com> Date: Sun, 6 Dec 2026 12:19:00 +0000 Subject: [PATCH 2/2] fix: use kept.textures.iter() and Vec for hazard IDs --- crates/metal2vulkan-runtime/src/render_encoder.rs | 2 +- crates/metal2vulkan-runtime/src/submit.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/render_encoder.rs b/crates/metal2vulkan-runtime/src/render_encoder.rs index ab1c88a4f..5600cacf4 100644 --- a/crates/metal2vulkan-runtime/src/render_encoder.rs +++ b/crates/metal2vulkan-runtime/src/render_encoder.rs @@ -1131,7 +1131,7 @@ fn begin( let mut pre_moved = Vec::new(); if core.attachment_reads && core.feedback_loop { let looped = vk::ImageLayout::ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT; - let eligible: Vec = pass + let eligible: Vec = pass .colors .iter() .flatten() diff --git a/crates/metal2vulkan-runtime/src/submit.rs b/crates/metal2vulkan-runtime/src/submit.rs index c0d9e29a7..a27e765a0 100644 --- a/crates/metal2vulkan-runtime/src/submit.rs +++ b/crates/metal2vulkan-runtime/src/submit.rs @@ -2069,7 +2069,7 @@ impl WorkState { } } } - for texture in &pending.gpu.kept.textures { + for texture in pending.gpu.kept.textures.iter() { if let Some(image) = texture.image_of() { group.seen_images.insert(Arc::as_ptr(image) as usize); }